clang 20.0.0git
SemaDecl.cpp
Go to the documentation of this file.
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"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
36#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
37#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
38#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
41#include "clang/Sema/DeclSpec.h"
44#include "clang/Sema/Lookup.h"
46#include "clang/Sema/Scope.h"
48#include "clang/Sema/SemaCUDA.h"
49#include "clang/Sema/SemaHLSL.h"
51#include "clang/Sema/SemaObjC.h"
53#include "clang/Sema/SemaPPC.h"
56#include "clang/Sema/SemaWasm.h"
57#include "clang/Sema/Template.h"
58#include "llvm/ADT/STLForwardCompat.h"
59#include "llvm/ADT/SmallString.h"
60#include "llvm/ADT/StringExtras.h"
61#include "llvm/TargetParser/Triple.h"
62#include <algorithm>
63#include <cstring>
64#include <optional>
65#include <unordered_map>
66
67using namespace clang;
68using namespace sema;
69
71 if (OwnedType) {
72 Decl *Group[2] = { OwnedType, Ptr };
74 }
75
77}
78
79namespace {
80
81class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
82 public:
83 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
84 bool AllowTemplates = false,
85 bool AllowNonTemplates = true)
86 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
87 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
88 WantExpressionKeywords = false;
89 WantCXXNamedCasts = false;
90 WantRemainingKeywords = false;
91 }
92
93 bool ValidateCandidate(const TypoCorrection &candidate) override {
94 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
95 if (!AllowInvalidDecl && ND->isInvalidDecl())
96 return false;
97
99 return AllowTemplates;
100
101 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
102 if (!IsType)
103 return false;
104
105 if (AllowNonTemplates)
106 return true;
107
108 // An injected-class-name of a class template (specialization) is valid
109 // as a template or as a non-template.
110 if (AllowTemplates) {
111 auto *RD = dyn_cast<CXXRecordDecl>(ND);
112 if (!RD || !RD->isInjectedClassName())
113 return false;
114 RD = cast<CXXRecordDecl>(RD->getDeclContext());
115 return RD->getDescribedClassTemplate() ||
116 isa<ClassTemplateSpecializationDecl>(RD);
117 }
118
119 return false;
120 }
121
122 return !WantClassName && candidate.isKeyword();
123 }
124
125 std::unique_ptr<CorrectionCandidateCallback> clone() override {
126 return std::make_unique<TypeNameValidatorCCC>(*this);
127 }
128
129 private:
130 bool AllowInvalidDecl;
131 bool WantClassName;
132 bool AllowTemplates;
133 bool AllowNonTemplates;
134};
135
136} // end anonymous namespace
137
138namespace {
139enum class UnqualifiedTypeNameLookupResult {
140 NotFound,
141 FoundNonType,
142 FoundType
143};
144} // end anonymous namespace
145
146/// Tries to perform unqualified lookup of the type decls in bases for
147/// dependent class.
148/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
149/// type decl, \a FoundType if only type decls are found.
150static UnqualifiedTypeNameLookupResult
152 SourceLocation NameLoc,
153 const CXXRecordDecl *RD) {
154 if (!RD->hasDefinition())
155 return UnqualifiedTypeNameLookupResult::NotFound;
156 // Look for type decls in base classes.
157 UnqualifiedTypeNameLookupResult FoundTypeDecl =
158 UnqualifiedTypeNameLookupResult::NotFound;
159 for (const auto &Base : RD->bases()) {
160 const CXXRecordDecl *BaseRD = nullptr;
161 if (auto *BaseTT = Base.getType()->getAs<TagType>())
162 BaseRD = BaseTT->getAsCXXRecordDecl();
163 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
164 // Look for type decls in dependent base classes that have known primary
165 // templates.
166 if (!TST || !TST->isDependentType())
167 continue;
168 auto *TD = TST->getTemplateName().getAsTemplateDecl();
169 if (!TD)
170 continue;
171 if (auto *BasePrimaryTemplate =
172 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
173 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
174 BaseRD = BasePrimaryTemplate;
175 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
177 CTD->findPartialSpecialization(Base.getType()))
178 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
179 BaseRD = PS;
180 }
181 }
182 }
183 if (BaseRD) {
184 for (NamedDecl *ND : BaseRD->lookup(&II)) {
185 if (!isa<TypeDecl>(ND))
186 return UnqualifiedTypeNameLookupResult::FoundNonType;
187 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
188 }
189 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
190 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
191 case UnqualifiedTypeNameLookupResult::FoundNonType:
192 return UnqualifiedTypeNameLookupResult::FoundNonType;
193 case UnqualifiedTypeNameLookupResult::FoundType:
194 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
195 break;
196 case UnqualifiedTypeNameLookupResult::NotFound:
197 break;
198 }
199 }
200 }
201 }
202
203 return FoundTypeDecl;
204}
205
207 const IdentifierInfo &II,
208 SourceLocation NameLoc) {
209 // Lookup in the parent class template context, if any.
210 const CXXRecordDecl *RD = nullptr;
211 UnqualifiedTypeNameLookupResult FoundTypeDecl =
212 UnqualifiedTypeNameLookupResult::NotFound;
213 for (DeclContext *DC = S.CurContext;
214 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
215 DC = DC->getParent()) {
216 // Look for type decls in dependent base classes that have known primary
217 // templates.
218 RD = dyn_cast<CXXRecordDecl>(DC);
219 if (RD && RD->getDescribedClassTemplate())
220 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
221 }
222 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
223 return nullptr;
224
225 // We found some types in dependent base classes. Recover as if the user
226 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
227 // lookup during template instantiation.
228 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
229
230 ASTContext &Context = S.Context;
231 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
232 cast<Type>(Context.getRecordType(RD)));
233 QualType T =
235
236 CXXScopeSpec SS;
237 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
238
239 TypeLocBuilder Builder;
240 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
241 DepTL.setNameLoc(NameLoc);
243 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
244 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
245}
246
247/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
249 SourceLocation NameLoc,
250 bool WantNontrivialTypeSourceInfo = true) {
251 switch (T->getTypeClass()) {
252 case Type::DeducedTemplateSpecialization:
253 case Type::Enum:
254 case Type::InjectedClassName:
255 case Type::Record:
256 case Type::Typedef:
257 case Type::UnresolvedUsing:
258 case Type::Using:
259 break;
260 // These can never be qualified so an ElaboratedType node
261 // would carry no additional meaning.
262 case Type::ObjCInterface:
263 case Type::ObjCTypeParam:
264 case Type::TemplateTypeParm:
265 return ParsedType::make(T);
266 default:
267 llvm_unreachable("Unexpected Type Class");
268 }
269
270 if (!SS || SS->isEmpty())
272 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
273
275 if (!WantNontrivialTypeSourceInfo)
276 return ParsedType::make(ElTy);
277
278 TypeLocBuilder Builder;
279 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
280 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
283 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
284}
285
287 Scope *S, CXXScopeSpec *SS, bool isClassName,
288 bool HasTrailingDot, ParsedType ObjectTypePtr,
289 bool IsCtorOrDtorName,
290 bool WantNontrivialTypeSourceInfo,
291 bool IsClassTemplateDeductionContext,
292 ImplicitTypenameContext AllowImplicitTypename,
293 IdentifierInfo **CorrectedII) {
294 // FIXME: Consider allowing this outside C++1z mode as an extension.
295 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
296 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
297 !isClassName && !HasTrailingDot;
298
299 // Determine where we will perform name lookup.
300 DeclContext *LookupCtx = nullptr;
301 if (ObjectTypePtr) {
302 QualType ObjectType = ObjectTypePtr.get();
303 if (ObjectType->isRecordType())
304 LookupCtx = computeDeclContext(ObjectType);
305 } else if (SS && SS->isNotEmpty()) {
306 LookupCtx = computeDeclContext(*SS, false);
307
308 if (!LookupCtx) {
309 if (isDependentScopeSpecifier(*SS)) {
310 // C++ [temp.res]p3:
311 // A qualified-id that refers to a type and in which the
312 // nested-name-specifier depends on a template-parameter (14.6.2)
313 // shall be prefixed by the keyword typename to indicate that the
314 // qualified-id denotes a type, forming an
315 // elaborated-type-specifier (7.1.5.3).
316 //
317 // We therefore do not perform any name lookup if the result would
318 // refer to a member of an unknown specialization.
319 // In C++2a, in several contexts a 'typename' is not required. Also
320 // allow this as an extension.
321 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
322 !isClassName && !IsCtorOrDtorName)
323 return nullptr;
324 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
325 if (IsImplicitTypename) {
326 SourceLocation QualifiedLoc = SS->getRange().getBegin();
328 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
329 else
330 Diag(QualifiedLoc, diag::ext_implicit_typename)
331 << SS->getScopeRep() << II.getName()
332 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
333 }
334
335 // We know from the grammar that this name refers to a type,
336 // so build a dependent node to describe the type.
337 if (WantNontrivialTypeSourceInfo)
338 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
339 (ImplicitTypenameContext)IsImplicitTypename)
340 .get();
341
344 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
346 SourceLocation(), QualifierLoc, II, NameLoc);
347 return ParsedType::make(T);
348 }
349
350 return nullptr;
351 }
352
353 if (!LookupCtx->isDependentContext() &&
354 RequireCompleteDeclContext(*SS, LookupCtx))
355 return nullptr;
356 }
357
358 // In the case where we know that the identifier is a class name, we know that
359 // it is a type declaration (struct, class, union or enum) so we can use tag
360 // name lookup.
361 //
362 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
363 // the component name of the type-name or simple-template-id is type-only.
364 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
365 LookupResult Result(*this, &II, NameLoc, Kind);
366 if (LookupCtx) {
367 // Perform "qualified" name lookup into the declaration context we
368 // computed, which is either the type of the base of a member access
369 // expression or the declaration context associated with a prior
370 // nested-name-specifier.
371 LookupQualifiedName(Result, LookupCtx);
372
373 if (ObjectTypePtr && Result.empty()) {
374 // C++ [basic.lookup.classref]p3:
375 // If the unqualified-id is ~type-name, the type-name is looked up
376 // in the context of the entire postfix-expression. If the type T of
377 // the object expression is of a class type C, the type-name is also
378 // looked up in the scope of class C. At least one of the lookups shall
379 // find a name that refers to (possibly cv-qualified) T.
380 LookupName(Result, S);
381 }
382 } else {
383 // Perform unqualified name lookup.
384 LookupName(Result, S);
385
386 // For unqualified lookup in a class template in MSVC mode, look into
387 // dependent base classes where the primary class template is known.
388 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
389 if (ParsedType TypeInBase =
390 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
391 return TypeInBase;
392 }
393 }
394
395 NamedDecl *IIDecl = nullptr;
396 UsingShadowDecl *FoundUsingShadow = nullptr;
397 switch (Result.getResultKind()) {
399 if (CorrectedII) {
400 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
401 AllowDeducedTemplate);
402 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
403 S, SS, CCC, CTK_ErrorRecovery);
404 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
405 TemplateTy Template;
406 bool MemberOfUnknownSpecialization;
408 TemplateName.setIdentifier(NewII, NameLoc);
410 CXXScopeSpec NewSS, *NewSSPtr = SS;
411 if (SS && NNS) {
412 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
413 NewSSPtr = &NewSS;
414 }
415 if (Correction && (NNS || NewII != &II) &&
416 // Ignore a correction to a template type as the to-be-corrected
417 // identifier is not a template (typo correction for template names
418 // is handled elsewhere).
419 !(getLangOpts().CPlusPlus && NewSSPtr &&
420 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
421 Template, MemberOfUnknownSpecialization))) {
422 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
423 isClassName, HasTrailingDot, ObjectTypePtr,
424 IsCtorOrDtorName,
425 WantNontrivialTypeSourceInfo,
426 IsClassTemplateDeductionContext);
427 if (Ty) {
428 diagnoseTypo(Correction,
429 PDiag(diag::err_unknown_type_or_class_name_suggest)
430 << Result.getLookupName() << isClassName);
431 if (SS && NNS)
432 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
433 *CorrectedII = NewII;
434 return Ty;
435 }
436 }
437 }
438 Result.suppressDiagnostics();
439 return nullptr;
441 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
443 SS->getScopeRep(), &II);
444 TypeLocBuilder TLB;
448 TL.setNameLoc(NameLoc);
450 }
451 [[fallthrough]];
454 Result.suppressDiagnostics();
455 return nullptr;
456
458 // Recover from type-hiding ambiguities by hiding the type. We'll
459 // do the lookup again when looking for an object, and we can
460 // diagnose the error then. If we don't do this, then the error
461 // about hiding the type will be immediately followed by an error
462 // that only makes sense if the identifier was treated like a type.
463 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
464 Result.suppressDiagnostics();
465 return nullptr;
466 }
467
468 // Look to see if we have a type anywhere in the list of results.
469 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
470 Res != ResEnd; ++Res) {
471 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
472 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
473 RealRes) ||
474 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
475 if (!IIDecl ||
476 // Make the selection of the recovery decl deterministic.
477 RealRes->getLocation() < IIDecl->getLocation()) {
478 IIDecl = RealRes;
479 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
480 }
481 }
482 }
483
484 if (!IIDecl) {
485 // None of the entities we found is a type, so there is no way
486 // to even assume that the result is a type. In this case, don't
487 // complain about the ambiguity. The parser will either try to
488 // perform this lookup again (e.g., as an object name), which
489 // will produce the ambiguity, or will complain that it expected
490 // a type name.
491 Result.suppressDiagnostics();
492 return nullptr;
493 }
494
495 // We found a type within the ambiguous lookup; diagnose the
496 // ambiguity and then return that type. This might be the right
497 // answer, or it might not be, but it suppresses any attempt to
498 // perform the name lookup again.
499 break;
500
502 IIDecl = Result.getFoundDecl();
503 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
504 break;
505 }
506
507 assert(IIDecl && "Didn't find decl");
508
509 QualType T;
510 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
511 // C++ [class.qual]p2: A lookup that would find the injected-class-name
512 // instead names the constructors of the class, except when naming a class.
513 // This is ill-formed when we're not actually forming a ctor or dtor name.
514 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
515 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
516 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
517 FoundRD->isInjectedClassName() &&
518 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
519 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
520 << &II << /*Type*/1;
521
522 DiagnoseUseOfDecl(IIDecl, NameLoc);
523
525 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
526 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
527 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
528 if (!HasTrailingDot)
530 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
531 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
532 (void)DiagnoseUseOfDecl(UD, NameLoc);
533 // Recover with 'int'
535 } else if (AllowDeducedTemplate) {
536 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
537 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
539 SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
540 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
542 false);
543 // Don't wrap in a further UsingType.
544 FoundUsingShadow = nullptr;
545 }
546 }
547
548 if (T.isNull()) {
549 // If it's not plausibly a type, suppress diagnostics.
550 Result.suppressDiagnostics();
551 return nullptr;
552 }
553
554 if (FoundUsingShadow)
555 T = Context.getUsingType(FoundUsingShadow, T);
556
557 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
558}
559
560// Builds a fake NNS for the given decl context.
561static NestedNameSpecifier *
563 for (;; DC = DC->getLookupParent()) {
564 DC = DC->getPrimaryContext();
565 auto *ND = dyn_cast<NamespaceDecl>(DC);
566 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
567 return NestedNameSpecifier::Create(Context, nullptr, ND);
568 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
569 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
570 RD->getTypeForDecl());
571 else if (isa<TranslationUnitDecl>(DC))
573 }
574 llvm_unreachable("something isn't in TU scope?");
575}
576
577/// Find the parent class with dependent bases of the innermost enclosing method
578/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
579/// up allowing unqualified dependent type names at class-level, which MSVC
580/// correctly rejects.
581static const CXXRecordDecl *
583 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
584 DC = DC->getPrimaryContext();
585 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
586 if (MD->getParent()->hasAnyDependentBases())
587 return MD->getParent();
588 }
589 return nullptr;
590}
591
593 SourceLocation NameLoc,
594 bool IsTemplateTypeArg) {
595 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
596
597 NestedNameSpecifier *NNS = nullptr;
598 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
599 // If we weren't able to parse a default template argument, delay lookup
600 // until instantiation time by making a non-dependent DependentTypeName. We
601 // pretend we saw a NestedNameSpecifier referring to the current scope, and
602 // lookup is retried.
603 // FIXME: This hurts our diagnostic quality, since we get errors like "no
604 // type named 'Foo' in 'current_namespace'" when the user didn't write any
605 // name specifiers.
607 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
608 } else if (const CXXRecordDecl *RD =
610 // Build a DependentNameType that will perform lookup into RD at
611 // instantiation time.
612 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
613 RD->getTypeForDecl());
614
615 // Diagnose that this identifier was undeclared, and retry the lookup during
616 // template instantiation.
617 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
618 << RD;
619 } else {
620 // This is not a situation that we should recover from.
621 return ParsedType();
622 }
623
624 QualType T =
626
627 // Build type location information. We synthesized the qualifier, so we have
628 // to build a fake NestedNameSpecifierLoc.
629 NestedNameSpecifierLocBuilder NNSLocBuilder;
630 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
631 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
632
633 TypeLocBuilder Builder;
634 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
635 DepTL.setNameLoc(NameLoc);
637 DepTL.setQualifierLoc(QualifierLoc);
638 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
639}
640
642 // Do a tag name lookup in this scope.
643 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
644 LookupName(R, S, false);
647 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
648 switch (TD->getTagKind()) {
654 return DeclSpec::TST_union;
656 return DeclSpec::TST_class;
658 return DeclSpec::TST_enum;
659 }
660 }
661
663}
664
666 if (CurContext->isRecord()) {
668 return true;
669
670 const Type *Ty = SS->getScopeRep()->getAsType();
671
672 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
673 for (const auto &Base : RD->bases())
674 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
675 return true;
676 return S->isFunctionPrototypeScope();
677 }
678 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
679}
680
682 SourceLocation IILoc,
683 Scope *S,
684 CXXScopeSpec *SS,
685 ParsedType &SuggestedType,
686 bool IsTemplateName) {
687 // Don't report typename errors for editor placeholders.
688 if (II->isEditorPlaceholder())
689 return;
690 // We don't have anything to suggest (yet).
691 SuggestedType = nullptr;
692
693 // There may have been a typo in the name of the type. Look up typo
694 // results, in case we have something that we can suggest.
695 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
696 /*AllowTemplates=*/IsTemplateName,
697 /*AllowNonTemplates=*/!IsTemplateName);
698 if (TypoCorrection Corrected =
700 CCC, CTK_ErrorRecovery)) {
701 // FIXME: Support error recovery for the template-name case.
702 bool CanRecover = !IsTemplateName;
703 if (Corrected.isKeyword()) {
704 // We corrected to a keyword.
705 diagnoseTypo(Corrected,
706 PDiag(IsTemplateName ? diag::err_no_template_suggest
707 : diag::err_unknown_typename_suggest)
708 << II);
709 II = Corrected.getCorrectionAsIdentifierInfo();
710 } else {
711 // We found a similarly-named type or interface; suggest that.
712 if (!SS || !SS->isSet()) {
713 diagnoseTypo(Corrected,
714 PDiag(IsTemplateName ? diag::err_no_template_suggest
715 : diag::err_unknown_typename_suggest)
716 << II, CanRecover);
717 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
718 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
719 bool DroppedSpecifier =
720 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
721 diagnoseTypo(Corrected,
722 PDiag(IsTemplateName
723 ? diag::err_no_member_template_suggest
724 : diag::err_unknown_nested_typename_suggest)
725 << II << DC << DroppedSpecifier << SS->getRange(),
726 CanRecover);
727 } else {
728 llvm_unreachable("could not have corrected a typo here");
729 }
730
731 if (!CanRecover)
732 return;
733
734 CXXScopeSpec tmpSS;
735 if (Corrected.getCorrectionSpecifier())
736 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
737 SourceRange(IILoc));
738 // FIXME: Support class template argument deduction here.
739 SuggestedType =
740 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
741 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
742 /*IsCtorOrDtorName=*/false,
743 /*WantNontrivialTypeSourceInfo=*/true);
744 }
745 return;
746 }
747
748 if (getLangOpts().CPlusPlus && !IsTemplateName) {
749 // See if II is a class template that the user forgot to pass arguments to.
750 UnqualifiedId Name;
751 Name.setIdentifier(II, IILoc);
752 CXXScopeSpec EmptySS;
753 TemplateTy TemplateResult;
754 bool MemberOfUnknownSpecialization;
755 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
756 Name, nullptr, true, TemplateResult,
757 MemberOfUnknownSpecialization) == TNK_Type_template) {
758 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
759 return;
760 }
761 }
762
763 // FIXME: Should we move the logic that tries to recover from a missing tag
764 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
765
766 if (!SS || (!SS->isSet() && !SS->isInvalid()))
767 Diag(IILoc, IsTemplateName ? diag::err_no_template
768 : diag::err_unknown_typename)
769 << II;
770 else if (DeclContext *DC = computeDeclContext(*SS, false))
771 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
772 : diag::err_typename_nested_not_found)
773 << II << DC << SS->getRange();
774 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
775 SuggestedType =
776 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
777 } else if (isDependentScopeSpecifier(*SS)) {
778 unsigned DiagID = diag::err_typename_missing;
779 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
780 DiagID = diag::ext_typename_missing;
781
782 Diag(SS->getRange().getBegin(), DiagID)
783 << SS->getScopeRep() << II->getName()
784 << SourceRange(SS->getRange().getBegin(), IILoc)
785 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
786 SuggestedType = ActOnTypenameType(S, SourceLocation(),
787 *SS, *II, IILoc).get();
788 } else {
789 assert(SS && SS->isInvalid() &&
790 "Invalid scope specifier has already been diagnosed");
791 }
792}
793
794/// Determine whether the given result set contains either a type name
795/// or
796static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
797 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
798 NextToken.is(tok::less);
799
800 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
801 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
802 return true;
803
804 if (CheckTemplate && isa<TemplateDecl>(*I))
805 return true;
806 }
807
808 return false;
809}
810
812 Scope *S, CXXScopeSpec &SS,
813 IdentifierInfo *&Name,
814 SourceLocation NameLoc) {
815 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
816 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
817 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
818 StringRef FixItTagName;
819 switch (Tag->getTagKind()) {
821 FixItTagName = "class ";
822 break;
823
825 FixItTagName = "enum ";
826 break;
827
829 FixItTagName = "struct ";
830 break;
831
833 FixItTagName = "__interface ";
834 break;
835
837 FixItTagName = "union ";
838 break;
839 }
840
841 StringRef TagName = FixItTagName.drop_back();
842 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
843 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
844 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
845
846 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
847 I != IEnd; ++I)
848 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
849 << Name << TagName;
850
851 // Replace lookup results with just the tag decl.
853 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
854 return true;
855 }
856
857 return false;
858}
859
861 IdentifierInfo *&Name,
862 SourceLocation NameLoc,
863 const Token &NextToken,
865 DeclarationNameInfo NameInfo(Name, NameLoc);
866 ObjCMethodDecl *CurMethod = getCurMethodDecl();
867
868 assert(NextToken.isNot(tok::coloncolon) &&
869 "parse nested name specifiers before calling ClassifyName");
870 if (getLangOpts().CPlusPlus && SS.isSet() &&
871 isCurrentClassName(*Name, S, &SS)) {
872 // Per [class.qual]p2, this names the constructors of SS, not the
873 // injected-class-name. We don't have a classification for that.
874 // There's not much point caching this result, since the parser
875 // will reject it later.
877 }
878
879 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
880 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
881 /*AllowBuiltinCreation=*/!CurMethod);
882
883 if (SS.isInvalid())
885
886 // For unqualified lookup in a class template in MSVC mode, look into
887 // dependent base classes where the primary class template is known.
888 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
889 if (ParsedType TypeInBase =
890 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
891 return TypeInBase;
892 }
893
894 // Perform lookup for Objective-C instance variables (including automatically
895 // synthesized instance variables), if we're in an Objective-C method.
896 // FIXME: This lookup really, really needs to be folded in to the normal
897 // unqualified lookup mechanism.
898 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
899 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
900 if (Ivar.isInvalid())
902 if (Ivar.isUsable())
903 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
904
905 // We defer builtin creation until after ivar lookup inside ObjC methods.
906 if (Result.empty())
908 }
909
910 bool SecondTry = false;
911 bool IsFilteredTemplateName = false;
912
913Corrected:
914 switch (Result.getResultKind()) {
916 // If an unqualified-id is followed by a '(', then we have a function
917 // call.
918 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
919 // In C++, this is an ADL-only call.
920 // FIXME: Reference?
923
924 // C90 6.3.2.2:
925 // If the expression that precedes the parenthesized argument list in a
926 // function call consists solely of an identifier, and if no
927 // declaration is visible for this identifier, the identifier is
928 // implicitly declared exactly as if, in the innermost block containing
929 // the function call, the declaration
930 //
931 // extern int identifier ();
932 //
933 // appeared.
934 //
935 // We also allow this in C99 as an extension. However, this is not
936 // allowed in all language modes as functions without prototypes may not
937 // be supported.
938 if (getLangOpts().implicitFunctionsAllowed()) {
939 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
941 }
942 }
943
944 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
945 // In C++20 onwards, this could be an ADL-only call to a function
946 // template, and we're required to assume that this is a template name.
947 //
948 // FIXME: Find a way to still do typo correction in this case.
949 TemplateName Template =
952 }
953
954 // In C, we first see whether there is a tag type by the same name, in
955 // which case it's likely that the user just forgot to write "enum",
956 // "struct", or "union".
957 if (!getLangOpts().CPlusPlus && !SecondTry &&
958 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
959 break;
960 }
961
962 // Perform typo correction to determine if there is another name that is
963 // close to this name.
964 if (!SecondTry && CCC) {
965 SecondTry = true;
966 if (TypoCorrection Corrected =
967 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
968 &SS, *CCC, CTK_ErrorRecovery)) {
969 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
970 unsigned QualifiedDiag = diag::err_no_member_suggest;
971
972 NamedDecl *FirstDecl = Corrected.getFoundDecl();
973 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
974 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
975 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
976 UnqualifiedDiag = diag::err_no_template_suggest;
977 QualifiedDiag = diag::err_no_member_template_suggest;
978 } else if (UnderlyingFirstDecl &&
979 (isa<TypeDecl>(UnderlyingFirstDecl) ||
980 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
981 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
982 UnqualifiedDiag = diag::err_unknown_typename_suggest;
983 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
984 }
985
986 if (SS.isEmpty()) {
987 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
988 } else {// FIXME: is this even reachable? Test it.
989 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
990 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
991 Name->getName() == CorrectedStr;
992 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
993 << Name << computeDeclContext(SS, false)
994 << DroppedSpecifier << SS.getRange());
995 }
996
997 // Update the name, so that the caller has the new name.
998 Name = Corrected.getCorrectionAsIdentifierInfo();
999
1000 // Typo correction corrected to a keyword.
1001 if (Corrected.isKeyword())
1002 return Name;
1003
1004 // Also update the LookupResult...
1005 // FIXME: This should probably go away at some point
1006 Result.clear();
1007 Result.setLookupName(Corrected.getCorrection());
1008 if (FirstDecl)
1009 Result.addDecl(FirstDecl);
1010
1011 // If we found an Objective-C instance variable, let
1012 // LookupInObjCMethod build the appropriate expression to
1013 // reference the ivar.
1014 // FIXME: This is a gross hack.
1015 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1016 DeclResult R =
1017 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1018 if (R.isInvalid())
1020 if (R.isUsable())
1021 return NameClassification::NonType(Ivar);
1022 }
1023
1024 goto Corrected;
1025 }
1026 }
1027
1028 // We failed to correct; just fall through and let the parser deal with it.
1029 Result.suppressDiagnostics();
1031
1033 // We performed name lookup into the current instantiation, and there were
1034 // dependent bases, so we treat this result the same way as any other
1035 // dependent nested-name-specifier.
1036
1037 // C++ [temp.res]p2:
1038 // A name used in a template declaration or definition and that is
1039 // dependent on a template-parameter is assumed not to name a type
1040 // unless the applicable name lookup finds a type name or the name is
1041 // qualified by the keyword typename.
1042 //
1043 // FIXME: If the next token is '<', we might want to ask the parser to
1044 // perform some heroics to see if we actually have a
1045 // template-argument-list, which would indicate a missing 'template'
1046 // keyword here.
1048 }
1049
1053 break;
1054
1056 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1057 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1058 /*AllowDependent=*/false)) {
1059 // C++ [temp.local]p3:
1060 // A lookup that finds an injected-class-name (10.2) can result in an
1061 // ambiguity in certain cases (for example, if it is found in more than
1062 // one base class). If all of the injected-class-names that are found
1063 // refer to specializations of the same class template, and if the name
1064 // is followed by a template-argument-list, the reference refers to the
1065 // class template itself and not a specialization thereof, and is not
1066 // ambiguous.
1067 //
1068 // This filtering can make an ambiguous result into an unambiguous one,
1069 // so try again after filtering out template names.
1071 if (!Result.isAmbiguous()) {
1072 IsFilteredTemplateName = true;
1073 break;
1074 }
1075 }
1076
1077 // Diagnose the ambiguity and return an error.
1079 }
1080
1081 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1082 (IsFilteredTemplateName ||
1084 Result, /*AllowFunctionTemplates=*/true,
1085 /*AllowDependent=*/false,
1086 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1088 // C++ [temp.names]p3:
1089 // After name lookup (3.4) finds that a name is a template-name or that
1090 // an operator-function-id or a literal- operator-id refers to a set of
1091 // overloaded functions any member of which is a function template if
1092 // this is followed by a <, the < is always taken as the delimiter of a
1093 // template-argument-list and never as the less-than operator.
1094 // C++2a [temp.names]p2:
1095 // A name is also considered to refer to a template if it is an
1096 // unqualified-id followed by a < and name lookup finds either one
1097 // or more functions or finds nothing.
1098 if (!IsFilteredTemplateName)
1100
1101 bool IsFunctionTemplate;
1102 bool IsVarTemplate;
1103 TemplateName Template;
1104 if (Result.end() - Result.begin() > 1) {
1105 IsFunctionTemplate = true;
1106 Template = Context.getOverloadedTemplateName(Result.begin(),
1107 Result.end());
1108 } else if (!Result.empty()) {
1109 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1110 *Result.begin(), /*AllowFunctionTemplates=*/true,
1111 /*AllowDependent=*/false));
1112 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1113 IsVarTemplate = isa<VarTemplateDecl>(TD);
1114
1115 UsingShadowDecl *FoundUsingShadow =
1116 dyn_cast<UsingShadowDecl>(*Result.begin());
1117 assert(!FoundUsingShadow ||
1118 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1120 SS.getScopeRep(),
1121 /*TemplateKeyword=*/false,
1122 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1123 } else {
1124 // All results were non-template functions. This is a function template
1125 // name.
1126 IsFunctionTemplate = true;
1127 Template = Context.getAssumedTemplateName(NameInfo.getName());
1128 }
1129
1130 if (IsFunctionTemplate) {
1131 // Function templates always go through overload resolution, at which
1132 // point we'll perform the various checks (e.g., accessibility) we need
1133 // to based on which function we selected.
1134 Result.suppressDiagnostics();
1135
1136 return NameClassification::FunctionTemplate(Template);
1137 }
1138
1139 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1141 }
1142
1143 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1145 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1146 T = Context.getUsingType(USD, T);
1147 return buildNamedType(*this, &SS, T, NameLoc);
1148 };
1149
1150 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1151 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1152 DiagnoseUseOfDecl(Type, NameLoc);
1153 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1154 return BuildTypeFor(Type, *Result.begin());
1155 }
1156
1157 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1158 if (!Class) {
1159 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1160 if (ObjCCompatibleAliasDecl *Alias =
1161 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1162 Class = Alias->getClassInterface();
1163 }
1164
1165 if (Class) {
1166 DiagnoseUseOfDecl(Class, NameLoc);
1167
1168 if (NextToken.is(tok::period)) {
1169 // Interface. <something> is parsed as a property reference expression.
1170 // Just return "unknown" as a fall-through for now.
1171 Result.suppressDiagnostics();
1173 }
1174
1176 return ParsedType::make(T);
1177 }
1178
1179 if (isa<ConceptDecl>(FirstDecl)) {
1180 // We want to preserve the UsingShadowDecl for concepts.
1181 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1184 TemplateName(cast<TemplateDecl>(FirstDecl)));
1185 }
1186
1187 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1188 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1190 }
1191
1192 // We can have a type template here if we're classifying a template argument.
1193 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1194 !isa<VarTemplateDecl>(FirstDecl))
1196 TemplateName(cast<TemplateDecl>(FirstDecl)));
1197
1198 // Check for a tag type hidden by a non-type decl in a few cases where it
1199 // seems likely a type is wanted instead of the non-type that was found.
1200 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1201 if ((NextToken.is(tok::identifier) ||
1202 (NextIsOp &&
1203 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1204 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1205 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1206 DiagnoseUseOfDecl(Type, NameLoc);
1207 return BuildTypeFor(Type, *Result.begin());
1208 }
1209
1210 // If we already know which single declaration is referenced, just annotate
1211 // that declaration directly. Defer resolving even non-overloaded class
1212 // member accesses, as we need to defer certain access checks until we know
1213 // the context.
1214 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1215 if (Result.isSingleResult() && !ADL &&
1216 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1217 return NameClassification::NonType(Result.getRepresentativeDecl());
1218
1219 // Otherwise, this is an overload set that we will need to resolve later.
1220 Result.suppressDiagnostics();
1222 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1223 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1224 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1225}
1226
1229 SourceLocation NameLoc) {
1230 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1231 CXXScopeSpec SS;
1232 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1233 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1234}
1235
1238 IdentifierInfo *Name,
1239 SourceLocation NameLoc,
1240 bool IsAddressOfOperand) {
1241 DeclarationNameInfo NameInfo(Name, NameLoc);
1242 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1243 NameInfo, IsAddressOfOperand,
1244 /*TemplateArgs=*/nullptr);
1245}
1246
1249 SourceLocation NameLoc,
1250 const Token &NextToken) {
1251 if (getCurMethodDecl() && SS.isEmpty())
1252 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1253 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1254
1255 // Reconstruct the lookup result.
1256 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1257 Result.addDecl(Found);
1258 Result.resolveKind();
1259
1260 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1261 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1262}
1263
1265 // For an implicit class member access, transform the result into a member
1266 // access expression if necessary.
1267 auto *ULE = cast<UnresolvedLookupExpr>(E);
1268 if ((*ULE->decls_begin())->isCXXClassMember()) {
1269 CXXScopeSpec SS;
1270 SS.Adopt(ULE->getQualifierLoc());
1271
1272 // Reconstruct the lookup result.
1273 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1275 Result.setNamingClass(ULE->getNamingClass());
1276 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1277 Result.addDecl(*I, I.getAccess());
1278 Result.resolveKind();
1280 nullptr, S);
1281 }
1282
1283 // Otherwise, this is already in the form we needed, and no further checks
1284 // are necessary.
1285 return ULE;
1286}
1287
1290 auto *TD = Name.getAsTemplateDecl();
1291 if (!TD)
1293 if (isa<ClassTemplateDecl>(TD))
1295 if (isa<FunctionTemplateDecl>(TD))
1297 if (isa<VarTemplateDecl>(TD))
1299 if (isa<TypeAliasTemplateDecl>(TD))
1301 if (isa<TemplateTemplateParmDecl>(TD))
1303 if (isa<ConceptDecl>(TD))
1306}
1307
1309 assert(DC->getLexicalParent() == CurContext &&
1310 "The next DeclContext should be lexically contained in the current one.");
1311 CurContext = DC;
1312 S->setEntity(DC);
1313}
1314
1316 assert(CurContext && "DeclContext imbalance!");
1317
1319 assert(CurContext && "Popped translation unit!");
1320}
1321
1323 Decl *D) {
1324 // Unlike PushDeclContext, the context to which we return is not necessarily
1325 // the containing DC of TD, because the new context will be some pre-existing
1326 // TagDecl definition instead of a fresh one.
1327 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1328 CurContext = cast<TagDecl>(D)->getDefinition();
1329 assert(CurContext && "skipping definition of undefined tag");
1330 // Start lookups from the parent of the current context; we don't want to look
1331 // into the pre-existing complete definition.
1332 S->setEntity(CurContext->getLookupParent());
1333 return Result;
1334}
1335
1337 CurContext = static_cast<decltype(CurContext)>(Context);
1338}
1339
1341 // C++0x [basic.lookup.unqual]p13:
1342 // A name used in the definition of a static data member of class
1343 // X (after the qualified-id of the static member) is looked up as
1344 // if the name was used in a member function of X.
1345 // C++0x [basic.lookup.unqual]p14:
1346 // If a variable member of a namespace is defined outside of the
1347 // scope of its namespace then any name used in the definition of
1348 // the variable member (after the declarator-id) is looked up as
1349 // if the definition of the variable member occurred in its
1350 // namespace.
1351 // Both of these imply that we should push a scope whose context
1352 // is the semantic context of the declaration. We can't use
1353 // PushDeclContext here because that context is not necessarily
1354 // lexically contained in the current context. Fortunately,
1355 // the containing scope should have the appropriate information.
1356
1357 assert(!S->getEntity() && "scope already has entity");
1358
1359#ifndef NDEBUG
1360 Scope *Ancestor = S->getParent();
1361 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1362 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1363#endif
1364
1365 CurContext = DC;
1366 S->setEntity(DC);
1367
1368 if (S->getParent()->isTemplateParamScope()) {
1369 // Also set the corresponding entities for all immediately-enclosing
1370 // template parameter scopes.
1371 EnterTemplatedContext(S->getParent(), DC);
1372 }
1373}
1374
1376 assert(S->getEntity() == CurContext && "Context imbalance!");
1377
1378 // Switch back to the lexical context. The safety of this is
1379 // enforced by an assert in EnterDeclaratorContext.
1380 Scope *Ancestor = S->getParent();
1381 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1382 CurContext = Ancestor->getEntity();
1383
1384 // We don't need to do anything with the scope, which is going to
1385 // disappear.
1386}
1387
1389 assert(S->isTemplateParamScope() &&
1390 "expected to be initializing a template parameter scope");
1391
1392 // C++20 [temp.local]p7:
1393 // In the definition of a member of a class template that appears outside
1394 // of the class template definition, the name of a member of the class
1395 // template hides the name of a template-parameter of any enclosing class
1396 // templates (but not a template-parameter of the member if the member is a
1397 // class or function template).
1398 // C++20 [temp.local]p9:
1399 // In the definition of a class template or in the definition of a member
1400 // of such a template that appears outside of the template definition, for
1401 // each non-dependent base class (13.8.2.1), if the name of the base class
1402 // or the name of a member of the base class is the same as the name of a
1403 // template-parameter, the base class name or member name hides the
1404 // template-parameter name (6.4.10).
1405 //
1406 // This means that a template parameter scope should be searched immediately
1407 // after searching the DeclContext for which it is a template parameter
1408 // scope. For example, for
1409 // template<typename T> template<typename U> template<typename V>
1410 // void N::A<T>::B<U>::f(...)
1411 // we search V then B<U> (and base classes) then U then A<T> (and base
1412 // classes) then T then N then ::.
1413 unsigned ScopeDepth = getTemplateDepth(S);
1414 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1415 DeclContext *SearchDCAfterScope = DC;
1416 for (; DC; DC = DC->getLookupParent()) {
1417 if (const TemplateParameterList *TPL =
1418 cast<Decl>(DC)->getDescribedTemplateParams()) {
1419 unsigned DCDepth = TPL->getDepth() + 1;
1420 if (DCDepth > ScopeDepth)
1421 continue;
1422 if (ScopeDepth == DCDepth)
1423 SearchDCAfterScope = DC = DC->getLookupParent();
1424 break;
1425 }
1426 }
1427 S->setLookupEntity(SearchDCAfterScope);
1428 }
1429}
1430
1432 // We assume that the caller has already called
1433 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1434 FunctionDecl *FD = D->getAsFunction();
1435 if (!FD)
1436 return;
1437
1438 // Same implementation as PushDeclContext, but enters the context
1439 // from the lexical parent, rather than the top-level class.
1440 assert(CurContext == FD->getLexicalParent() &&
1441 "The next DeclContext should be lexically contained in the current one.");
1442 CurContext = FD;
1443 S->setEntity(CurContext);
1444
1445 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1446 ParmVarDecl *Param = FD->getParamDecl(P);
1447 // If the parameter has an identifier, then add it to the scope
1448 if (Param->getIdentifier()) {
1449 S->AddDecl(Param);
1450 IdResolver.AddDecl(Param);
1451 }
1452 }
1453}
1454
1456 // Same implementation as PopDeclContext, but returns to the lexical parent,
1457 // rather than the top-level class.
1458 assert(CurContext && "DeclContext imbalance!");
1460 assert(CurContext && "Popped translation unit!");
1461}
1462
1463/// Determine whether overloading is allowed for a new function
1464/// declaration considering prior declarations of the same name.
1465///
1466/// This routine determines whether overloading is possible, not
1467/// whether a new declaration actually overloads a previous one.
1468/// It will return true in C++ (where overloads are always permitted)
1469/// or, as a C extension, when either the new declaration or a
1470/// previous one is declared with the 'overloadable' attribute.
1472 ASTContext &Context,
1473 const FunctionDecl *New) {
1474 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1475 return true;
1476
1477 // Multiversion function declarations are not overloads in the
1478 // usual sense of that term, but lookup will report that an
1479 // overload set was found if more than one multiversion function
1480 // declaration is present for the same name. It is therefore
1481 // inadequate to assume that some prior declaration(s) had
1482 // the overloadable attribute; checking is required. Since one
1483 // declaration is permitted to omit the attribute, it is necessary
1484 // to check at least two; hence the 'any_of' check below. Note that
1485 // the overloadable attribute is implicitly added to declarations
1486 // that were required to have it but did not.
1487 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1488 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1489 return ND->hasAttr<OverloadableAttr>();
1490 });
1491 } else if (Previous.getResultKind() == LookupResult::Found)
1492 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1493
1494 return false;
1495}
1496
1497void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1498 // Move up the scope chain until we find the nearest enclosing
1499 // non-transparent context. The declaration will be introduced into this
1500 // scope.
1501 while (S->getEntity() && S->getEntity()->isTransparentContext())
1502 S = S->getParent();
1503
1504 // Add scoped declarations into their context, so that they can be
1505 // found later. Declarations without a context won't be inserted
1506 // into any context.
1507 if (AddToContext)
1509
1510 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1511 // are function-local declarations.
1512 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1513 return;
1514
1515 // Template instantiations should also not be pushed into scope.
1516 if (isa<FunctionDecl>(D) &&
1517 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1518 return;
1519
1520 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1521 S->AddDecl(D);
1522 return;
1523 }
1524 // If this replaces anything in the current scope,
1525 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1526 IEnd = IdResolver.end();
1527 for (; I != IEnd; ++I) {
1528 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1529 S->RemoveDecl(*I);
1531
1532 // Should only need to replace one decl.
1533 break;
1534 }
1535 }
1536
1537 S->AddDecl(D);
1538
1539 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1540 // Implicitly-generated labels may end up getting generated in an order that
1541 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1542 // the label at the appropriate place in the identifier chain.
1543 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1544 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1545 if (IDC == CurContext) {
1546 if (!S->isDeclScope(*I))
1547 continue;
1548 } else if (IDC->Encloses(CurContext))
1549 break;
1550 }
1551
1553 } else {
1555 }
1557}
1558
1560 bool AllowInlineNamespace) const {
1561 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1562}
1563
1565 DeclContext *TargetDC = DC->getPrimaryContext();
1566 do {
1567 if (DeclContext *ScopeDC = S->getEntity())
1568 if (ScopeDC->getPrimaryContext() == TargetDC)
1569 return S;
1570 } while ((S = S->getParent()));
1571
1572 return nullptr;
1573}
1574
1576 DeclContext*,
1577 ASTContext&);
1578
1580 bool ConsiderLinkage,
1581 bool AllowInlineNamespace) {
1583 while (F.hasNext()) {
1584 NamedDecl *D = F.next();
1585
1586 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1587 continue;
1588
1589 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1590 continue;
1591
1592 F.erase();
1593 }
1594
1595 F.done();
1596}
1597
1599 // [module.interface]p7:
1600 // A declaration is attached to a module as follows:
1601 // - If the declaration is a non-dependent friend declaration that nominates a
1602 // function with a declarator-id that is a qualified-id or template-id or that
1603 // nominates a class other than with an elaborated-type-specifier with neither
1604 // a nested-name-specifier nor a simple-template-id, it is attached to the
1605 // module to which the friend is attached ([basic.link]).
1606 if (New->getFriendObjectKind() &&
1610 return false;
1611 }
1612
1613 Module *NewM = New->getOwningModule();
1614 Module *OldM = Old->getOwningModule();
1615
1616 if (NewM && NewM->isPrivateModule())
1617 NewM = NewM->Parent;
1618 if (OldM && OldM->isPrivateModule())
1619 OldM = OldM->Parent;
1620
1621 if (NewM == OldM)
1622 return false;
1623
1624 if (NewM && OldM) {
1625 // A module implementation unit has visibility of the decls in its
1626 // implicitly imported interface.
1627 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1628 return false;
1629
1630 // Partitions are part of the module, but a partition could import another
1631 // module, so verify that the PMIs agree.
1632 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1633 getASTContext().isInSameModule(NewM, OldM))
1634 return false;
1635 }
1636
1637 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1638 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1639 if (NewIsModuleInterface || OldIsModuleInterface) {
1640 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1641 // if a declaration of D [...] appears in the purview of a module, all
1642 // other such declarations shall appear in the purview of the same module
1643 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1644 << New
1645 << NewIsModuleInterface
1646 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1647 << OldIsModuleInterface
1648 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1649 Diag(Old->getLocation(), diag::note_previous_declaration);
1650 New->setInvalidDecl();
1651 return true;
1652 }
1653
1654 return false;
1655}
1656
1658 // [module.interface]p1:
1659 // An export-declaration shall inhabit a namespace scope.
1660 //
1661 // So it is meaningless to talk about redeclaration which is not at namespace
1662 // scope.
1663 if (!New->getLexicalDeclContext()
1665 ->isFileContext() ||
1666 !Old->getLexicalDeclContext()
1668 ->isFileContext())
1669 return false;
1670
1671 bool IsNewExported = New->isInExportDeclContext();
1672 bool IsOldExported = Old->isInExportDeclContext();
1673
1674 // It should be irrevelant if both of them are not exported.
1675 if (!IsNewExported && !IsOldExported)
1676 return false;
1677
1678 if (IsOldExported)
1679 return false;
1680
1681 // If the Old declaration are not attached to named modules
1682 // and the New declaration are attached to global module.
1683 // It should be fine to allow the export since it doesn't change
1684 // the linkage of declarations. See
1685 // https://github.com/llvm/llvm-project/issues/98583 for details.
1686 if (!Old->isInNamedModule() && New->getOwningModule() &&
1688 return false;
1689
1690 assert(IsNewExported);
1691
1692 auto Lk = Old->getFormalLinkage();
1693 int S = 0;
1694 if (Lk == Linkage::Internal)
1695 S = 1;
1696 else if (Lk == Linkage::Module)
1697 S = 2;
1698 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1699 Diag(Old->getLocation(), diag::note_previous_declaration);
1700 return true;
1701}
1702
1705 return true;
1706
1707 if (CheckRedeclarationExported(New, Old))
1708 return true;
1709
1710 return false;
1711}
1712
1714 const NamedDecl *Old) const {
1715 assert(getASTContext().isSameEntity(New, Old) &&
1716 "New and Old are not the same definition, we should diagnostic it "
1717 "immediately instead of checking it.");
1718 assert(const_cast<Sema *>(this)->isReachable(New) &&
1719 const_cast<Sema *>(this)->isReachable(Old) &&
1720 "We shouldn't see unreachable definitions here.");
1721
1722 Module *NewM = New->getOwningModule();
1723 Module *OldM = Old->getOwningModule();
1724
1725 // We only checks for named modules here. The header like modules is skipped.
1726 // FIXME: This is not right if we import the header like modules in the module
1727 // purview.
1728 //
1729 // For example, assuming "header.h" provides definition for `D`.
1730 // ```C++
1731 // //--- M.cppm
1732 // export module M;
1733 // import "header.h"; // or #include "header.h" but import it by clang modules
1734 // actually.
1735 //
1736 // //--- Use.cpp
1737 // import M;
1738 // import "header.h"; // or uses clang modules.
1739 // ```
1740 //
1741 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1742 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1743 // reject it. But the current implementation couldn't detect the case since we
1744 // don't record the information about the importee modules.
1745 //
1746 // But this might not be painful in practice. Since the design of C++20 Named
1747 // Modules suggests us to use headers in global module fragment instead of
1748 // module purview.
1749 if (NewM && NewM->isHeaderLikeModule())
1750 NewM = nullptr;
1751 if (OldM && OldM->isHeaderLikeModule())
1752 OldM = nullptr;
1753
1754 if (!NewM && !OldM)
1755 return true;
1756
1757 // [basic.def.odr]p14.3
1758 // Each such definition shall not be attached to a named module
1759 // ([module.unit]).
1760 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1761 return true;
1762
1763 // Then New and Old lives in the same TU if their share one same module unit.
1764 if (NewM)
1765 NewM = NewM->getTopLevelModule();
1766 if (OldM)
1767 OldM = OldM->getTopLevelModule();
1768 return OldM == NewM;
1769}
1770
1772 if (D->getDeclContext()->isFileContext())
1773 return false;
1774
1775 return isa<UsingShadowDecl>(D) ||
1776 isa<UnresolvedUsingTypenameDecl>(D) ||
1777 isa<UnresolvedUsingValueDecl>(D);
1778}
1779
1780/// Removes using shadow declarations not at class scope from the lookup
1781/// results.
1784 while (F.hasNext())
1786 F.erase();
1787
1788 F.done();
1789}
1790
1791/// Check for this common pattern:
1792/// @code
1793/// class S {
1794/// S(const S&); // DO NOT IMPLEMENT
1795/// void operator=(const S&); // DO NOT IMPLEMENT
1796/// };
1797/// @endcode
1799 // FIXME: Should check for private access too but access is set after we get
1800 // the decl here.
1801 if (D->doesThisDeclarationHaveABody())
1802 return false;
1803
1804 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1805 return CD->isCopyConstructor();
1806 return D->isCopyAssignmentOperator();
1807}
1808
1809bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1810 const DeclContext *DC = D->getDeclContext();
1811 while (!DC->isTranslationUnit()) {
1812 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1813 if (!RD->hasNameForLinkage())
1814 return true;
1815 }
1816 DC = DC->getParent();
1817 }
1818
1819 return !D->isExternallyVisible();
1820}
1821
1822// FIXME: This needs to be refactored; some other isInMainFile users want
1823// these semantics.
1824static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1826 return false;
1827 return S.SourceMgr.isInMainFile(Loc);
1828}
1829
1831 assert(D);
1832
1833 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1834 return false;
1835
1836 // Ignore all entities declared within templates, and out-of-line definitions
1837 // of members of class templates.
1840 return false;
1841
1842 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1843 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1844 return false;
1845 // A non-out-of-line declaration of a member specialization was implicitly
1846 // instantiated; it's the out-of-line declaration that we're interested in.
1847 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1848 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1849 return false;
1850
1851 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1852 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1853 return false;
1854 } else {
1855 // 'static inline' functions are defined in headers; don't warn.
1856 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1857 return false;
1858 }
1859
1860 if (FD->doesThisDeclarationHaveABody() &&
1862 return false;
1863 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1864 // Constants and utility variables are defined in headers with internal
1865 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1866 // like "inline".)
1867 if (!isMainFileLoc(*this, VD->getLocation()))
1868 return false;
1869
1870 if (Context.DeclMustBeEmitted(VD))
1871 return false;
1872
1873 if (VD->isStaticDataMember() &&
1874 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1875 return false;
1876 if (VD->isStaticDataMember() &&
1877 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1878 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1879 return false;
1880
1881 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1882 return false;
1883 } else {
1884 return false;
1885 }
1886
1887 // Only warn for unused decls internal to the translation unit.
1888 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1889 // for inline functions defined in the main source file, for instance.
1890 return mightHaveNonExternalLinkage(D);
1891}
1892
1894 if (!D)
1895 return;
1896
1897 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1898 const FunctionDecl *First = FD->getFirstDecl();
1900 return; // First should already be in the vector.
1901 }
1902
1903 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1904 const VarDecl *First = VD->getFirstDecl();
1906 return; // First should already be in the vector.
1907 }
1908
1911}
1912
1913static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1914 const NamedDecl *D) {
1915 if (D->isInvalidDecl())
1916 return false;
1917
1918 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1919 // For a decomposition declaration, warn if none of the bindings are
1920 // referenced, instead of if the variable itself is referenced (which
1921 // it is, by the bindings' expressions).
1922 bool IsAllPlaceholders = true;
1923 for (const auto *BD : DD->bindings()) {
1924 if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())
1925 return false;
1926 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1927 }
1928 if (IsAllPlaceholders)
1929 return false;
1930 } else if (!D->getDeclName()) {
1931 return false;
1932 } else if (D->isReferenced() || D->isUsed()) {
1933 return false;
1934 }
1935
1936 if (D->isPlaceholderVar(LangOpts))
1937 return false;
1938
1939 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1940 D->hasAttr<CleanupAttr>())
1941 return false;
1942
1943 if (isa<LabelDecl>(D))
1944 return true;
1945
1946 // Except for labels, we only care about unused decls that are local to
1947 // functions.
1948 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1949 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1950 // For dependent types, the diagnostic is deferred.
1951 WithinFunction =
1952 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1953 if (!WithinFunction)
1954 return false;
1955
1956 if (isa<TypedefNameDecl>(D))
1957 return true;
1958
1959 // White-list anything that isn't a local variable.
1960 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1961 return false;
1962
1963 // Types of valid local variables should be complete, so this should succeed.
1964 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1965
1966 const Expr *Init = VD->getInit();
1967 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
1968 Init = Cleanups->getSubExpr();
1969
1970 const auto *Ty = VD->getType().getTypePtr();
1971
1972 // Only look at the outermost level of typedef.
1973 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1974 // Allow anything marked with __attribute__((unused)).
1975 if (TT->getDecl()->hasAttr<UnusedAttr>())
1976 return false;
1977 }
1978
1979 // Warn for reference variables whose initializtion performs lifetime
1980 // extension.
1981 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
1982 MTE && MTE->getExtendingDecl()) {
1983 Ty = VD->getType().getNonReferenceType().getTypePtr();
1984 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1985 }
1986
1987 // If we failed to complete the type for some reason, or if the type is
1988 // dependent, don't diagnose the variable.
1989 if (Ty->isIncompleteType() || Ty->isDependentType())
1990 return false;
1991
1992 // Look at the element type to ensure that the warning behaviour is
1993 // consistent for both scalars and arrays.
1994 Ty = Ty->getBaseElementTypeUnsafe();
1995
1996 if (const TagType *TT = Ty->getAs<TagType>()) {
1997 const TagDecl *Tag = TT->getDecl();
1998 if (Tag->hasAttr<UnusedAttr>())
1999 return false;
2000
2001 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2002 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2003 return false;
2004
2005 if (Init) {
2006 const auto *Construct =
2007 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2008 if (Construct && !Construct->isElidable()) {
2009 const CXXConstructorDecl *CD = Construct->getConstructor();
2010 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2011 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2012 return false;
2013 }
2014
2015 // Suppress the warning if we don't know how this is constructed, and
2016 // it could possibly be non-trivial constructor.
2017 if (Init->isTypeDependent()) {
2018 for (const CXXConstructorDecl *Ctor : RD->ctors())
2019 if (!Ctor->isTrivial())
2020 return false;
2021 }
2022
2023 // Suppress the warning if the constructor is unresolved because
2024 // its arguments are dependent.
2025 if (isa<CXXUnresolvedConstructExpr>(Init))
2026 return false;
2027 }
2028 }
2029 }
2030
2031 // TODO: __attribute__((unused)) templates?
2032 }
2033
2034 return true;
2035}
2036
2038 FixItHint &Hint) {
2039 if (isa<LabelDecl>(D)) {
2041 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2042 /*SkipTrailingWhitespaceAndNewline=*/false);
2043 if (AfterColon.isInvalid())
2044 return;
2047 }
2048}
2049
2052 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2053}
2054
2056 DiagReceiverTy DiagReceiver) {
2057 if (D->getTypeForDecl()->isDependentType())
2058 return;
2059
2060 for (auto *TmpD : D->decls()) {
2061 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2062 DiagnoseUnusedDecl(T, DiagReceiver);
2063 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2064 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2065 }
2066}
2067
2070 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2071}
2072
2075 return;
2076
2077 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2078 // typedefs can be referenced later on, so the diagnostics are emitted
2079 // at end-of-translation-unit.
2081 return;
2082 }
2083
2084 FixItHint Hint;
2086
2087 unsigned DiagID;
2088 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2089 DiagID = diag::warn_unused_exception_param;
2090 else if (isa<LabelDecl>(D))
2091 DiagID = diag::warn_unused_label;
2092 else
2093 DiagID = diag::warn_unused_variable;
2094
2095 SourceLocation DiagLoc = D->getLocation();
2096 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2097}
2098
2100 DiagReceiverTy DiagReceiver) {
2101 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2102 // it's not really unused.
2103 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2104 return;
2105
2106 // In C++, `_` variables behave as if they were maybe_unused
2107 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2108 return;
2109
2110 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2111
2112 if (Ty->isReferenceType() || Ty->isDependentType())
2113 return;
2114
2115 if (const TagType *TT = Ty->getAs<TagType>()) {
2116 const TagDecl *Tag = TT->getDecl();
2117 if (Tag->hasAttr<UnusedAttr>())
2118 return;
2119 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2120 // mimic gcc's behavior.
2121 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2122 RD && !RD->hasAttr<WarnUnusedAttr>())
2123 return;
2124 }
2125
2126 // Don't warn about __block Objective-C pointer variables, as they might
2127 // be assigned in the block but not used elsewhere for the purpose of lifetime
2128 // extension.
2129 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2130 return;
2131
2132 // Don't warn about Objective-C pointer variables with precise lifetime
2133 // semantics; they can be used to ensure ARC releases the object at a known
2134 // time, which may mean assignment but no other references.
2135 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2136 return;
2137
2138 auto iter = RefsMinusAssignments.find(VD);
2139 if (iter == RefsMinusAssignments.end())
2140 return;
2141
2142 assert(iter->getSecond() >= 0 &&
2143 "Found a negative number of references to a VarDecl");
2144 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2145 // Assume the given VarDecl is "used" if its ref count stored in
2146 // `RefMinusAssignments` is positive, with one exception.
2147 //
2148 // For a C++ variable whose decl (with initializer) entirely consist the
2149 // condition expression of a if/while/for construct,
2150 // Clang creates a DeclRefExpr for the condition expression rather than a
2151 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2152 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2153 // used in the body of the if/while/for construct.
2154 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2155 if (!UnusedCXXCondDecl)
2156 return;
2157 }
2158
2159 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2160 : diag::warn_unused_but_set_variable;
2161 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2162}
2163
2165 Sema::DiagReceiverTy DiagReceiver) {
2166 // Verify that we have no forward references left. If so, there was a goto
2167 // or address of a label taken, but no definition of it. Label fwd
2168 // definitions are indicated with a null substmt which is also not a resolved
2169 // MS inline assembly label name.
2170 bool Diagnose = false;
2171 if (L->isMSAsmLabel())
2172 Diagnose = !L->isResolvedMSAsmLabel();
2173 else
2174 Diagnose = L->getStmt() == nullptr;
2175 if (Diagnose)
2176 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2177 << L);
2178}
2179
2181 S->applyNRVO();
2182
2183 if (S->decl_empty()) return;
2184 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2185 "Scope shouldn't contain decls!");
2186
2187 /// We visit the decls in non-deterministic order, but we want diagnostics
2188 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2189 /// and sort the diagnostics before emitting them, after we visited all decls.
2190 struct LocAndDiag {
2192 std::optional<SourceLocation> PreviousDeclLoc;
2194 };
2196 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2197 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2198 };
2199 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2200 SourceLocation PreviousDeclLoc,
2201 PartialDiagnostic PD) {
2202 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2203 };
2204
2205 for (auto *TmpD : S->decls()) {
2206 assert(TmpD && "This decl didn't get pushed??");
2207
2208 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2209 NamedDecl *D = cast<NamedDecl>(TmpD);
2210
2211 // Diagnose unused variables in this scope.
2212 if (!S->hasUnrecoverableErrorOccurred()) {
2213 DiagnoseUnusedDecl(D, addDiag);
2214 if (const auto *RD = dyn_cast<RecordDecl>(D))
2215 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2216 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2217 DiagnoseUnusedButSetDecl(VD, addDiag);
2218 RefsMinusAssignments.erase(VD);
2219 }
2220 }
2221
2222 if (!D->getDeclName()) continue;
2223
2224 // If this was a forward reference to a label, verify it was defined.
2225 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2226 CheckPoppedLabel(LD, *this, addDiag);
2227
2228 // Partial translation units that are created in incremental processing must
2229 // not clean up the IdResolver because PTUs should take into account the
2230 // declarations that came from previous PTUs.
2234
2235 // Warn on it if we are shadowing a declaration.
2236 auto ShadowI = ShadowingDecls.find(D);
2237 if (ShadowI != ShadowingDecls.end()) {
2238 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2239 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2240 PDiag(diag::warn_ctor_parm_shadows_field)
2241 << D << FD << FD->getParent());
2242 }
2243 ShadowingDecls.erase(ShadowI);
2244 }
2245 }
2246
2247 llvm::sort(DeclDiags,
2248 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2249 // The particular order for diagnostics is not important, as long
2250 // as the order is deterministic. Using the raw location is going
2251 // to generally be in source order unless there are macro
2252 // expansions involved.
2253 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2254 });
2255 for (const LocAndDiag &D : DeclDiags) {
2256 Diag(D.Loc, D.PD);
2257 if (D.PreviousDeclLoc)
2258 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2259 }
2260}
2261
2263 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2264 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2265 (S->isClassScope() && !getLangOpts().CPlusPlus))
2266 S = S->getParent();
2267 return S;
2268}
2269
2270static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2272 switch (Error) {
2274 return "";
2276 return BuiltinInfo.getHeaderName(ID);
2278 return "stdio.h";
2280 return "setjmp.h";
2282 return "ucontext.h";
2283 }
2284 llvm_unreachable("unhandled error kind");
2285}
2286
2288 unsigned ID, SourceLocation Loc) {
2290
2291 if (getLangOpts().CPlusPlus) {
2294 CLinkageDecl->setImplicit();
2295 Parent->addDecl(CLinkageDecl);
2296 Parent = CLinkageDecl;
2297 }
2298
2301 assert(getLangOpts().CPlusPlus20 &&
2302 "consteval builtins should only be available in C++20 mode");
2303 ConstexprKind = ConstexprSpecKind::Consteval;
2304 }
2305
2307 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2308 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2309 Type->isFunctionProtoType(), ConstexprKind);
2310 New->setImplicit();
2311 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2312
2313 // Create Decl objects for each parameter, adding them to the
2314 // FunctionDecl.
2315 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2317 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2319 Context, New, SourceLocation(), SourceLocation(), nullptr,
2320 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2321 parm->setScopeInfo(0, i);
2322 Params.push_back(parm);
2323 }
2324 New->setParams(Params);
2325 }
2326
2328 return New;
2329}
2330
2332 Scope *S, bool ForRedeclaration,
2335
2337 QualType R = Context.GetBuiltinType(ID, Error);
2338 if (Error) {
2339 if (!ForRedeclaration)
2340 return nullptr;
2341
2342 // If we have a builtin without an associated type we should not emit a
2343 // warning when we were not able to find a type for it.
2344 if (Error == ASTContext::GE_Missing_type ||
2346 return nullptr;
2347
2348 // If we could not find a type for setjmp it is because the jmp_buf type was
2349 // not defined prior to the setjmp declaration.
2350 if (Error == ASTContext::GE_Missing_setjmp) {
2351 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2353 return nullptr;
2354 }
2355
2356 // Generally, we emit a warning that the declaration requires the
2357 // appropriate header.
2358 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2359 << getHeaderName(Context.BuiltinInfo, ID, Error)
2361 return nullptr;
2362 }
2363
2364 if (!ForRedeclaration &&
2367 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2368 : diag::ext_implicit_lib_function_decl)
2369 << Context.BuiltinInfo.getName(ID) << R;
2370 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2371 Diag(Loc, diag::note_include_header_or_declare)
2372 << Header << Context.BuiltinInfo.getName(ID);
2373 }
2374
2375 if (R.isNull())
2376 return nullptr;
2377
2378 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2380
2381 // TUScope is the translation-unit scope to insert this function into.
2382 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2383 // relate Scopes to DeclContexts, and probably eliminate CurContext
2384 // entirely, but we're not there yet.
2385 DeclContext *SavedContext = CurContext;
2386 CurContext = New->getDeclContext();
2388 CurContext = SavedContext;
2389 return New;
2390}
2391
2392/// Typedef declarations don't have linkage, but they still denote the same
2393/// entity if their types are the same.
2394/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2395/// isSameEntity.
2396static void
2399 // This is only interesting when modules are enabled.
2400 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2401 return;
2402
2403 // Empty sets are uninteresting.
2404 if (Previous.empty())
2405 return;
2406
2407 LookupResult::Filter Filter = Previous.makeFilter();
2408 while (Filter.hasNext()) {
2409 NamedDecl *Old = Filter.next();
2410
2411 // Non-hidden declarations are never ignored.
2412 if (S.isVisible(Old))
2413 continue;
2414
2415 // Declarations of the same entity are not ignored, even if they have
2416 // different linkages.
2417 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2418 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2419 Decl->getUnderlyingType()))
2420 continue;
2421
2422 // If both declarations give a tag declaration a typedef name for linkage
2423 // purposes, then they declare the same entity.
2424 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2425 Decl->getAnonDeclWithTypedefName())
2426 continue;
2427 }
2428
2429 Filter.erase();
2430 }
2431
2432 Filter.done();
2433}
2434
2436 QualType OldType;
2437 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2438 OldType = OldTypedef->getUnderlyingType();
2439 else
2440 OldType = Context.getTypeDeclType(Old);
2441 QualType NewType = New->getUnderlyingType();
2442
2443 if (NewType->isVariablyModifiedType()) {
2444 // Must not redefine a typedef with a variably-modified type.
2445 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2446 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2447 << Kind << NewType;
2448 if (Old->getLocation().isValid())
2450 New->setInvalidDecl();
2451 return true;
2452 }
2453
2454 if (OldType != NewType &&
2455 !OldType->isDependentType() &&
2456 !NewType->isDependentType() &&
2457 !Context.hasSameType(OldType, NewType)) {
2458 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2459 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2460 << Kind << NewType << OldType;
2461 if (Old->getLocation().isValid())
2463 New->setInvalidDecl();
2464 return true;
2465 }
2466 return false;
2467}
2468
2470 LookupResult &OldDecls) {
2471 // If the new decl is known invalid already, don't bother doing any
2472 // merging checks.
2473 if (New->isInvalidDecl()) return;
2474
2475 // Allow multiple definitions for ObjC built-in typedefs.
2476 // FIXME: Verify the underlying types are equivalent!
2477 if (getLangOpts().ObjC) {
2478 const IdentifierInfo *TypeID = New->getIdentifier();
2479 switch (TypeID->getLength()) {
2480 default: break;
2481 case 2:
2482 {
2483 if (!TypeID->isStr("id"))
2484 break;
2485 QualType T = New->getUnderlyingType();
2486 if (!T->isPointerType())
2487 break;
2488 if (!T->isVoidPointerType()) {
2490 if (!PT->isStructureType())
2491 break;
2492 }
2494 // Install the built-in type for 'id', ignoring the current definition.
2496 return;
2497 }
2498 case 5:
2499 if (!TypeID->isStr("Class"))
2500 break;
2502 // Install the built-in type for 'Class', ignoring the current definition.
2504 return;
2505 case 3:
2506 if (!TypeID->isStr("SEL"))
2507 break;
2509 // Install the built-in type for 'SEL', ignoring the current definition.
2511 return;
2512 }
2513 // Fall through - the typedef name was not a builtin type.
2514 }
2515
2516 // Verify the old decl was also a type.
2517 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2518 if (!Old) {
2519 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2520 << New->getDeclName();
2521
2522 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2523 if (OldD->getLocation().isValid())
2524 notePreviousDefinition(OldD, New->getLocation());
2525
2526 return New->setInvalidDecl();
2527 }
2528
2529 // If the old declaration is invalid, just give up here.
2530 if (Old->isInvalidDecl())
2531 return New->setInvalidDecl();
2532
2533 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2534 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2535 auto *NewTag = New->getAnonDeclWithTypedefName();
2536 NamedDecl *Hidden = nullptr;
2537 if (OldTag && NewTag &&
2538 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2539 !hasVisibleDefinition(OldTag, &Hidden)) {
2540 // There is a definition of this tag, but it is not visible. Use it
2541 // instead of our tag.
2542 New->setTypeForDecl(OldTD->getTypeForDecl());
2543 if (OldTD->isModed())
2544 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2545 OldTD->getUnderlyingType());
2546 else
2547 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2548
2549 // Make the old tag definition visible.
2551
2552 // If this was an unscoped enumeration, yank all of its enumerators
2553 // out of the scope.
2554 if (isa<EnumDecl>(NewTag)) {
2555 Scope *EnumScope = getNonFieldDeclScope(S);
2556 for (auto *D : NewTag->decls()) {
2557 auto *ED = cast<EnumConstantDecl>(D);
2558 assert(EnumScope->isDeclScope(ED));
2559 EnumScope->RemoveDecl(ED);
2561 ED->getLexicalDeclContext()->removeDecl(ED);
2562 }
2563 }
2564 }
2565 }
2566
2567 // If the typedef types are not identical, reject them in all languages and
2568 // with any extensions enabled.
2569 if (isIncompatibleTypedef(Old, New))
2570 return;
2571
2572 // The types match. Link up the redeclaration chain and merge attributes if
2573 // the old declaration was a typedef.
2574 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2575 New->setPreviousDecl(Typedef);
2576 mergeDeclAttributes(New, Old);
2577 }
2578
2579 if (getLangOpts().MicrosoftExt)
2580 return;
2581
2582 if (getLangOpts().CPlusPlus) {
2583 // C++ [dcl.typedef]p2:
2584 // In a given non-class scope, a typedef specifier can be used to
2585 // redefine the name of any type declared in that scope to refer
2586 // to the type to which it already refers.
2587 if (!isa<CXXRecordDecl>(CurContext))
2588 return;
2589
2590 // C++0x [dcl.typedef]p4:
2591 // In a given class scope, a typedef specifier can be used to redefine
2592 // any class-name declared in that scope that is not also a typedef-name
2593 // to refer to the type to which it already refers.
2594 //
2595 // This wording came in via DR424, which was a correction to the
2596 // wording in DR56, which accidentally banned code like:
2597 //
2598 // struct S {
2599 // typedef struct A { } A;
2600 // };
2601 //
2602 // in the C++03 standard. We implement the C++0x semantics, which
2603 // allow the above but disallow
2604 //
2605 // struct S {
2606 // typedef int I;
2607 // typedef int I;
2608 // };
2609 //
2610 // since that was the intent of DR56.
2611 if (!isa<TypedefNameDecl>(Old))
2612 return;
2613
2614 Diag(New->getLocation(), diag::err_redefinition)
2615 << New->getDeclName();
2617 return New->setInvalidDecl();
2618 }
2619
2620 // Modules always permit redefinition of typedefs, as does C11.
2621 if (getLangOpts().Modules || getLangOpts().C11)
2622 return;
2623
2624 // If we have a redefinition of a typedef in C, emit a warning. This warning
2625 // is normally mapped to an error, but can be controlled with
2626 // -Wtypedef-redefinition. If either the original or the redefinition is
2627 // in a system header, don't emit this for compatibility with GCC.
2628 if (getDiagnostics().getSuppressSystemWarnings() &&
2629 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2630 (Old->isImplicit() ||
2633 return;
2634
2635 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2636 << New->getDeclName();
2638}
2639
2640/// DeclhasAttr - returns true if decl Declaration already has the target
2641/// attribute.
2642static bool DeclHasAttr(const Decl *D, const Attr *A) {
2643 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2644 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2645 for (const auto *i : D->attrs())
2646 if (i->getKind() == A->getKind()) {
2647 if (Ann) {
2648 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2649 return true;
2650 continue;
2651 }
2652 // FIXME: Don't hardcode this check
2653 if (OA && isa<OwnershipAttr>(i))
2654 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2655 return true;
2656 }
2657
2658 return false;
2659}
2660
2662 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2663 return VD->isThisDeclarationADefinition();
2664 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2665 return TD->isCompleteDefinition() || TD->isBeingDefined();
2666 return true;
2667}
2668
2669/// Merge alignment attributes from \p Old to \p New, taking into account the
2670/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2671///
2672/// \return \c true if any attributes were added to \p New.
2673static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2674 // Look for alignas attributes on Old, and pick out whichever attribute
2675 // specifies the strictest alignment requirement.
2676 AlignedAttr *OldAlignasAttr = nullptr;
2677 AlignedAttr *OldStrictestAlignAttr = nullptr;
2678 unsigned OldAlign = 0;
2679 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2680 // FIXME: We have no way of representing inherited dependent alignments
2681 // in a case like:
2682 // template<int A, int B> struct alignas(A) X;
2683 // template<int A, int B> struct alignas(B) X {};
2684 // For now, we just ignore any alignas attributes which are not on the
2685 // definition in such a case.
2686 if (I->isAlignmentDependent())
2687 return false;
2688
2689 if (I->isAlignas())
2690 OldAlignasAttr = I;
2691
2692 unsigned Align = I->getAlignment(S.Context);
2693 if (Align > OldAlign) {
2694 OldAlign = Align;
2695 OldStrictestAlignAttr = I;
2696 }
2697 }
2698
2699 // Look for alignas attributes on New.
2700 AlignedAttr *NewAlignasAttr = nullptr;
2701 unsigned NewAlign = 0;
2702 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2703 if (I->isAlignmentDependent())
2704 return false;
2705
2706 if (I->isAlignas())
2707 NewAlignasAttr = I;
2708
2709 unsigned Align = I->getAlignment(S.Context);
2710 if (Align > NewAlign)
2711 NewAlign = Align;
2712 }
2713
2714 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2715 // Both declarations have 'alignas' attributes. We require them to match.
2716 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2717 // fall short. (If two declarations both have alignas, they must both match
2718 // every definition, and so must match each other if there is a definition.)
2719
2720 // If either declaration only contains 'alignas(0)' specifiers, then it
2721 // specifies the natural alignment for the type.
2722 if (OldAlign == 0 || NewAlign == 0) {
2723 QualType Ty;
2724 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2725 Ty = VD->getType();
2726 else
2727 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2728
2729 if (OldAlign == 0)
2730 OldAlign = S.Context.getTypeAlign(Ty);
2731 if (NewAlign == 0)
2732 NewAlign = S.Context.getTypeAlign(Ty);
2733 }
2734
2735 if (OldAlign != NewAlign) {
2736 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2739 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2740 }
2741 }
2742
2743 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2744 // C++11 [dcl.align]p6:
2745 // if any declaration of an entity has an alignment-specifier,
2746 // every defining declaration of that entity shall specify an
2747 // equivalent alignment.
2748 // C11 6.7.5/7:
2749 // If the definition of an object does not have an alignment
2750 // specifier, any other declaration of that object shall also
2751 // have no alignment specifier.
2752 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2753 << OldAlignasAttr;
2754 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2755 << OldAlignasAttr;
2756 }
2757
2758 bool AnyAdded = false;
2759
2760 // Ensure we have an attribute representing the strictest alignment.
2761 if (OldAlign > NewAlign) {
2762 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2763 Clone->setInherited(true);
2764 New->addAttr(Clone);
2765 AnyAdded = true;
2766 }
2767
2768 // Ensure we have an alignas attribute if the old declaration had one.
2769 if (OldAlignasAttr && !NewAlignasAttr &&
2770 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2771 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2772 Clone->setInherited(true);
2773 New->addAttr(Clone);
2774 AnyAdded = true;
2775 }
2776
2777 return AnyAdded;
2778}
2779
2780#define WANT_DECL_MERGE_LOGIC
2781#include "clang/Sema/AttrParsedAttrImpl.inc"
2782#undef WANT_DECL_MERGE_LOGIC
2783
2785 const InheritableAttr *Attr,
2787 // Diagnose any mutual exclusions between the attribute that we want to add
2788 // and attributes that already exist on the declaration.
2789 if (!DiagnoseMutualExclusions(S, D, Attr))
2790 return false;
2791
2792 // This function copies an attribute Attr from a previous declaration to the
2793 // new declaration D if the new declaration doesn't itself have that attribute
2794 // yet or if that attribute allows duplicates.
2795 // If you're adding a new attribute that requires logic different from
2796 // "use explicit attribute on decl if present, else use attribute from
2797 // previous decl", for example if the attribute needs to be consistent
2798 // between redeclarations, you need to call a custom merge function here.
2799 InheritableAttr *NewAttr = nullptr;
2800 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2801 NewAttr = S.mergeAvailabilityAttr(
2802 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2803 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2804 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2805 AA->getPriority(), AA->getEnvironment());
2806 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2807 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2808 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2809 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2810 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2811 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2812 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2813 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2814 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2815 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2816 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2817 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2818 FA->getFirstArg());
2819 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2820 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2821 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2822 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2823 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2824 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2825 IA->getInheritanceModel());
2826 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2827 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2828 &S.Context.Idents.get(AA->getSpelling()));
2829 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2830 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2831 isa<CUDAGlobalAttr>(Attr))) {
2832 // CUDA target attributes are part of function signature for
2833 // overloading purposes and must not be merged.
2834 return false;
2835 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2836 NewAttr = S.mergeMinSizeAttr(D, *MA);
2837 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2838 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2839 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2840 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2841 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2842 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2843 else if (isa<AlignedAttr>(Attr))
2844 // AlignedAttrs are handled separately, because we need to handle all
2845 // such attributes on a declaration at the same time.
2846 NewAttr = nullptr;
2847 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2848 (AMK == Sema::AMK_Override ||
2851 NewAttr = nullptr;
2852 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2853 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2854 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2855 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2856 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2857 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2858 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2859 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2860 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2861 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2862 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2863 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2864 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2865 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2866 NT->getZ());
2867 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2868 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2869 WS->getPreferred(),
2870 WS->getSpelledArgsCount());
2871 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2872 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2873 else if (isa<SuppressAttr>(Attr))
2874 // Do nothing. Each redeclaration should be suppressed separately.
2875 NewAttr = nullptr;
2876 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2877 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2878
2879 if (NewAttr) {
2880 NewAttr->setInherited(true);
2881 D->addAttr(NewAttr);
2882 if (isa<MSInheritanceAttr>(NewAttr))
2883 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2884 return true;
2885 }
2886
2887 return false;
2888}
2889
2890static const NamedDecl *getDefinition(const Decl *D) {
2891 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2892 return TD->getDefinition();
2893 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2894 const VarDecl *Def = VD->getDefinition();
2895 if (Def)
2896 return Def;
2897 return VD->getActingDefinition();
2898 }
2899 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2900 const FunctionDecl *Def = nullptr;
2901 if (FD->isDefined(Def, true))
2902 return Def;
2903 }
2904 return nullptr;
2905}
2906
2907static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2908 for (const auto *Attribute : D->attrs())
2909 if (Attribute->getKind() == Kind)
2910 return true;
2911 return false;
2912}
2913
2914/// checkNewAttributesAfterDef - If we already have a definition, check that
2915/// there are no new attributes in this declaration.
2916static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2917 if (!New->hasAttrs())
2918 return;
2919
2920 const NamedDecl *Def = getDefinition(Old);
2921 if (!Def || Def == New)
2922 return;
2923
2924 AttrVec &NewAttributes = New->getAttrs();
2925 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2926 const Attr *NewAttribute = NewAttributes[I];
2927
2928 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2929 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2930 SkipBodyInfo SkipBody;
2931 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2932
2933 // If we're skipping this definition, drop the "alias" attribute.
2934 if (SkipBody.ShouldSkip) {
2935 NewAttributes.erase(NewAttributes.begin() + I);
2936 --E;
2937 continue;
2938 }
2939 } else {
2940 VarDecl *VD = cast<VarDecl>(New);
2941 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2943 ? diag::err_alias_after_tentative
2944 : diag::err_redefinition;
2945 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2946 if (Diag == diag::err_redefinition)
2947 S.notePreviousDefinition(Def, VD->getLocation());
2948 else
2949 S.Diag(Def->getLocation(), diag::note_previous_definition);
2950 VD->setInvalidDecl();
2951 }
2952 ++I;
2953 continue;
2954 }
2955
2956 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2957 // Tentative definitions are only interesting for the alias check above.
2958 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2959 ++I;
2960 continue;
2961 }
2962 }
2963
2964 if (hasAttribute(Def, NewAttribute->getKind())) {
2965 ++I;
2966 continue; // regular attr merging will take care of validating this.
2967 }
2968
2969 if (isa<C11NoReturnAttr>(NewAttribute)) {
2970 // C's _Noreturn is allowed to be added to a function after it is defined.
2971 ++I;
2972 continue;
2973 } else if (isa<UuidAttr>(NewAttribute)) {
2974 // msvc will allow a subsequent definition to add an uuid to a class
2975 ++I;
2976 continue;
2977 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2978 if (AA->isAlignas()) {
2979 // C++11 [dcl.align]p6:
2980 // if any declaration of an entity has an alignment-specifier,
2981 // every defining declaration of that entity shall specify an
2982 // equivalent alignment.
2983 // C11 6.7.5/7:
2984 // If the definition of an object does not have an alignment
2985 // specifier, any other declaration of that object shall also
2986 // have no alignment specifier.
2987 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2988 << AA;
2989 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2990 << AA;
2991 NewAttributes.erase(NewAttributes.begin() + I);
2992 --E;
2993 continue;
2994 }
2995 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2996 // If there is a C definition followed by a redeclaration with this
2997 // attribute then there are two different definitions. In C++, prefer the
2998 // standard diagnostics.
2999 if (!S.getLangOpts().CPlusPlus) {
3000 S.Diag(NewAttribute->getLocation(),
3001 diag::err_loader_uninitialized_redeclaration);
3002 S.Diag(Def->getLocation(), diag::note_previous_definition);
3003 NewAttributes.erase(NewAttributes.begin() + I);
3004 --E;
3005 continue;
3006 }
3007 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3008 cast<VarDecl>(New)->isInline() &&
3009 !cast<VarDecl>(New)->isInlineSpecified()) {
3010 // Don't warn about applying selectany to implicitly inline variables.
3011 // Older compilers and language modes would require the use of selectany
3012 // to make such variables inline, and it would have no effect if we
3013 // honored it.
3014 ++I;
3015 continue;
3016 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3017 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3018 // declarations after definitions.
3019 ++I;
3020 continue;
3021 }
3022
3023 S.Diag(NewAttribute->getLocation(),
3024 diag::warn_attribute_precede_definition);
3025 S.Diag(Def->getLocation(), diag::note_previous_definition);
3026 NewAttributes.erase(NewAttributes.begin() + I);
3027 --E;
3028 }
3029}
3030
3031static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3032 const ConstInitAttr *CIAttr,
3033 bool AttrBeforeInit) {
3034 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3035
3036 // Figure out a good way to write this specifier on the old declaration.
3037 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3038 // enough of the attribute list spelling information to extract that without
3039 // heroics.
3040 std::string SuitableSpelling;
3041 if (S.getLangOpts().CPlusPlus20)
3042 SuitableSpelling = std::string(
3043 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3044 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3045 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3046 InsertLoc, {tok::l_square, tok::l_square,
3047 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3048 S.PP.getIdentifierInfo("require_constant_initialization"),
3049 tok::r_square, tok::r_square}));
3050 if (SuitableSpelling.empty())
3051 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3052 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3053 S.PP.getIdentifierInfo("require_constant_initialization"),
3054 tok::r_paren, tok::r_paren}));
3055 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3056 SuitableSpelling = "constinit";
3057 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3058 SuitableSpelling = "[[clang::require_constant_initialization]]";
3059 if (SuitableSpelling.empty())
3060 SuitableSpelling = "__attribute__((require_constant_initialization))";
3061 SuitableSpelling += " ";
3062
3063 if (AttrBeforeInit) {
3064 // extern constinit int a;
3065 // int a = 0; // error (missing 'constinit'), accepted as extension
3066 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3067 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3068 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3069 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3070 } else {
3071 // int a = 0;
3072 // constinit extern int a; // error (missing 'constinit')
3073 S.Diag(CIAttr->getLocation(),
3074 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3075 : diag::warn_require_const_init_added_too_late)
3076 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3077 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3078 << CIAttr->isConstinit()
3079 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3080 }
3081}
3082
3085 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3086 UsedAttr *NewAttr = OldAttr->clone(Context);
3087 NewAttr->setInherited(true);
3088 New->addAttr(NewAttr);
3089 }
3090 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3091 RetainAttr *NewAttr = OldAttr->clone(Context);
3092 NewAttr->setInherited(true);
3093 New->addAttr(NewAttr);
3094 }
3095
3096 if (!Old->hasAttrs() && !New->hasAttrs())
3097 return;
3098
3099 // [dcl.constinit]p1:
3100 // If the [constinit] specifier is applied to any declaration of a
3101 // variable, it shall be applied to the initializing declaration.
3102 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3103 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3104 if (bool(OldConstInit) != bool(NewConstInit)) {
3105 const auto *OldVD = cast<VarDecl>(Old);
3106 auto *NewVD = cast<VarDecl>(New);
3107
3108 // Find the initializing declaration. Note that we might not have linked
3109 // the new declaration into the redeclaration chain yet.
3110 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3111 if (!InitDecl &&
3112 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3113 InitDecl = NewVD;
3114
3115 if (InitDecl == NewVD) {
3116 // This is the initializing declaration. If it would inherit 'constinit',
3117 // that's ill-formed. (Note that we do not apply this to the attribute
3118 // form).
3119 if (OldConstInit && OldConstInit->isConstinit())
3120 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3121 /*AttrBeforeInit=*/true);
3122 } else if (NewConstInit) {
3123 // This is the first time we've been told that this declaration should
3124 // have a constant initializer. If we already saw the initializing
3125 // declaration, this is too late.
3126 if (InitDecl && InitDecl != NewVD) {
3127 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3128 /*AttrBeforeInit=*/false);
3129 NewVD->dropAttr<ConstInitAttr>();
3130 }
3131 }
3132 }
3133
3134 // Attributes declared post-definition are currently ignored.
3135 checkNewAttributesAfterDef(*this, New, Old);
3136
3137 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3138 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3139 if (!OldA->isEquivalent(NewA)) {
3140 // This redeclaration changes __asm__ label.
3141 Diag(New->getLocation(), diag::err_different_asm_label);
3142 Diag(OldA->getLocation(), diag::note_previous_declaration);
3143 }
3144 } else if (Old->isUsed()) {
3145 // This redeclaration adds an __asm__ label to a declaration that has
3146 // already been ODR-used.
3147 Diag(New->getLocation(), diag::err_late_asm_label_name)
3148 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3149 }
3150 }
3151
3152 // Re-declaration cannot add abi_tag's.
3153 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3154 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3155 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3156 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3157 Diag(NewAbiTagAttr->getLocation(),
3158 diag::err_new_abi_tag_on_redeclaration)
3159 << NewTag;
3160 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3161 }
3162 }
3163 } else {
3164 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3165 Diag(Old->getLocation(), diag::note_previous_declaration);
3166 }
3167 }
3168
3169 // This redeclaration adds a section attribute.
3170 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3171 if (auto *VD = dyn_cast<VarDecl>(New)) {
3172 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3173 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3174 Diag(Old->getLocation(), diag::note_previous_declaration);
3175 }
3176 }
3177 }
3178
3179 // Redeclaration adds code-seg attribute.
3180 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3181 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3182 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3183 Diag(New->getLocation(), diag::warn_mismatched_section)
3184 << 0 /*codeseg*/;
3185 Diag(Old->getLocation(), diag::note_previous_declaration);
3186 }
3187
3188 if (!Old->hasAttrs())
3189 return;
3190
3191 bool foundAny = New->hasAttrs();
3192
3193 // Ensure that any moving of objects within the allocated map is done before
3194 // we process them.
3195 if (!foundAny) New->setAttrs(AttrVec());
3196
3197 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3198 // Ignore deprecated/unavailable/availability attributes if requested.
3200 if (isa<DeprecatedAttr>(I) ||
3201 isa<UnavailableAttr>(I) ||
3202 isa<AvailabilityAttr>(I)) {
3203 switch (AMK) {
3204 case AMK_None:
3205 continue;
3206
3207 case AMK_Redeclaration:
3208 case AMK_Override:
3211 LocalAMK = AMK;
3212 break;
3213 }
3214 }
3215
3216 // Already handled.
3217 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3218 continue;
3219
3220 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3221 foundAny = true;
3222 }
3223
3224 if (mergeAlignedAttrs(*this, New, Old))
3225 foundAny = true;
3226
3227 if (!foundAny) New->dropAttrs();
3228}
3229
3230/// mergeParamDeclAttributes - Copy attributes from the old parameter
3231/// to the new one.
3233 const ParmVarDecl *oldDecl,
3234 Sema &S) {
3235 // C++11 [dcl.attr.depend]p2:
3236 // The first declaration of a function shall specify the
3237 // carries_dependency attribute for its declarator-id if any declaration
3238 // of the function specifies the carries_dependency attribute.
3239 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3240 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3241 S.Diag(CDA->getLocation(),
3242 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3243 // Find the first declaration of the parameter.
3244 // FIXME: Should we build redeclaration chains for function parameters?
3245 const FunctionDecl *FirstFD =
3246 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3247 const ParmVarDecl *FirstVD =
3248 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3249 S.Diag(FirstVD->getLocation(),
3250 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3251 }
3252
3253 if (!oldDecl->hasAttrs())
3254 return;
3255
3256 bool foundAny = newDecl->hasAttrs();
3257
3258 // Ensure that any moving of objects within the allocated map is
3259 // done before we process them.
3260 if (!foundAny) newDecl->setAttrs(AttrVec());
3261
3262 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3263 if (!DeclHasAttr(newDecl, I)) {
3264 InheritableAttr *newAttr =
3265 cast<InheritableParamAttr>(I->clone(S.Context));
3266 newAttr->setInherited(true);
3267 newDecl->addAttr(newAttr);
3268 foundAny = true;
3269 }
3270 }
3271
3272 if (!foundAny) newDecl->dropAttrs();
3273}
3274
3276 const ASTContext &Ctx) {
3277
3278 auto NoSizeInfo = [&Ctx](QualType Ty) {
3279 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3280 return true;
3281 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3282 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3283 return false;
3284 };
3285
3286 // `type[]` is equivalent to `type *` and `type[*]`.
3287 if (NoSizeInfo(Old) && NoSizeInfo(New))
3288 return true;
3289
3290 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3291 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3292 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3293 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3294 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3295 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3296 return false;
3297 return true;
3298 }
3299
3300 // Only compare size, ignore Size modifiers and CVR.
3301 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3302 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3303 Ctx.getAsConstantArrayType(New)->getSize();
3304 }
3305
3306 // Don't try to compare dependent sized array
3308 return true;
3309 }
3310
3311 return Old == New;
3312}
3313
3314static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3315 const ParmVarDecl *OldParam,
3316 Sema &S) {
3317 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3318 if (auto Newnullability = NewParam->getType()->getNullability()) {
3319 if (*Oldnullability != *Newnullability) {
3320 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3322 *Newnullability,
3324 != 0))
3326 *Oldnullability,
3328 != 0));
3329 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3330 }
3331 } else {
3332 QualType NewT = NewParam->getType();
3333 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3334 NewParam->setType(NewT);
3335 }
3336 }
3337 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3338 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3339 if (OldParamDT && NewParamDT &&
3340 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3341 QualType OldParamOT = OldParamDT->getOriginalType();
3342 QualType NewParamOT = NewParamDT->getOriginalType();
3343 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3344 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3345 << NewParam << NewParamOT;
3346 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3347 << OldParamOT;
3348 }
3349 }
3350}
3351
3352namespace {
3353
3354/// Used in MergeFunctionDecl to keep track of function parameters in
3355/// C.
3356struct GNUCompatibleParamWarning {
3357 ParmVarDecl *OldParm;
3358 ParmVarDecl *NewParm;
3359 QualType PromotedType;
3360};
3361
3362} // end anonymous namespace
3363
3364// Determine whether the previous declaration was a definition, implicit
3365// declaration, or a declaration.
3366template <typename T>
3367static std::pair<diag::kind, SourceLocation>
3368getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3369 diag::kind PrevDiag;
3370 SourceLocation OldLocation = Old->getLocation();
3371 if (Old->isThisDeclarationADefinition())
3372 PrevDiag = diag::note_previous_definition;
3373 else if (Old->isImplicit()) {
3374 PrevDiag = diag::note_previous_implicit_declaration;
3375 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3376 if (FD->getBuiltinID())
3377 PrevDiag = diag::note_previous_builtin_declaration;
3378 }
3379 if (OldLocation.isInvalid())
3380 OldLocation = New->getLocation();
3381 } else
3382 PrevDiag = diag::note_previous_declaration;
3383 return std::make_pair(PrevDiag, OldLocation);
3384}
3385
3386/// canRedefineFunction - checks if a function can be redefined. Currently,
3387/// only extern inline functions can be redefined, and even then only in
3388/// GNU89 mode.
3389static bool canRedefineFunction(const FunctionDecl *FD,
3390 const LangOptions& LangOpts) {
3391 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3392 !LangOpts.CPlusPlus &&
3393 FD->isInlineSpecified() &&
3394 FD->getStorageClass() == SC_Extern);
3395}
3396
3398 const AttributedType *AT = T->getAs<AttributedType>();
3399 while (AT && !AT->isCallingConv())
3400 AT = AT->getModifiedType()->getAs<AttributedType>();
3401 return AT;
3402}
3403
3404template <typename T>
3405static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3406 const DeclContext *DC = Old->getDeclContext();
3407 if (DC->isRecord())
3408 return false;
3409
3410 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3411 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3412 return true;
3413 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3414 return true;
3415 return false;
3416}
3417
3418template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3419static bool isExternC(VarTemplateDecl *) { return false; }
3420static bool isExternC(FunctionTemplateDecl *) { return false; }
3421
3422/// Check whether a redeclaration of an entity introduced by a
3423/// using-declaration is valid, given that we know it's not an overload
3424/// (nor a hidden tag declaration).
3425template<typename ExpectedDecl>
3427 ExpectedDecl *New) {
3428 // C++11 [basic.scope.declarative]p4:
3429 // Given a set of declarations in a single declarative region, each of
3430 // which specifies the same unqualified name,
3431 // -- they shall all refer to the same entity, or all refer to functions
3432 // and function templates; or
3433 // -- exactly one declaration shall declare a class name or enumeration
3434 // name that is not a typedef name and the other declarations shall all
3435 // refer to the same variable or enumerator, or all refer to functions
3436 // and function templates; in this case the class name or enumeration
3437 // name is hidden (3.3.10).
3438
3439 // C++11 [namespace.udecl]p14:
3440 // If a function declaration in namespace scope or block scope has the
3441 // same name and the same parameter-type-list as a function introduced
3442 // by a using-declaration, and the declarations do not declare the same
3443 // function, the program is ill-formed.
3444
3445 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3446 if (Old &&
3447 !Old->getDeclContext()->getRedeclContext()->Equals(
3448 New->getDeclContext()->getRedeclContext()) &&
3449 !(isExternC(Old) && isExternC(New)))
3450 Old = nullptr;
3451
3452 if (!Old) {
3453 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3454 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3455 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3456 return true;
3457 }
3458 return false;
3459}
3460
3462 const FunctionDecl *B) {
3463 assert(A->getNumParams() == B->getNumParams());
3464
3465 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3466 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3467 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3468 if (AttrA == AttrB)
3469 return true;
3470 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3471 AttrA->isDynamic() == AttrB->isDynamic();
3472 };
3473
3474 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3475}
3476
3477/// If necessary, adjust the semantic declaration context for a qualified
3478/// declaration to name the correct inline namespace within the qualifier.
3480 DeclaratorDecl *OldD) {
3481 // The only case where we need to update the DeclContext is when
3482 // redeclaration lookup for a qualified name finds a declaration
3483 // in an inline namespace within the context named by the qualifier:
3484 //
3485 // inline namespace N { int f(); }
3486 // int ::f(); // Sema DC needs adjusting from :: to N::.
3487 //
3488 // For unqualified declarations, the semantic context *can* change
3489 // along the redeclaration chain (for local extern declarations,
3490 // extern "C" declarations, and friend declarations in particular).
3491 if (!NewD->getQualifier())
3492 return;
3493
3494 // NewD is probably already in the right context.
3495 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3496 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3497 if (NamedDC->Equals(SemaDC))
3498 return;
3499
3500 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3501 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3502 "unexpected context for redeclaration");
3503
3504 auto *LexDC = NewD->getLexicalDeclContext();
3505 auto FixSemaDC = [=](NamedDecl *D) {
3506 if (!D)
3507 return;
3508 D->setDeclContext(SemaDC);
3509 D->setLexicalDeclContext(LexDC);
3510 };
3511
3512 FixSemaDC(NewD);
3513 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3514 FixSemaDC(FD->getDescribedFunctionTemplate());
3515 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3516 FixSemaDC(VD->getDescribedVarTemplate());
3517}
3518
3520 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3521 // Verify the old decl was also a function.
3522 FunctionDecl *Old = OldD->getAsFunction();
3523 if (!Old) {
3524 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3525 if (New->getFriendObjectKind()) {
3526 Diag(New->getLocation(), diag::err_using_decl_friend);
3527 Diag(Shadow->getTargetDecl()->getLocation(),
3528 diag::note_using_decl_target);
3529 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3530 << 0;
3531 return true;
3532 }
3533
3534 // Check whether the two declarations might declare the same function or
3535 // function template.
3536 if (FunctionTemplateDecl *NewTemplate =
3538 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3539 NewTemplate))
3540 return true;
3541 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3542 ->getAsFunction();
3543 } else {
3544 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3545 return true;
3546 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3547 }
3548 } else {
3549 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3550 << New->getDeclName();
3551 notePreviousDefinition(OldD, New->getLocation());
3552 return true;
3553 }
3554 }
3555
3556 // If the old declaration was found in an inline namespace and the new
3557 // declaration was qualified, update the DeclContext to match.
3559
3560 // If the old declaration is invalid, just give up here.
3561 if (Old->isInvalidDecl())
3562 return true;
3563
3564 // Disallow redeclaration of some builtins.
3565 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3566 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3567 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3568 << Old << Old->getType();
3569 return true;
3570 }
3571
3572 diag::kind PrevDiag;
3573 SourceLocation OldLocation;
3574 std::tie(PrevDiag, OldLocation) =
3576
3577 // Don't complain about this if we're in GNU89 mode and the old function
3578 // is an extern inline function.
3579 // Don't complain about specializations. They are not supposed to have
3580 // storage classes.
3581 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3582 New->getStorageClass() == SC_Static &&
3583 Old->hasExternalFormalLinkage() &&
3586 if (getLangOpts().MicrosoftExt) {
3587 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3588 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3589 } else {
3590 Diag(New->getLocation(), diag::err_static_non_static) << New;
3591 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3592 return true;
3593 }
3594 }
3595
3596 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3597 if (!Old->hasAttr<InternalLinkageAttr>()) {
3598 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3599 << ILA;
3600 Diag(Old->getLocation(), diag::note_previous_declaration);
3601 New->dropAttr<InternalLinkageAttr>();
3602 }
3603
3604 if (auto *EA = New->getAttr<ErrorAttr>()) {
3605 if (!Old->hasAttr<ErrorAttr>()) {
3606 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3607 Diag(Old->getLocation(), diag::note_previous_declaration);
3608 New->dropAttr<ErrorAttr>();
3609 }
3610 }
3611
3612 if (CheckRedeclarationInModule(New, Old))
3613 return true;
3614
3615 if (!getLangOpts().CPlusPlus) {
3616 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3617 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3618 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3619 << New << OldOvl;
3620
3621 // Try our best to find a decl that actually has the overloadable
3622 // attribute for the note. In most cases (e.g. programs with only one
3623 // broken declaration/definition), this won't matter.
3624 //
3625 // FIXME: We could do this if we juggled some extra state in
3626 // OverloadableAttr, rather than just removing it.
3627 const Decl *DiagOld = Old;
3628 if (OldOvl) {
3629 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3630 const auto *A = D->getAttr<OverloadableAttr>();
3631 return A && !A->isImplicit();
3632 });
3633 // If we've implicitly added *all* of the overloadable attrs to this
3634 // chain, emitting a "previous redecl" note is pointless.
3635 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3636 }
3637
3638 if (DiagOld)
3639 Diag(DiagOld->getLocation(),
3640 diag::note_attribute_overloadable_prev_overload)
3641 << OldOvl;
3642
3643 if (OldOvl)
3644 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3645 else
3646 New->dropAttr<OverloadableAttr>();
3647 }
3648 }
3649
3650 // It is not permitted to redeclare an SME function with different SME
3651 // attributes.
3652 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3653 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3654 << New->getType() << Old->getType();
3655 Diag(OldLocation, diag::note_previous_declaration);
3656 return true;
3657 }
3658
3659 // If a function is first declared with a calling convention, but is later
3660 // declared or defined without one, all following decls assume the calling
3661 // convention of the first.
3662 //
3663 // It's OK if a function is first declared without a calling convention,
3664 // but is later declared or defined with the default calling convention.
3665 //
3666 // To test if either decl has an explicit calling convention, we look for
3667 // AttributedType sugar nodes on the type as written. If they are missing or
3668 // were canonicalized away, we assume the calling convention was implicit.
3669 //
3670 // Note also that we DO NOT return at this point, because we still have
3671 // other tests to run.
3672 QualType OldQType = Context.getCanonicalType(Old->getType());
3673 QualType NewQType = Context.getCanonicalType(New->getType());
3674 const FunctionType *OldType = cast<FunctionType>(OldQType);
3675 const FunctionType *NewType = cast<FunctionType>(NewQType);
3676 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3677 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3678 bool RequiresAdjustment = false;
3679
3680 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3682 const FunctionType *FT =
3683 First->getType().getCanonicalType()->castAs<FunctionType>();
3685 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3686 if (!NewCCExplicit) {
3687 // Inherit the CC from the previous declaration if it was specified
3688 // there but not here.
3689 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3690 RequiresAdjustment = true;
3691 } else if (Old->getBuiltinID()) {
3692 // Builtin attribute isn't propagated to the new one yet at this point,
3693 // so we check if the old one is a builtin.
3694
3695 // Calling Conventions on a Builtin aren't really useful and setting a
3696 // default calling convention and cdecl'ing some builtin redeclarations is
3697 // common, so warn and ignore the calling convention on the redeclaration.
3698 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3699 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3701 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3702 RequiresAdjustment = true;
3703 } else {
3704 // Calling conventions aren't compatible, so complain.
3705 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3706 Diag(New->getLocation(), diag::err_cconv_change)
3707 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3708 << !FirstCCExplicit
3709 << (!FirstCCExplicit ? "" :
3711
3712 // Put the note on the first decl, since it is the one that matters.
3713 Diag(First->getLocation(), diag::note_previous_declaration);
3714 return true;
3715 }
3716 }
3717
3718 // FIXME: diagnose the other way around?
3719 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3720 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3721 RequiresAdjustment = true;
3722 }
3723
3724 // Merge regparm attribute.
3725 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3726 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3727 if (NewTypeInfo.getHasRegParm()) {
3728 Diag(New->getLocation(), diag::err_regparm_mismatch)
3729 << NewType->getRegParmType()
3730 << OldType->getRegParmType();
3731 Diag(OldLocation, diag::note_previous_declaration);
3732 return true;
3733 }
3734
3735 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3736 RequiresAdjustment = true;
3737 }
3738
3739 // Merge ns_returns_retained attribute.
3740 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3741 if (NewTypeInfo.getProducesResult()) {
3742 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3743 << "'ns_returns_retained'";
3744 Diag(OldLocation, diag::note_previous_declaration);
3745 return true;
3746 }
3747
3748 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3749 RequiresAdjustment = true;
3750 }
3751
3752 if (OldTypeInfo.getNoCallerSavedRegs() !=
3753 NewTypeInfo.getNoCallerSavedRegs()) {
3754 if (NewTypeInfo.getNoCallerSavedRegs()) {
3755 AnyX86NoCallerSavedRegistersAttr *Attr =
3756 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3757 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3758 Diag(OldLocation, diag::note_previous_declaration);
3759 return true;
3760 }
3761
3762 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3763 RequiresAdjustment = true;
3764 }
3765
3766 if (RequiresAdjustment) {
3769 New->setType(QualType(AdjustedType, 0));
3770 NewQType = Context.getCanonicalType(New->getType());
3771 }
3772
3773 // If this redeclaration makes the function inline, we may need to add it to
3774 // UndefinedButUsed.
3775 if (!Old->isInlined() && New->isInlined() &&
3776 !New->hasAttr<GNUInlineAttr>() &&
3777 !getLangOpts().GNUInline &&
3778 Old->isUsed(false) &&
3779 !Old->isDefined() && !New->isThisDeclarationADefinition())
3780 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3781 SourceLocation()));
3782
3783 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3784 // about it.
3785 if (New->hasAttr<GNUInlineAttr>() &&
3786 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3787 UndefinedButUsed.erase(Old->getCanonicalDecl());
3788 }
3789
3790 // If pass_object_size params don't match up perfectly, this isn't a valid
3791 // redeclaration.
3792 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3794 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3795 << New->getDeclName();
3796 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3797 return true;
3798 }
3799
3800 QualType OldQTypeForComparison = OldQType;
3802 const auto OldFX = Old->getFunctionEffects();
3803 const auto NewFX = New->getFunctionEffects();
3804 if (OldFX != NewFX) {
3805 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
3806 for (const auto &Diff : Diffs) {
3807 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3808 Diag(New->getLocation(),
3809 diag::warn_mismatched_func_effect_redeclaration)
3810 << Diff.effectName();
3811 Diag(Old->getLocation(), diag::note_previous_declaration);
3812 }
3813 }
3814 // Following a warning, we could skip merging effects from the previous
3815 // declaration, but that would trigger an additional "conflicting types"
3816 // error.
3817 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3819 FunctionEffectSet MergedFX =
3820 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3821 if (!MergeErrs.empty())
3823 Old->getLocation());
3824
3825 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3826 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3827 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3828 NewFPT->getParamTypes(), EPI);
3829
3830 New->setType(ModQT);
3831 NewQType = New->getType();
3832
3833 // Revise OldQTForComparison to include the merged effects,
3834 // so as not to fail due to differences later.
3835 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3836 EPI = OldFPT->getExtProtoInfo();
3837 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3838 OldQTypeForComparison = Context.getFunctionType(
3839 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3840 }
3841 if (OldFX.empty()) {
3842 // A redeclaration may add the attribute to a previously seen function
3843 // body which needs to be verified.
3844 maybeAddDeclWithEffects(Old, MergedFX);
3845 }
3846 }
3847 }
3848 }
3849
3850 if (getLangOpts().CPlusPlus) {
3851 OldQType = Context.getCanonicalType(Old->getType());
3852 NewQType = Context.getCanonicalType(New->getType());
3853
3854 // Go back to the type source info to compare the declared return types,
3855 // per C++1y [dcl.type.auto]p13:
3856 // Redeclarations or specializations of a function or function template
3857 // with a declared return type that uses a placeholder type shall also
3858 // use that placeholder, not a deduced type.
3859 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3860 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3861 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3862 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3863 OldDeclaredReturnType)) {
3864 QualType ResQT;
3865 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3866 OldDeclaredReturnType->isObjCObjectPointerType())
3867 // FIXME: This does the wrong thing for a deduced return type.
3868 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3869 if (ResQT.isNull()) {
3870 if (New->isCXXClassMember() && New->isOutOfLine())
3871 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3872 << New << New->getReturnTypeSourceRange();
3873 else if (Old->isExternC() && New->isExternC() &&
3874 !Old->hasAttr<OverloadableAttr>() &&
3875 !New->hasAttr<OverloadableAttr>())
3876 Diag(New->getLocation(), diag::err_conflicting_types) << New;
3877 else
3878 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3879 << New->getReturnTypeSourceRange();
3880 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3881 << Old->getReturnTypeSourceRange();
3882 return true;
3883 }
3884 else
3885 NewQType = ResQT;
3886 }
3887
3888 QualType OldReturnType = OldType->getReturnType();
3889 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3890 if (OldReturnType != NewReturnType) {
3891 // If this function has a deduced return type and has already been
3892 // defined, copy the deduced value from the old declaration.
3893 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3894 if (OldAT && OldAT->isDeduced()) {
3895 QualType DT = OldAT->getDeducedType();
3896 if (DT.isNull()) {
3898 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3899 } else {
3900 New->setType(SubstAutoType(New->getType(), DT));
3901 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3902 }
3903 }
3904 }
3905
3906 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3907 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3908 if (OldMethod && NewMethod) {
3909 // Preserve triviality.
3910 NewMethod->setTrivial(OldMethod->isTrivial());
3911
3912 // MSVC allows explicit template specialization at class scope:
3913 // 2 CXXMethodDecls referring to the same function will be injected.
3914 // We don't want a redeclaration error.
3915 bool IsClassScopeExplicitSpecialization =
3916 OldMethod->isFunctionTemplateSpecialization() &&
3918 bool isFriend = NewMethod->getFriendObjectKind();
3919
3920 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3921 !IsClassScopeExplicitSpecialization) {
3922 // -- Member function declarations with the same name and the
3923 // same parameter types cannot be overloaded if any of them
3924 // is a static member function declaration.
3925 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3926 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3927 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3928 return true;
3929 }
3930
3931 // C++ [class.mem]p1:
3932 // [...] A member shall not be declared twice in the
3933 // member-specification, except that a nested class or member
3934 // class template can be declared and then later defined.
3935 if (!inTemplateInstantiation()) {
3936 unsigned NewDiag;
3937 if (isa<CXXConstructorDecl>(OldMethod))
3938 NewDiag = diag::err_constructor_redeclared;
3939 else if (isa<CXXDestructorDecl>(NewMethod))
3940 NewDiag = diag::err_destructor_redeclared;
3941 else if (isa<CXXConversionDecl>(NewMethod))
3942 NewDiag = diag::err_conv_function_redeclared;
3943 else
3944 NewDiag = diag::err_member_redeclared;
3945
3946 Diag(New->getLocation(), NewDiag);
3947 } else {
3948 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3949 << New << New->getType();
3950 }
3951 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3952 return true;
3953
3954 // Complain if this is an explicit declaration of a special
3955 // member that was initially declared implicitly.
3956 //
3957 // As an exception, it's okay to befriend such methods in order
3958 // to permit the implicit constructor/destructor/operator calls.
3959 } else if (OldMethod->isImplicit()) {
3960 if (isFriend) {
3961 NewMethod->setImplicit();
3962 } else {
3963 Diag(NewMethod->getLocation(),
3964 diag::err_definition_of_implicitly_declared_member)
3965 << New << llvm::to_underlying(getSpecialMember(OldMethod));
3966 return true;
3967 }
3968 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3969 Diag(NewMethod->getLocation(),
3970 diag::err_definition_of_explicitly_defaulted_member)
3971 << llvm::to_underlying(getSpecialMember(OldMethod));
3972 return true;
3973 }
3974 }
3975
3976 // C++1z [over.load]p2
3977 // Certain function declarations cannot be overloaded:
3978 // -- Function declarations that differ only in the return type,
3979 // the exception specification, or both cannot be overloaded.
3980
3981 // Check the exception specifications match. This may recompute the type of
3982 // both Old and New if it resolved exception specifications, so grab the
3983 // types again after this. Because this updates the type, we do this before
3984 // any of the other checks below, which may update the "de facto" NewQType
3985 // but do not necessarily update the type of New.
3986 if (CheckEquivalentExceptionSpec(Old, New))
3987 return true;
3988
3989 // C++11 [dcl.attr.noreturn]p1:
3990 // The first declaration of a function shall specify the noreturn
3991 // attribute if any declaration of that function specifies the noreturn
3992 // attribute.
3993 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3994 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3995 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3996 << NRA;
3997 Diag(Old->getLocation(), diag::note_previous_declaration);
3998 }
3999
4000 // C++11 [dcl.attr.depend]p2:
4001 // The first declaration of a function shall specify the
4002 // carries_dependency attribute for its declarator-id if any declaration
4003 // of the function specifies the carries_dependency attribute.
4004 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4005 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4006 Diag(CDA->getLocation(),
4007 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4008 Diag(Old->getFirstDecl()->getLocation(),
4009 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4010 }
4011
4012 // (C++98 8.3.5p3):
4013 // All declarations for a function shall agree exactly in both the
4014 // return type and the parameter-type-list.
4015 // We also want to respect all the extended bits except noreturn.
4016
4017 // noreturn should now match unless the old type info didn't have it.
4018 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4019 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4020 const FunctionType *OldTypeForComparison
4021 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4022 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4023 assert(OldQTypeForComparison.isCanonical());
4024 }
4025
4026 if (haveIncompatibleLanguageLinkages(Old, New)) {
4027 // As a special case, retain the language linkage from previous
4028 // declarations of a friend function as an extension.
4029 //
4030 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4031 // and is useful because there's otherwise no way to specify language
4032 // linkage within class scope.
4033 //
4034 // Check cautiously as the friend object kind isn't yet complete.
4035 if (New->getFriendObjectKind() != Decl::FOK_None) {
4036 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4037 Diag(OldLocation, PrevDiag);
4038 } else {
4039 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4040 Diag(OldLocation, PrevDiag);
4041 return true;
4042 }
4043 }
4044
4045 // HLSL check parameters for matching ABI specifications.
4046 if (getLangOpts().HLSL) {
4047 if (HLSL().CheckCompatibleParameterABI(New, Old))
4048 return true;
4049
4050 // If no errors are generated when checking parameter ABIs we can check if
4051 // the two declarations have the same type ignoring the ABIs and if so,
4052 // the declarations can be merged. This case for merging is only valid in
4053 // HLSL because there are no valid cases of merging mismatched parameter
4054 // ABIs except the HLSL implicit in and explicit in.
4055 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4056 NewQType))
4057 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4058 // Fall through for conflicting redeclarations and redefinitions.
4059 }
4060
4061 // If the function types are compatible, merge the declarations. Ignore the
4062 // exception specifier because it was already checked above in
4063 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4064 // about incompatible types under -fms-compatibility.
4065 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4066 NewQType))
4067 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4068
4069 // If the types are imprecise (due to dependent constructs in friends or
4070 // local extern declarations), it's OK if they differ. We'll check again
4071 // during instantiation.
4072 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4073 return false;
4074
4075 // Fall through for conflicting redeclarations and redefinitions.
4076 }
4077
4078 // C: Function types need to be compatible, not identical. This handles
4079 // duplicate function decls like "void f(int); void f(enum X);" properly.
4080 if (!getLangOpts().CPlusPlus) {
4081 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4082 // type is specified by a function definition that contains a (possibly
4083 // empty) identifier list, both shall agree in the number of parameters
4084 // and the type of each parameter shall be compatible with the type that
4085 // results from the application of default argument promotions to the
4086 // type of the corresponding identifier. ...
4087 // This cannot be handled by ASTContext::typesAreCompatible() because that
4088 // doesn't know whether the function type is for a definition or not when
4089 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4090 // we need to cover here is that the number of arguments agree as the
4091 // default argument promotion rules were already checked by
4092 // ASTContext::typesAreCompatible().
4093 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4094 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4095 if (Old->hasInheritedPrototype())
4096 Old = Old->getCanonicalDecl();
4097 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4098 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4099 return true;
4100 }
4101
4102 // If we are merging two functions where only one of them has a prototype,
4103 // we may have enough information to decide to issue a diagnostic that the
4104 // function without a prototype will change behavior in C23. This handles
4105 // cases like:
4106 // void i(); void i(int j);
4107 // void i(int j); void i();
4108 // void i(); void i(int j) {}
4109 // See ActOnFinishFunctionBody() for other cases of the behavior change
4110 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4111 // type without a prototype.
4112 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4113 !New->isImplicit() && !Old->isImplicit()) {
4114 const FunctionDecl *WithProto, *WithoutProto;
4115 if (New->hasWrittenPrototype()) {
4116 WithProto = New;
4117 WithoutProto = Old;
4118 } else {
4119 WithProto = Old;
4120 WithoutProto = New;
4121 }
4122
4123 if (WithProto->getNumParams() != 0) {
4124 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4125 // The one without the prototype will be changing behavior in C23, so
4126 // warn about that one so long as it's a user-visible declaration.
4127 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4128 if (WithoutProto == New)
4129 IsWithoutProtoADef = NewDeclIsDefn;
4130 else
4131 IsWithProtoADef = NewDeclIsDefn;
4132 Diag(WithoutProto->getLocation(),
4133 diag::warn_non_prototype_changes_behavior)
4134 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4135 << (WithoutProto == Old) << IsWithProtoADef;
4136
4137 // The reason the one without the prototype will be changing behavior
4138 // is because of the one with the prototype, so note that so long as
4139 // it's a user-visible declaration. There is one exception to this:
4140 // when the new declaration is a definition without a prototype, the
4141 // old declaration with a prototype is not the cause of the issue,
4142 // and that does not need to be noted because the one with a
4143 // prototype will not change behavior in C23.
4144 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4145 !IsWithoutProtoADef)
4146 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4147 }
4148 }
4149 }
4150
4151 if (Context.typesAreCompatible(OldQType, NewQType)) {
4152 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4153 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4154 const FunctionProtoType *OldProto = nullptr;
4155 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4156 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4157 // The old declaration provided a function prototype, but the
4158 // new declaration does not. Merge in the prototype.
4159 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4160 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4161 OldProto->getParamTypes(),
4162 OldProto->getExtProtoInfo());
4163 New->setType(NewQType);
4165
4166 // Synthesize parameters with the same types.
4168 for (const auto &ParamType : OldProto->param_types()) {
4170 Context, New, SourceLocation(), SourceLocation(), nullptr,
4171 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4172 Param->setScopeInfo(0, Params.size());
4173 Param->setImplicit();
4174 Params.push_back(Param);
4175 }
4176
4177 New->setParams(Params);
4178 }
4179
4180 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4181 }
4182 }
4183
4184 // Check if the function types are compatible when pointer size address
4185 // spaces are ignored.
4186 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4187 return false;
4188
4189 // GNU C permits a K&R definition to follow a prototype declaration
4190 // if the declared types of the parameters in the K&R definition
4191 // match the types in the prototype declaration, even when the
4192 // promoted types of the parameters from the K&R definition differ
4193 // from the types in the prototype. GCC then keeps the types from
4194 // the prototype.
4195 //
4196 // If a variadic prototype is followed by a non-variadic K&R definition,
4197 // the K&R definition becomes variadic. This is sort of an edge case, but
4198 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4199 // C99 6.9.1p8.
4200 if (!getLangOpts().CPlusPlus &&
4201 Old->hasPrototype() && !New->hasPrototype() &&
4202 New->getType()->getAs<FunctionProtoType>() &&
4203 Old->getNumParams() == New->getNumParams()) {
4206 const FunctionProtoType *OldProto
4207 = Old->getType()->getAs<FunctionProtoType>();
4208 const FunctionProtoType *NewProto
4209 = New->getType()->getAs<FunctionProtoType>();
4210
4211 // Determine whether this is the GNU C extension.
4212 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4213 NewProto->getReturnType());
4214 bool LooseCompatible = !MergedReturn.isNull();
4215 for (unsigned Idx = 0, End = Old->getNumParams();
4216 LooseCompatible && Idx != End; ++Idx) {
4217 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4218 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4219 if (Context.typesAreCompatible(OldParm->getType(),
4220 NewProto->getParamType(Idx))) {
4221 ArgTypes.push_back(NewParm->getType());
4222 } else if (Context.typesAreCompatible(OldParm->getType(),
4223 NewParm->getType(),
4224 /*CompareUnqualified=*/true)) {
4225 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4226 NewProto->getParamType(Idx) };
4227 Warnings.push_back(Warn);
4228 ArgTypes.push_back(NewParm->getType());
4229 } else
4230 LooseCompatible = false;
4231 }
4232
4233 if (LooseCompatible) {
4234 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4235 Diag(Warnings[Warn].NewParm->getLocation(),
4236 diag::ext_param_promoted_not_compatible_with_prototype)
4237 << Warnings[Warn].PromotedType
4238 << Warnings[Warn].OldParm->getType();
4239 if (Warnings[Warn].OldParm->getLocation().isValid())
4240 Diag(Warnings[Warn].OldParm->getLocation(),
4241 diag::note_previous_declaration);
4242 }
4243
4244 if (MergeTypeWithOld)
4245 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4246 OldProto->getExtProtoInfo()));
4247 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4248 }
4249
4250 // Fall through to diagnose conflicting types.
4251 }
4252
4253 // A function that has already been declared has been redeclared or
4254 // defined with a different type; show an appropriate diagnostic.
4255
4256 // If the previous declaration was an implicitly-generated builtin
4257 // declaration, then at the very least we should use a specialized note.
4258 unsigned BuiltinID;
4259 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4260 // If it's actually a library-defined builtin function like 'malloc'
4261 // or 'printf', just warn about the incompatible redeclaration.
4263 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4264 Diag(OldLocation, diag::note_previous_builtin_declaration)
4265 << Old << Old->getType();
4266 return false;
4267 }
4268
4269 PrevDiag = diag::note_previous_builtin_declaration;
4270 }
4271
4272 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4273 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4274 return true;
4275}
4276
4278 Scope *S, bool MergeTypeWithOld) {
4279 // Merge the attributes
4280 mergeDeclAttributes(New, Old);
4281
4282 // Merge "pure" flag.
4283 if (Old->isPureVirtual())
4284 New->setIsPureVirtual();
4285
4286 // Merge "used" flag.
4287 if (Old->getMostRecentDecl()->isUsed(false))
4288 New->setIsUsed();
4289
4290 // Merge attributes from the parameters. These can mismatch with K&R
4291 // declarations.
4292 if (New->getNumParams() == Old->getNumParams())
4293 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4294 ParmVarDecl *NewParam = New->getParamDecl(i);
4295 ParmVarDecl *OldParam = Old->getParamDecl(i);
4296 mergeParamDeclAttributes(NewParam, OldParam, *this);
4297 mergeParamDeclTypes(NewParam, OldParam, *this);
4298 }
4299
4300 if (getLangOpts().CPlusPlus)
4301 return MergeCXXFunctionDecl(New, Old, S);
4302
4303 // Merge the function types so the we get the composite types for the return
4304 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4305 // was visible.
4306 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4307 if (!Merged.isNull() && MergeTypeWithOld)
4308 New->setType(Merged);
4309
4310 return false;
4311}
4312
4314 ObjCMethodDecl *oldMethod) {
4315 // Merge the attributes, including deprecated/unavailable
4316 AvailabilityMergeKind MergeKind =
4317 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4320 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4321 : AMK_Override;
4322
4323 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4324
4325 // Merge attributes from the parameters.
4327 oe = oldMethod->param_end();
4329 ni = newMethod->param_begin(), ne = newMethod->param_end();
4330 ni != ne && oi != oe; ++ni, ++oi)
4331 mergeParamDeclAttributes(*ni, *oi, *this);
4332
4333 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4334}
4335
4337 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4338
4340 ? diag::err_redefinition_different_type
4341 : diag::err_redeclaration_different_type)
4342 << New->getDeclName() << New->getType() << Old->getType();
4343
4344 diag::kind PrevDiag;
4345 SourceLocation OldLocation;
4346 std::tie(PrevDiag, OldLocation)
4348 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4349 New->setInvalidDecl();
4350}
4351
4353 bool MergeTypeWithOld) {
4354 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4355 return;
4356
4357 QualType MergedT;
4358 if (getLangOpts().CPlusPlus) {
4359 if (New->getType()->isUndeducedType()) {
4360 // We don't know what the new type is until the initializer is attached.
4361 return;
4362 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4363 // These could still be something that needs exception specs checked.
4364 return MergeVarDeclExceptionSpecs(New, Old);
4365 }
4366 // C++ [basic.link]p10:
4367 // [...] the types specified by all declarations referring to a given
4368 // object or function shall be identical, except that declarations for an
4369 // array object can specify array types that differ by the presence or
4370 // absence of a major array bound (8.3.4).
4371 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4372 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4373 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4374
4375 // We are merging a variable declaration New into Old. If it has an array
4376 // bound, and that bound differs from Old's bound, we should diagnose the
4377 // mismatch.
4378 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4379 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4380 PrevVD = PrevVD->getPreviousDecl()) {
4381 QualType PrevVDTy = PrevVD->getType();
4382 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4383 continue;
4384
4385 if (!Context.hasSameType(New->getType(), PrevVDTy))
4386 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4387 }
4388 }
4389
4390 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4391 if (Context.hasSameType(OldArray->getElementType(),
4392 NewArray->getElementType()))
4393 MergedT = New->getType();
4394 }
4395 // FIXME: Check visibility. New is hidden but has a complete type. If New
4396 // has no array bound, it should not inherit one from Old, if Old is not
4397 // visible.
4398 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4399 if (Context.hasSameType(OldArray->getElementType(),
4400 NewArray->getElementType()))
4401 MergedT = Old->getType();
4402 }
4403 }
4404 else if (New->getType()->isObjCObjectPointerType() &&
4405 Old->getType()->isObjCObjectPointerType()) {
4406 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4407 Old->getType());
4408 }
4409 } else {
4410 // C 6.2.7p2:
4411 // All declarations that refer to the same object or function shall have
4412 // compatible type.
4413 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4414 }
4415 if (MergedT.isNull()) {
4416 // It's OK if we couldn't merge types if either type is dependent, for a
4417 // block-scope variable. In other cases (static data members of class
4418 // templates, variable templates, ...), we require the types to be
4419 // equivalent.
4420 // FIXME: The C++ standard doesn't say anything about this.
4421 if ((New->getType()->isDependentType() ||
4422 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4423 // If the old type was dependent, we can't merge with it, so the new type
4424 // becomes dependent for now. We'll reproduce the original type when we
4425 // instantiate the TypeSourceInfo for the variable.
4426 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4428 return;
4429 }
4430 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4431 }
4432
4433 // Don't actually update the type on the new declaration if the old
4434 // declaration was an extern declaration in a different scope.
4435 if (MergeTypeWithOld)
4436 New->setType(MergedT);
4437}
4438
4439static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4441 // C11 6.2.7p4:
4442 // For an identifier with internal or external linkage declared
4443 // in a scope in which a prior declaration of that identifier is
4444 // visible, if the prior declaration specifies internal or
4445 // external linkage, the type of the identifier at the later
4446 // declaration becomes the composite type.
4447 //
4448 // If the variable isn't visible, we do not merge with its type.
4449 if (Previous.isShadowed())
4450 return false;
4451
4452 if (S.getLangOpts().CPlusPlus) {
4453 // C++11 [dcl.array]p3:
4454 // If there is a preceding declaration of the entity in the same
4455 // scope in which the bound was specified, an omitted array bound
4456 // is taken to be the same as in that earlier declaration.
4457 return NewVD->isPreviousDeclInSameBlockScope() ||
4460 } else {
4461 // If the old declaration was function-local, don't merge with its
4462 // type unless we're in the same function.
4463 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4464 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4465 }
4466}
4467
4469 // If the new decl is already invalid, don't do any other checking.
4470 if (New->isInvalidDecl())
4471 return;
4472
4473 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4474 return;
4475
4476 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4477
4478 // Verify the old decl was also a variable or variable template.
4479 VarDecl *Old = nullptr;
4480 VarTemplateDecl *OldTemplate = nullptr;
4481 if (Previous.isSingleResult()) {
4482 if (NewTemplate) {
4483 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4484 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4485
4486 if (auto *Shadow =
4487 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4488 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4489 return New->setInvalidDecl();
4490 } else {
4491 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4492
4493 if (auto *Shadow =
4494 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4495 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4496 return New->setInvalidDecl();
4497 }
4498 }
4499 if (!Old) {
4500 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4501 << New->getDeclName();
4502 notePreviousDefinition(Previous.getRepresentativeDecl(),
4503 New->getLocation());
4504 return New->setInvalidDecl();
4505 }
4506
4507 // If the old declaration was found in an inline namespace and the new
4508 // declaration was qualified, update the DeclContext to match.
4510
4511 // Ensure the template parameters are compatible.
4512 if (NewTemplate &&
4514 OldTemplate->getTemplateParameters(),
4515 /*Complain=*/true, TPL_TemplateMatch))
4516 return New->setInvalidDecl();
4517
4518 // C++ [class.mem]p1:
4519 // A member shall not be declared twice in the member-specification [...]
4520 //
4521 // Here, we need only consider static data members.
4522 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4523 Diag(New->getLocation(), diag::err_duplicate_member)
4524 << New->getIdentifier();
4525 Diag(Old->getLocation(), diag::note_previous_declaration);
4526 New->setInvalidDecl();
4527 }
4528
4529 mergeDeclAttributes(New, Old);
4530 // Warn if an already-defined variable is made a weak_import in a subsequent
4531 // declaration
4532 if (New->hasAttr<WeakImportAttr>())
4533 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4534 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4535 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4536 Diag(D->getLocation(), diag::note_previous_definition);
4537 // Remove weak_import attribute on new declaration.
4538 New->dropAttr<WeakImportAttr>();
4539 break;
4540 }
4541 }
4542
4543 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4544 if (!Old->hasAttr<InternalLinkageAttr>()) {
4545 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4546 << ILA;
4547 Diag(Old->getLocation(), diag::note_previous_declaration);
4548 New->dropAttr<InternalLinkageAttr>();
4549 }
4550
4551 // Merge the types.
4552 VarDecl *MostRecent = Old->getMostRecentDecl();
4553 if (MostRecent != Old) {
4554 MergeVarDeclTypes(New, MostRecent,
4555 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4556 if (New->isInvalidDecl())
4557 return;
4558 }
4559
4560 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4561 if (New->isInvalidDecl())
4562 return;
4563
4564 diag::kind PrevDiag;
4565 SourceLocation OldLocation;
4566 std::tie(PrevDiag, OldLocation) =
4568
4569 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4570 if (New->getStorageClass() == SC_Static &&
4571 !New->isStaticDataMember() &&
4572 Old->hasExternalFormalLinkage()) {
4573 if (getLangOpts().MicrosoftExt) {
4574 Diag(New->getLocation(), diag::ext_static_non_static)
4575 << New->getDeclName();
4576 Diag(OldLocation, PrevDiag);
4577 } else {
4578 Diag(New->getLocation(), diag::err_static_non_static)
4579 << New->getDeclName();
4580 Diag(OldLocation, PrevDiag);
4581 return New->setInvalidDecl();
4582 }
4583 }
4584 // C99 6.2.2p4:
4585 // For an identifier declared with the storage-class specifier
4586 // extern in a scope in which a prior declaration of that
4587 // identifier is visible,23) if the prior declaration specifies
4588 // internal or external linkage, the linkage of the identifier at
4589 // the later declaration is the same as the linkage specified at
4590 // the prior declaration. If no prior declaration is visible, or
4591 // if the prior declaration specifies no linkage, then the
4592 // identifier has external linkage.
4593 if (New->hasExternalStorage() && Old->hasLinkage())
4594 /* Okay */;
4595 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4596 !New->isStaticDataMember() &&
4598 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4599 Diag(OldLocation, PrevDiag);
4600 return New->setInvalidDecl();
4601 }
4602
4603 // Check if extern is followed by non-extern and vice-versa.
4604 if (New->hasExternalStorage() &&
4605 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4606 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4607 Diag(OldLocation, PrevDiag);
4608 return New->setInvalidDecl();
4609 }
4610 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4611 !New->hasExternalStorage()) {
4612 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4613 Diag(OldLocation, PrevDiag);
4614 return New->setInvalidDecl();
4615 }
4616
4617 if (CheckRedeclarationInModule(New, Old))
4618 return;
4619
4620 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4621
4622 // FIXME: The test for external storage here seems wrong? We still
4623 // need to check for mismatches.
4624 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4625 // Don't complain about out-of-line definitions of static members.
4626 !(Old->getLexicalDeclContext()->isRecord() &&
4627 !New->getLexicalDeclContext()->isRecord())) {
4628 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4629 Diag(OldLocation, PrevDiag);
4630 return New->setInvalidDecl();
4631 }
4632
4633 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4634 if (VarDecl *Def = Old->getDefinition()) {
4635 // C++1z [dcl.fcn.spec]p4:
4636 // If the definition of a variable appears in a translation unit before
4637 // its first declaration as inline, the program is ill-formed.
4638 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4639 Diag(Def->getLocation(), diag::note_previous_definition);
4640 }
4641 }
4642
4643 // If this redeclaration makes the variable inline, we may need to add it to
4644 // UndefinedButUsed.
4645 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4647 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4648 SourceLocation()));
4649
4650 if (New->getTLSKind() != Old->getTLSKind()) {
4651 if (!Old->getTLSKind()) {
4652 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4653 Diag(OldLocation, PrevDiag);
4654 } else if (!New->getTLSKind()) {
4655 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4656 Diag(OldLocation, PrevDiag);
4657 } else {
4658 // Do not allow redeclaration to change the variable between requiring
4659 // static and dynamic initialization.
4660 // FIXME: GCC allows this, but uses the TLS keyword on the first
4661 // declaration to determine the kind. Do we need to be compatible here?
4662 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4663 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4664 Diag(OldLocation, PrevDiag);
4665 }
4666 }
4667
4668 // C++ doesn't have tentative definitions, so go right ahead and check here.
4669 if (getLangOpts().CPlusPlus) {
4670 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4671 Old->getCanonicalDecl()->isConstexpr()) {
4672 // This definition won't be a definition any more once it's been merged.
4673 Diag(New->getLocation(),
4674 diag::warn_deprecated_redundant_constexpr_static_def);
4676 VarDecl *Def = Old->getDefinition();
4677 if (Def && checkVarDeclRedefinition(Def, New))
4678 return;
4679 }
4680 }
4681
4682 if (haveIncompatibleLanguageLinkages(Old, New)) {
4683 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4684 Diag(OldLocation, PrevDiag);
4685 New->setInvalidDecl();
4686 return;
4687 }
4688
4689 // Merge "used" flag.
4690 if (Old->getMostRecentDecl()->isUsed(false))
4691 New->setIsUsed();
4692
4693 // Keep a chain of previous declarations.
4694 New->setPreviousDecl(Old);
4695 if (NewTemplate)
4696 NewTemplate->setPreviousDecl(OldTemplate);
4697
4698 // Inherit access appropriately.
4699 New->setAccess(Old->getAccess());
4700 if (NewTemplate)
4701 NewTemplate->setAccess(New->getAccess());
4702
4703 if (Old->isInline())
4704 New->setImplicitlyInline();
4705}
4706
4708 SourceManager &SrcMgr = getSourceManager();
4709 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4710 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4711 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4712 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4713 auto &HSI = PP.getHeaderSearchInfo();
4714 StringRef HdrFilename =
4715 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4716
4717 auto noteFromModuleOrInclude = [&](Module *Mod,
4718 SourceLocation IncLoc) -> bool {
4719 // Redefinition errors with modules are common with non modular mapped
4720 // headers, example: a non-modular header H in module A that also gets
4721 // included directly in a TU. Pointing twice to the same header/definition
4722 // is confusing, try to get better diagnostics when modules is on.
4723 if (IncLoc.isValid()) {
4724 if (Mod) {
4725 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4726 << HdrFilename.str() << Mod->getFullModuleName();
4727 if (!Mod->DefinitionLoc.isInvalid())
4728 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4729 << Mod->getFullModuleName();
4730 } else {
4731 Diag(IncLoc, diag::note_redefinition_include_same_file)
4732 << HdrFilename.str();
4733 }
4734 return true;
4735 }
4736
4737 return false;
4738 };
4739
4740 // Is it the same file and same offset? Provide more information on why
4741 // this leads to a redefinition error.
4742 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4743 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4744 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4745 bool EmittedDiag =
4746 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4747 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4748
4749 // If the header has no guards, emit a note suggesting one.
4750 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4751 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4752
4753 if (EmittedDiag)
4754 return;
4755 }
4756
4757 // Redefinition coming from different files or couldn't do better above.
4758 if (Old->getLocation().isValid())
4759 Diag(Old->getLocation(), diag::note_previous_definition);
4760}
4761
4763 if (!hasVisibleDefinition(Old) &&
4764 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4765 isa<VarTemplateSpecializationDecl>(New) ||
4768 // The previous definition is hidden, and multiple definitions are
4769 // permitted (in separate TUs). Demote this to a declaration.
4771
4772 // Make the canonical definition visible.
4773 if (auto *OldTD = Old->getDescribedVarTemplate())
4776 return false;
4777 } else {
4778 Diag(New->getLocation(), diag::err_redefinition) << New;
4780 New->setInvalidDecl();
4781 return true;
4782 }
4783}
4784
4786 DeclSpec &DS,
4787 const ParsedAttributesView &DeclAttrs,
4788 RecordDecl *&AnonRecord) {
4790 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4791}
4792
4793// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4794// disambiguate entities defined in different scopes.
4795// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4796// compatibility.
4797// We will pick our mangling number depending on which version of MSVC is being
4798// targeted.
4799static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4801 ? S->getMSCurManglingNumber()
4802 : S->getMSLastManglingNumber();
4803}
4804
4805void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4806 if (!Context.getLangOpts().CPlusPlus)
4807 return;
4808
4809 if (isa<CXXRecordDecl>(Tag->getParent())) {
4810 // If this tag is the direct child of a class, number it if
4811 // it is anonymous.
4812 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4813 return;
4815 Context.getManglingNumberContext(Tag->getParent());
4817 Tag, MCtx.getManglingNumber(
4818 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4819 return;
4820 }
4821
4822 // If this tag isn't a direct child of a class, number it if it is local.
4824 Decl *ManglingContextDecl;
4825 std::tie(MCtx, ManglingContextDecl) =
4826 getCurrentMangleNumberContext(Tag->getDeclContext());
4827 if (MCtx) {
4829 Tag, MCtx->getManglingNumber(
4830 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4831 }
4832}
4833
4834namespace {
4835struct NonCLikeKind {
4836 enum {
4837 None,
4838 BaseClass,
4839 DefaultMemberInit,
4840 Lambda,
4841 Friend,
4842 OtherMember,
4843 Invalid,
4844 } Kind = None;
4846
4847 explicit operator bool() { return Kind != None; }
4848};
4849}
4850
4851/// Determine whether a class is C-like, according to the rules of C++
4852/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4853static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4854 if (RD->isInvalidDecl())
4855 return {NonCLikeKind::Invalid, {}};
4856
4857 // C++ [dcl.typedef]p9: [P1766R1]
4858 // An unnamed class with a typedef name for linkage purposes shall not
4859 //
4860 // -- have any base classes
4861 if (RD->getNumBases())
4862 return {NonCLikeKind::BaseClass,
4864 RD->bases_end()[-1].getEndLoc())};
4865 bool Invalid = false;
4866 for (Decl *D : RD->decls()) {
4867 // Don't complain about things we already diagnosed.
4868 if (D->isInvalidDecl()) {
4869 Invalid = true;
4870 continue;
4871 }
4872
4873 // -- have any [...] default member initializers
4874 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4875 if (FD->hasInClassInitializer()) {
4876 auto *Init = FD->getInClassInitializer();
4877 return {NonCLikeKind::DefaultMemberInit,
4878 Init ? Init->getSourceRange() : D->getSourceRange()};
4879 }
4880 continue;
4881 }
4882
4883 // FIXME: We don't allow friend declarations. This violates the wording of
4884 // P1766, but not the intent.
4885 if (isa<FriendDecl>(D))
4886 return {NonCLikeKind::Friend, D->getSourceRange()};
4887
4888 // -- declare any members other than non-static data members, member
4889 // enumerations, or member classes,
4890 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4891 isa<EnumDecl>(D))
4892 continue;
4893 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4894 if (!MemberRD) {
4895 if (D->isImplicit())
4896 continue;
4897 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4898 }
4899
4900 // -- contain a lambda-expression,
4901 if (MemberRD->isLambda())
4902 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4903
4904 // and all member classes shall also satisfy these requirements
4905 // (recursively).
4906 if (MemberRD->isThisDeclarationADefinition()) {
4907 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4908 return Kind;
4909 }
4910 }
4911
4912 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4913}
4914
4916 TypedefNameDecl *NewTD) {
4917 if (TagFromDeclSpec->isInvalidDecl())
4918 return;
4919
4920 // Do nothing if the tag already has a name for linkage purposes.
4921 if (TagFromDeclSpec->hasNameForLinkage())
4922 return;
4923
4924 // A well-formed anonymous tag must always be a TagUseKind::Definition.
4925 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4926
4927 // The type must match the tag exactly; no qualifiers allowed.
4929 Context.getTagDeclType(TagFromDeclSpec))) {
4930 if (getLangOpts().CPlusPlus)
4931 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4932 return;
4933 }
4934
4935 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4936 // An unnamed class with a typedef name for linkage purposes shall [be
4937 // C-like].
4938 //
4939 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4940 // shouldn't happen, but there are constructs that the language rule doesn't
4941 // disallow for which we can't reasonably avoid computing linkage early.
4942 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4943 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4944 : NonCLikeKind();
4945 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4946 if (NonCLike || ChangesLinkage) {
4947 if (NonCLike.Kind == NonCLikeKind::Invalid)
4948 return;
4949
4950 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4951 if (ChangesLinkage) {
4952 // If the linkage changes, we can't accept this as an extension.
4953 if (NonCLike.Kind == NonCLikeKind::None)
4954 DiagID = diag::err_typedef_changes_linkage;
4955 else
4956 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4957 }
4958
4959 SourceLocation FixitLoc =
4960 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4961 llvm::SmallString<40> TextToInsert;
4962 TextToInsert += ' ';
4963 TextToInsert += NewTD->getIdentifier()->getName();
4964
4965 Diag(FixitLoc, DiagID)
4966 << isa<TypeAliasDecl>(NewTD)
4967 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4968 if (NonCLike.Kind != NonCLikeKind::None) {
4969 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4970 << NonCLike.Kind - 1 << NonCLike.Range;
4971 }
4972 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4973 << NewTD << isa<TypeAliasDecl>(NewTD);
4974
4975 if (ChangesLinkage)
4976 return;
4977 }
4978
4979 // Otherwise, set this as the anon-decl typedef for the tag.
4980 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4981
4982 // Now that we have a name for the tag, process API notes again.
4983 ProcessAPINotes(TagFromDeclSpec);
4984}
4985
4986static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
4988 switch (T) {
4990 return 0;
4992 return 1;
4994 return 2;
4996 return 3;
4997 case DeclSpec::TST_enum:
4998 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
4999 if (ED->isScopedUsingClassTag())
5000 return 5;
5001 if (ED->isScoped())
5002 return 6;
5003 }
5004 return 4;
5005 default:
5006 llvm_unreachable("unexpected type specifier");
5007 }
5008}
5009
5011 DeclSpec &DS,
5012 const ParsedAttributesView &DeclAttrs,
5013 MultiTemplateParamsArg TemplateParams,
5014 bool IsExplicitInstantiation,
5015 RecordDecl *&AnonRecord,
5016 SourceLocation EllipsisLoc) {
5017 Decl *TagD = nullptr;
5018 TagDecl *Tag = nullptr;
5024 TagD = DS.getRepAsDecl();
5025
5026 if (!TagD) // We probably had an error
5027 return nullptr;
5028
5029 // Note that the above type specs guarantee that the
5030 // type rep is a Decl, whereas in many of the others
5031 // it's a Type.
5032 if (isa<TagDecl>(TagD))
5033 Tag = cast<TagDecl>(TagD);
5034 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5035 Tag = CTD->getTemplatedDecl();
5036 }
5037
5038 if (Tag) {
5039 handleTagNumbering(Tag, S);
5040 Tag->setFreeStanding();
5041 if (Tag->isInvalidDecl())
5042 return Tag;
5043 }
5044
5045 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5046 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5047 // or incomplete types shall not be restrict-qualified."
5048 if (TypeQuals & DeclSpec::TQ_restrict)
5050 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5051 << DS.getSourceRange();
5052 }
5053
5054 if (DS.isInlineSpecified())
5055 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5056 << getLangOpts().CPlusPlus17;
5057
5058 if (DS.hasConstexprSpecifier()) {
5059 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5060 // and definitions of functions and variables.
5061 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5062 // the declaration of a function or function template
5063 if (Tag)
5064 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5066 << static_cast<int>(DS.getConstexprSpecifier());
5067 else if (getLangOpts().C23)
5068 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5069 else
5070 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5071 << static_cast<int>(DS.getConstexprSpecifier());
5072 // Don't emit warnings after this error.
5073 return TagD;
5074 }
5075
5077
5078 if (DS.isFriendSpecified()) {
5079 // If we're dealing with a decl but not a TagDecl, assume that
5080 // whatever routines created it handled the friendship aspect.
5081 if (TagD && !Tag)
5082 return nullptr;
5083 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5084 }
5085
5086 assert(EllipsisLoc.isInvalid() &&
5087 "Friend ellipsis but not friend-specified?");
5088
5089 // Track whether this decl-specifier declares anything.
5090 bool DeclaresAnything = true;
5091
5092 // Handle anonymous struct definitions.
5093 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5094 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5096 if (getLangOpts().CPlusPlus ||
5097 Record->getDeclContext()->isRecord()) {
5098 // If CurContext is a DeclContext that can contain statements,
5099 // RecursiveASTVisitor won't visit the decls that
5100 // BuildAnonymousStructOrUnion() will put into CurContext.
5101 // Also store them here so that they can be part of the
5102 // DeclStmt that gets created in this case.
5103 // FIXME: Also return the IndirectFieldDecls created by
5104 // BuildAnonymousStructOr union, for the same reason?
5106 AnonRecord = Record;
5107 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5109 }
5110
5111 DeclaresAnything = false;
5112 }
5113 }
5114
5115 // C11 6.7.2.1p2:
5116 // A struct-declaration that does not declare an anonymous structure or
5117 // anonymous union shall contain a struct-declarator-list.
5118 //
5119 // This rule also existed in C89 and C99; the grammar for struct-declaration
5120 // did not permit a struct-declaration without a struct-declarator-list.
5123 // Check for Microsoft C extension: anonymous struct/union member.
5124 // Handle 2 kinds of anonymous struct/union:
5125 // struct STRUCT;
5126 // union UNION;
5127 // and
5128 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5129 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5130 if ((Tag && Tag->getDeclName()) ||
5132 RecordDecl *Record = nullptr;
5133 if (Tag)
5134 Record = dyn_cast<RecordDecl>(Tag);
5135 else if (const RecordType *RT =
5137 Record = RT->getDecl();
5138 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5139 Record = UT->getDecl();
5140
5141 if (Record && getLangOpts().MicrosoftExt) {
5142 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5143 << Record->isUnion() << DS.getSourceRange();
5145 }
5146
5147 DeclaresAnything = false;
5148 }
5149 }
5150
5151 // Skip all the checks below if we have a type error.
5153 (TagD && TagD->isInvalidDecl()))
5154 return TagD;
5155
5156 if (getLangOpts().CPlusPlus &&
5158 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5159 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5160 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5161 DeclaresAnything = false;
5162
5163 if (!DS.isMissingDeclaratorOk()) {
5164 // Customize diagnostic for a typedef missing a name.
5166 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5167 << DS.getSourceRange();
5168 else
5169 DeclaresAnything = false;
5170 }
5171
5172 if (DS.isModulePrivateSpecified() &&
5173 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5174 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5175 << llvm::to_underlying(Tag->getTagKind())
5177
5179
5180 // C 6.7/2:
5181 // A declaration [...] shall declare at least a declarator [...], a tag,
5182 // or the members of an enumeration.
5183 // C++ [dcl.dcl]p3:
5184 // [If there are no declarators], and except for the declaration of an
5185 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5186 // names into the program, or shall redeclare a name introduced by a
5187 // previous declaration.
5188 if (!DeclaresAnything) {
5189 // In C, we allow this as a (popular) extension / bug. Don't bother
5190 // producing further diagnostics for redundant qualifiers after this.
5191 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5192 ? diag::err_no_declarators
5193 : diag::ext_no_declarators)
5194 << DS.getSourceRange();
5195 return TagD;
5196 }
5197
5198 // C++ [dcl.stc]p1:
5199 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5200 // init-declarator-list of the declaration shall not be empty.
5201 // C++ [dcl.fct.spec]p1:
5202 // If a cv-qualifier appears in a decl-specifier-seq, the
5203 // init-declarator-list of the declaration shall not be empty.
5204 //
5205 // Spurious qualifiers here appear to be valid in C.
5206 unsigned DiagID = diag::warn_standalone_specifier;
5207 if (getLangOpts().CPlusPlus)
5208 DiagID = diag::ext_standalone_specifier;
5209
5210 // Note that a linkage-specification sets a storage class, but
5211 // 'extern "C" struct foo;' is actually valid and not theoretically
5212 // useless.
5213 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5214 if (SCS == DeclSpec::SCS_mutable)
5215 // Since mutable is not a viable storage class specifier in C, there is
5216 // no reason to treat it as an extension. Instead, diagnose as an error.
5217 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5218 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5219 Diag(DS.getStorageClassSpecLoc(), DiagID)
5221 }
5222
5226 if (DS.getTypeQualifiers()) {
5228 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5230 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5231 // Restrict is covered above.
5233 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5235 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5236 }
5237
5238 // Warn about ignored type attributes, for example:
5239 // __attribute__((aligned)) struct A;
5240 // Attributes should be placed after tag to apply to type declaration.
5241 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5242 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5243 if (TypeSpecType == DeclSpec::TST_class ||
5244 TypeSpecType == DeclSpec::TST_struct ||
5245 TypeSpecType == DeclSpec::TST_interface ||
5246 TypeSpecType == DeclSpec::TST_union ||
5247 TypeSpecType == DeclSpec::TST_enum) {
5248
5249 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5250 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5251 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5252 DiagnosticId = diag::warn_attribute_ignored;
5253 else if (AL.isRegularKeywordAttribute())
5254 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5255 else
5256 DiagnosticId = diag::warn_declspec_attribute_ignored;
5257 Diag(AL.getLoc(), DiagnosticId)
5258 << AL << GetDiagnosticTypeSpecifierID(DS);
5259 };
5260
5261 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5262 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5263 }
5264 }
5265
5266 return TagD;
5267}
5268
5269/// We are trying to inject an anonymous member into the given scope;
5270/// check if there's an existing declaration that can't be overloaded.
5271///
5272/// \return true if this is a forbidden redeclaration
5273static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5274 DeclContext *Owner,
5275 DeclarationName Name,
5276 SourceLocation NameLoc, bool IsUnion,
5277 StorageClass SC) {
5278 LookupResult R(SemaRef, Name, NameLoc,
5281 RedeclarationKind::ForVisibleRedeclaration);
5282 if (!SemaRef.LookupName(R, S)) return false;
5283
5284 // Pick a representative declaration.
5286 assert(PrevDecl && "Expected a non-null Decl");
5287
5288 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5289 return false;
5290
5291 if (SC == StorageClass::SC_None &&
5292 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5293 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5294 if (!Owner->isRecord())
5295 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5296 return false;
5297 }
5298
5299 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5300 << IsUnion << Name;
5301 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5302
5303 return true;
5304}
5305
5307 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5309}
5310
5312 if (!getLangOpts().CPlusPlus)
5313 return;
5314
5315 // This function can be parsed before we have validated the
5316 // structure as an anonymous struct
5317 if (Record->isAnonymousStructOrUnion())
5318 return;
5319
5320 const NamedDecl *First = 0;
5321 for (const Decl *D : Record->decls()) {
5322 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5323 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5324 continue;
5325 if (!First)
5326 First = ND;
5327 else
5329 }
5330}
5331
5332/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5333/// anonymous struct or union AnonRecord into the owning context Owner
5334/// and scope S. This routine will be invoked just after we realize
5335/// that an unnamed union or struct is actually an anonymous union or
5336/// struct, e.g.,
5337///
5338/// @code
5339/// union {
5340/// int i;
5341/// float f;
5342/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5343/// // f into the surrounding scope.x
5344/// @endcode
5345///
5346/// This routine is recursive, injecting the names of nested anonymous
5347/// structs/unions into the owning context and scope as well.
5348static bool
5350 RecordDecl *AnonRecord, AccessSpecifier AS,
5351 StorageClass SC,
5352 SmallVectorImpl<NamedDecl *> &Chaining) {
5353 bool Invalid = false;
5354
5355 // Look every FieldDecl and IndirectFieldDecl with a name.
5356 for (auto *D : AnonRecord->decls()) {
5357 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5358 cast<NamedDecl>(D)->getDeclName()) {
5359 ValueDecl *VD = cast<ValueDecl>(D);
5360 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5361 VD->getLocation(), AnonRecord->isUnion(),
5362 SC)) {
5363 // C++ [class.union]p2:
5364 // The names of the members of an anonymous union shall be
5365 // distinct from the names of any other entity in the
5366 // scope in which the anonymous union is declared.
5367 Invalid = true;
5368 } else {
5369 // C++ [class.union]p2:
5370 // For the purpose of name lookup, after the anonymous union
5371 // definition, the members of the anonymous union are
5372 // considered to have been defined in the scope in which the
5373 // anonymous union is declared.
5374 unsigned OldChainingSize = Chaining.size();
5375 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5376 Chaining.append(IF->chain_begin(), IF->chain_end());
5377 else
5378 Chaining.push_back(VD);
5379
5380 assert(Chaining.size() >= 2);
5381 NamedDecl **NamedChain =
5382 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5383 for (unsigned i = 0; i < Chaining.size(); i++)
5384 NamedChain[i] = Chaining[i];
5385
5387 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5388 VD->getType(), {NamedChain, Chaining.size()});
5389
5390 for (const auto *Attr : VD->attrs())
5391 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5392
5393 IndirectField->setAccess(AS);
5394 IndirectField->setImplicit();
5395 SemaRef.PushOnScopeChains(IndirectField, S);
5396
5397 // That includes picking up the appropriate access specifier.
5398 if (AS != AS_none) IndirectField->setAccess(AS);
5399
5400 Chaining.resize(OldChainingSize);
5401 }
5402 }
5403 }
5404
5405 return Invalid;
5406}
5407
5408/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5409/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5410/// illegal input values are mapped to SC_None.
5411static StorageClass
5413 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5414 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5415 "Parser allowed 'typedef' as storage class VarDecl.");
5416 switch (StorageClassSpec) {
5419 if (DS.isExternInLinkageSpec())
5420 return SC_None;
5421 return SC_Extern;
5422 case DeclSpec::SCS_static: return SC_Static;
5423 case DeclSpec::SCS_auto: return SC_Auto;
5426 // Illegal SCSs map to None: error reporting is up to the caller.
5427 case DeclSpec::SCS_mutable: // Fall through.
5428 case DeclSpec::SCS_typedef: return SC_None;
5429 }
5430 llvm_unreachable("unknown storage class specifier");
5431}
5432
5434 assert(Record->hasInClassInitializer());
5435
5436 for (const auto *I : Record->decls()) {
5437 const auto *FD = dyn_cast<FieldDecl>(I);
5438 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5439 FD = IFD->getAnonField();
5440 if (FD && FD->hasInClassInitializer())
5441 return FD->getLocation();
5442 }
5443
5444 llvm_unreachable("couldn't find in-class initializer");
5445}
5446
5448 SourceLocation DefaultInitLoc) {
5449 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5450 return;
5451
5452 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5453 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5454}
5455
5457 CXXRecordDecl *AnonUnion) {
5458 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5459 return;
5460
5462}
5463
5465 AccessSpecifier AS,
5467 const PrintingPolicy &Policy) {
5468 DeclContext *Owner = Record->getDeclContext();
5469
5470 // Diagnose whether this anonymous struct/union is an extension.
5471 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5472 Diag(Record->getLocation(), diag::ext_anonymous_union);
5473 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5474 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5475 else if (!Record->isUnion() && !getLangOpts().C11)
5476 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5477
5478 // C and C++ require different kinds of checks for anonymous
5479 // structs/unions.
5480 bool Invalid = false;
5481 if (getLangOpts().CPlusPlus) {
5482 const char *PrevSpec = nullptr;
5483 if (Record->isUnion()) {
5484 // C++ [class.union]p6:
5485 // C++17 [class.union.anon]p2:
5486 // Anonymous unions declared in a named namespace or in the
5487 // global namespace shall be declared static.
5488 unsigned DiagID;
5489 DeclContext *OwnerScope = Owner->getRedeclContext();
5491 (OwnerScope->isTranslationUnit() ||
5492 (OwnerScope->isNamespace() &&
5493 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5494 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5495 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5496
5497 // Recover by adding 'static'.
5499 PrevSpec, DiagID, Policy);
5500 }
5501 // C++ [class.union]p6:
5502 // A storage class is not allowed in a declaration of an
5503 // anonymous union in a class scope.
5505 isa<RecordDecl>(Owner)) {
5507 diag::err_anonymous_union_with_storage_spec)
5509
5510 // Recover by removing the storage specifier.
5513 PrevSpec, DiagID, Context.getPrintingPolicy());
5514 }
5515 }
5516
5517 // Ignore const/volatile/restrict qualifiers.
5518 if (DS.getTypeQualifiers()) {
5520 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5521 << Record->isUnion() << "const"
5525 diag::ext_anonymous_struct_union_qualified)
5526 << Record->isUnion() << "volatile"
5530 diag::ext_anonymous_struct_union_qualified)
5531 << Record->isUnion() << "restrict"
5535 diag::ext_anonymous_struct_union_qualified)
5536 << Record->isUnion() << "_Atomic"
5540 diag::ext_anonymous_struct_union_qualified)
5541 << Record->isUnion() << "__unaligned"
5543
5545 }
5546
5547 // C++ [class.union]p2:
5548 // The member-specification of an anonymous union shall only
5549 // define non-static data members. [Note: nested types and
5550 // functions cannot be declared within an anonymous union. ]
5551 for (auto *Mem : Record->decls()) {
5552 // Ignore invalid declarations; we already diagnosed them.
5553 if (Mem->isInvalidDecl())
5554 continue;
5555
5556 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5557 // C++ [class.union]p3:
5558 // An anonymous union shall not have private or protected
5559 // members (clause 11).
5560 assert(FD->getAccess() != AS_none);
5561 if (FD->getAccess() != AS_public) {
5562 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5563 << Record->isUnion() << (FD->getAccess() == AS_protected);
5564 Invalid = true;
5565 }
5566
5567 // C++ [class.union]p1
5568 // An object of a class with a non-trivial constructor, a non-trivial
5569 // copy constructor, a non-trivial destructor, or a non-trivial copy
5570 // assignment operator cannot be a member of a union, nor can an
5571 // array of such objects.
5572 if (CheckNontrivialField(FD))
5573 Invalid = true;
5574 } else if (Mem->isImplicit()) {
5575 // Any implicit members are fine.
5576 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5577 // This is a type that showed up in an
5578 // elaborated-type-specifier inside the anonymous struct or
5579 // union, but which actually declares a type outside of the
5580 // anonymous struct or union. It's okay.
5581 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5582 if (!MemRecord->isAnonymousStructOrUnion() &&
5583 MemRecord->getDeclName()) {
5584 // Visual C++ allows type definition in anonymous struct or union.
5585 if (getLangOpts().MicrosoftExt)
5586 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5587 << Record->isUnion();
5588 else {
5589 // This is a nested type declaration.
5590 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5591 << Record->isUnion();
5592 Invalid = true;
5593 }
5594 } else {
5595 // This is an anonymous type definition within another anonymous type.
5596 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5597 // not part of standard C++.
5598 Diag(MemRecord->getLocation(),
5599 diag::ext_anonymous_record_with_anonymous_type)
5600 << Record->isUnion();
5601 }
5602 } else if (isa<AccessSpecDecl>(Mem)) {
5603 // Any access specifier is fine.
5604 } else if (isa<StaticAssertDecl>(Mem)) {
5605 // In C++1z, static_assert declarations are also fine.
5606 } else {
5607 // We have something that isn't a non-static data
5608 // member. Complain about it.
5609 unsigned DK = diag::err_anonymous_record_bad_member;
5610 if (isa<TypeDecl>(Mem))
5611 DK = diag::err_anonymous_record_with_type;
5612 else if (isa<FunctionDecl>(Mem))
5613 DK = diag::err_anonymous_record_with_function;
5614 else if (isa<VarDecl>(Mem))
5615 DK = diag::err_anonymous_record_with_static;
5616
5617 // Visual C++ allows type definition in anonymous struct or union.
5618 if (getLangOpts().MicrosoftExt &&
5619 DK == diag::err_anonymous_record_with_type)
5620 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5621 << Record->isUnion();
5622 else {
5623 Diag(Mem->getLocation(), DK) << Record->isUnion();
5624 Invalid = true;
5625 }
5626 }
5627 }
5628
5629 // C++11 [class.union]p8 (DR1460):
5630 // At most one variant member of a union may have a
5631 // brace-or-equal-initializer.
5632 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5633 Owner->isRecord())
5634 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5635 cast<CXXRecordDecl>(Record));
5636 }
5637
5638 if (!Record->isUnion() && !Owner->isRecord()) {
5639 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5640 << getLangOpts().CPlusPlus;
5641 Invalid = true;
5642 }
5643
5644 // C++ [dcl.dcl]p3:
5645 // [If there are no declarators], and except for the declaration of an
5646 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5647 // names into the program
5648 // C++ [class.mem]p2:
5649 // each such member-declaration shall either declare at least one member
5650 // name of the class or declare at least one unnamed bit-field
5651 //
5652 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5653 if (getLangOpts().CPlusPlus && Record->field_empty())
5654 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5655
5656 // Mock up a declarator.
5660 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5661
5662 // Create a declaration for this anonymous struct/union.
5663 NamedDecl *Anon = nullptr;
5664 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5665 Anon = FieldDecl::Create(
5666 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5667 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5668 /*BitWidth=*/nullptr, /*Mutable=*/false,
5669 /*InitStyle=*/ICIS_NoInit);
5670 Anon->setAccess(AS);
5671 ProcessDeclAttributes(S, Anon, Dc);
5672
5673 if (getLangOpts().CPlusPlus)
5674 FieldCollector->Add(cast<FieldDecl>(Anon));
5675 } else {
5676 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5677 if (SCSpec == DeclSpec::SCS_mutable) {
5678 // mutable can only appear on non-static class members, so it's always
5679 // an error here
5680 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5681 Invalid = true;
5682 SC = SC_None;
5683 }
5684
5685 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5686 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5687 Context.getTypeDeclType(Record), TInfo, SC);
5688 if (Invalid)
5689 Anon->setInvalidDecl();
5690
5691 ProcessDeclAttributes(S, Anon, Dc);
5692
5693 // Default-initialize the implicit variable. This initialization will be
5694 // trivial in almost all cases, except if a union member has an in-class
5695 // initializer:
5696 // union { int n = 0; };
5698 }
5699 Anon->setImplicit();
5700
5701 // Mark this as an anonymous struct/union type.
5702 Record->setAnonymousStructOrUnion(true);
5703
5704 // Add the anonymous struct/union object to the current
5705 // context. We'll be referencing this object when we refer to one of
5706 // its members.
5707 Owner->addDecl(Anon);
5708
5709 // Inject the members of the anonymous struct/union into the owning
5710 // context and into the identifier resolver chain for name lookup
5711 // purposes.
5713 Chain.push_back(Anon);
5714
5715 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5716 Chain))
5717 Invalid = true;
5718
5719 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5720 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5722 Decl *ManglingContextDecl;
5723 std::tie(MCtx, ManglingContextDecl) =
5724 getCurrentMangleNumberContext(NewVD->getDeclContext());
5725 if (MCtx) {
5727 NewVD, MCtx->getManglingNumber(
5728 NewVD, getMSManglingNumber(getLangOpts(), S)));
5730 }
5731 }
5732 }
5733
5734 if (Invalid)
5735 Anon->setInvalidDecl();
5736
5737 return Anon;
5738}
5739
5741 RecordDecl *Record) {
5742 assert(Record && "expected a record!");
5743
5744 // Mock up a declarator.
5747 assert(TInfo && "couldn't build declarator info for anonymous struct");
5748
5749 auto *ParentDecl = cast<RecordDecl>(CurContext);
5751
5752 // Create a declaration for this anonymous struct.
5753 NamedDecl *Anon =
5754 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5755 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5756 /*BitWidth=*/nullptr, /*Mutable=*/false,
5757 /*InitStyle=*/ICIS_NoInit);
5758 Anon->setImplicit();
5759
5760 // Add the anonymous struct object to the current context.
5761 CurContext->addDecl(Anon);
5762
5763 // Inject the members of the anonymous struct into the current
5764 // context and into the identifier resolver chain for name lookup
5765 // purposes.
5767 Chain.push_back(Anon);
5768
5769 RecordDecl *RecordDef = Record->getDefinition();
5770 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5771 diag::err_field_incomplete_or_sizeless) ||
5773 *this, S, CurContext, RecordDef, AS_none,
5775 Anon->setInvalidDecl();
5776 ParentDecl->setInvalidDecl();
5777 }
5778
5779 return Anon;
5780}
5781
5783 return GetNameFromUnqualifiedId(D.getName());
5784}
5785
5788 DeclarationNameInfo NameInfo;
5789 NameInfo.setLoc(Name.StartLocation);
5790
5791 switch (Name.getKind()) {
5792
5795 NameInfo.setName(Name.Identifier);
5796 return NameInfo;
5797
5799 // C++ [temp.deduct.guide]p3:
5800 // The simple-template-id shall name a class template specialization.
5801 // The template-name shall be the same identifier as the template-name
5802 // of the simple-template-id.
5803 // These together intend to imply that the template-name shall name a
5804 // class template.
5805 // FIXME: template<typename T> struct X {};
5806 // template<typename T> using Y = X<T>;
5807 // Y(int) -> Y<int>;
5808 // satisfies these rules but does not name a class template.
5809 TemplateName TN = Name.TemplateName.get().get();
5810 auto *Template = TN.getAsTemplateDecl();
5811 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5812 Diag(Name.StartLocation,
5813 diag::err_deduction_guide_name_not_class_template)
5815 if (Template)
5816 NoteTemplateLocation(*Template);
5817 return DeclarationNameInfo();
5818 }
5819
5820 NameInfo.setName(
5822 return NameInfo;
5823 }
5824
5827 Name.OperatorFunctionId.Operator));
5829 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5830 return NameInfo;
5831
5834 Name.Identifier));
5835 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5836 return NameInfo;
5837
5839 TypeSourceInfo *TInfo;
5840 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5841 if (Ty.isNull())
5842 return DeclarationNameInfo();
5845 NameInfo.setNamedTypeInfo(TInfo);
5846 return NameInfo;
5847 }
5848
5850 TypeSourceInfo *TInfo;
5851 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5852 if (Ty.isNull())
5853 return DeclarationNameInfo();
5856 NameInfo.setNamedTypeInfo(TInfo);
5857 return NameInfo;
5858 }
5859
5861 // In well-formed code, we can only have a constructor
5862 // template-id that refers to the current context, so go there
5863 // to find the actual type being constructed.
5864 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5865 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5866 return DeclarationNameInfo();
5867
5868 // Determine the type of the class being constructed.
5869 QualType CurClassType = Context.getTypeDeclType(CurClass);
5870
5871 // FIXME: Check two things: that the template-id names the same type as
5872 // CurClassType, and that the template-id does not occur when the name
5873 // was qualified.
5874
5876 Context.getCanonicalType(CurClassType)));
5877 // FIXME: should we retrieve TypeSourceInfo?
5878 NameInfo.setNamedTypeInfo(nullptr);
5879 return NameInfo;
5880 }
5881
5883 TypeSourceInfo *TInfo;
5884 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5885 if (Ty.isNull())
5886 return DeclarationNameInfo();
5889 NameInfo.setNamedTypeInfo(TInfo);
5890 return NameInfo;
5891 }
5892
5894 TemplateName TName = Name.TemplateId->Template.get();
5895 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5896 return Context.getNameForTemplate(TName, TNameLoc);
5897 }
5898
5899 } // switch (Name.getKind())
5900
5901 llvm_unreachable("Unknown name kind");
5902}
5903
5905 do {
5906 if (Ty->isPointerOrReferenceType())
5907 Ty = Ty->getPointeeType();
5908 else if (Ty->isArrayType())
5910 else
5911 return Ty.withoutLocalFastQualifiers();
5912 } while (true);
5913}
5914
5915/// hasSimilarParameters - Determine whether the C++ functions Declaration
5916/// and Definition have "nearly" matching parameters. This heuristic is
5917/// used to improve diagnostics in the case where an out-of-line function
5918/// definition doesn't match any declaration within the class or namespace.
5919/// Also sets Params to the list of indices to the parameters that differ
5920/// between the declaration and the definition. If hasSimilarParameters
5921/// returns true and Params is empty, then all of the parameters match.
5925 SmallVectorImpl<unsigned> &Params) {
5926 Params.clear();
5927 if (Declaration->param_size() != Definition->param_size())
5928 return false;
5929 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5930 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5931 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5932
5933 // The parameter types are identical
5934 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5935 continue;
5936
5937 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5938 QualType DefParamBaseTy = getCoreType(DefParamTy);
5939 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5940 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5941
5942 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5943 (DeclTyName && DeclTyName == DefTyName))
5944 Params.push_back(Idx);
5945 else // The two parameters aren't even close
5946 return false;
5947 }
5948
5949 return true;
5950}
5951
5952/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5953/// declarator needs to be rebuilt in the current instantiation.
5954/// Any bits of declarator which appear before the name are valid for
5955/// consideration here. That's specifically the type in the decl spec
5956/// and the base type in any member-pointer chunks.
5958 DeclarationName Name) {
5959 // The types we specifically need to rebuild are:
5960 // - typenames, typeofs, and decltypes
5961 // - types which will become injected class names
5962 // Of course, we also need to rebuild any type referencing such a
5963 // type. It's safest to just say "dependent", but we call out a
5964 // few cases here.
5965
5966 DeclSpec &DS = D.getMutableDeclSpec();
5967 switch (DS.getTypeSpecType()) {
5971#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
5972#include "clang/Basic/TransformTypeTraits.def"
5973 case DeclSpec::TST_atomic: {
5974 // Grab the type from the parser.
5975 TypeSourceInfo *TSI = nullptr;
5976 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5977 if (T.isNull() || !T->isInstantiationDependentType()) break;
5978
5979 // Make sure there's a type source info. This isn't really much
5980 // of a waste; most dependent types should have type source info
5981 // attached already.
5982 if (!TSI)
5984
5985 // Rebuild the type in the current instantiation.
5986 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5987 if (!TSI) return true;
5988
5989 // Store the new type back in the decl spec.
5990 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5991 DS.UpdateTypeRep(LocType);
5992 break;
5993 }
5994
5998 Expr *E = DS.getRepAsExpr();
6000 if (Result.isInvalid()) return true;
6001 DS.UpdateExprRep(Result.get());
6002 break;
6003 }
6004
6005 default:
6006 // Nothing to do for these decl specs.
6007 break;
6008 }
6009
6010 // It doesn't matter what order we do this in.
6011 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6012 DeclaratorChunk &Chunk = D.getTypeObject(I);
6013
6014 // The only type information in the declarator which can come
6015 // before the declaration name is the base type of a member
6016 // pointer.
6018 continue;
6019
6020 // Rebuild the scope specifier in-place.
6021 CXXScopeSpec &SS = Chunk.Mem.Scope();
6023 return true;
6024 }
6025
6026 return false;
6027}
6028
6029/// Returns true if the declaration is declared in a system header or from a
6030/// system macro.
6032 return SM.isInSystemHeader(D->getLocation()) ||
6033 SM.isInSystemMacro(D->getLocation());
6034}
6035
6037 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6038 // of system decl.
6039 if (D->getPreviousDecl() || D->isImplicit())
6040 return;
6041 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6044 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6045 << D << static_cast<int>(Status);
6046 }
6047}
6048
6050 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6051
6052 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6053 // declaration only if the `bind_to_declaration` extension is set.
6055 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6056 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6057 llvm::omp::TraitProperty::
6058 implementation_extension_bind_to_declaration))
6060 S, D, MultiTemplateParamsArg(), Bases);
6061
6063
6065 Dcl && Dcl->getDeclContext()->isFileContext())
6067
6068 if (!Bases.empty())
6070 Bases);
6071
6072 return Dcl;
6073}
6074
6076 DeclarationNameInfo NameInfo) {
6077 DeclarationName Name = NameInfo.getName();
6078
6079 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6080 while (Record && Record->isAnonymousStructOrUnion())
6081 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6082 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6083 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6084 return true;
6085 }
6086
6087 return false;
6088}
6089
6091 DeclarationName Name,
6093 TemplateIdAnnotation *TemplateId,
6094 bool IsMemberSpecialization) {
6095 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6096 "without nested-name-specifier");
6097 DeclContext *Cur = CurContext;
6098 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6099 Cur = Cur->getParent();
6100
6101 // If the user provided a superfluous scope specifier that refers back to the
6102 // class in which the entity is already declared, diagnose and ignore it.
6103 //
6104 // class X {
6105 // void X::f();
6106 // };
6107 //
6108 // Note, it was once ill-formed to give redundant qualification in all
6109 // contexts, but that rule was removed by DR482.
6110 if (Cur->Equals(DC)) {
6111 if (Cur->isRecord()) {
6112 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6113 : diag::err_member_extra_qualification)
6114 << Name << FixItHint::CreateRemoval(SS.getRange());
6115 SS.clear();
6116 } else {
6117 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6118 }
6119 return false;
6120 }
6121
6122 // Check whether the qualifying scope encloses the scope of the original
6123 // declaration. For a template-id, we perform the checks in
6124 // CheckTemplateSpecializationScope.
6125 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6126 if (Cur->isRecord())
6127 Diag(Loc, diag::err_member_qualification)
6128 << Name << SS.getRange();
6129 else if (isa<TranslationUnitDecl>(DC))
6130 Diag(Loc, diag::err_invalid_declarator_global_scope)
6131 << Name << SS.getRange();
6132 else if (isa<FunctionDecl>(Cur))
6133 Diag(Loc, diag::err_invalid_declarator_in_function)
6134 << Name << SS.getRange();
6135 else if (isa<BlockDecl>(Cur))
6136 Diag(Loc, diag::err_invalid_declarator_in_block)
6137 << Name << SS.getRange();
6138 else if (isa<ExportDecl>(Cur)) {
6139 if (!isa<NamespaceDecl>(DC))
6140 Diag(Loc, diag::err_export_non_namespace_scope_name)
6141 << Name << SS.getRange();
6142 else
6143 // The cases that DC is not NamespaceDecl should be handled in
6144 // CheckRedeclarationExported.
6145 return false;
6146 } else
6147 Diag(Loc, diag::err_invalid_declarator_scope)
6148 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6149
6150 return true;
6151 }
6152
6153 if (Cur->isRecord()) {
6154 // Cannot qualify members within a class.
6155 Diag(Loc, diag::err_member_qualification)
6156 << Name << SS.getRange();
6157 SS.clear();
6158
6159 // C++ constructors and destructors with incorrect scopes can break
6160 // our AST invariants by having the wrong underlying types. If
6161 // that's the case, then drop this declaration entirely.
6162 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6163 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6164 !Context.hasSameType(Name.getCXXNameType(),
6165 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6166 return true;
6167
6168 return false;
6169 }
6170
6171 // C++23 [temp.names]p5:
6172 // The keyword template shall not appear immediately after a declarative
6173 // nested-name-specifier.
6174 //
6175 // First check the template-id (if any), and then check each component of the
6176 // nested-name-specifier in reverse order.
6177 //
6178 // FIXME: nested-name-specifiers in friend declarations are declarative,
6179 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6180 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6181 Diag(Loc, diag::ext_template_after_declarative_nns)
6183
6185 do {
6186 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6188 Diag(Loc, diag::ext_template_after_declarative_nns)
6190 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6191
6192 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6193 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6194 // C++23 [expr.prim.id.qual]p3:
6195 // [...] If a nested-name-specifier N is declarative and has a
6196 // simple-template-id with a template argument list A that involves a
6197 // template parameter, let T be the template nominated by N without A.
6198 // T shall be a class template.
6199 if (TST->isDependentType() && TST->isTypeAlias())
6200 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6201 << SpecLoc.getLocalSourceRange();
6202 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6203 // C++23 [expr.prim.id.qual]p2:
6204 // [...] A declarative nested-name-specifier shall not have a
6205 // computed-type-specifier.
6206 //
6207 // CWG2858 changed this from 'decltype-specifier' to
6208 // 'computed-type-specifier'.
6209 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6210 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6211 }
6212 }
6213 } while ((SpecLoc = SpecLoc.getPrefix()));
6214
6215 return false;
6216}
6217
6219 MultiTemplateParamsArg TemplateParamLists) {
6220 // TODO: consider using NameInfo for diagnostic.
6222 DeclarationName Name = NameInfo.getName();
6223
6224 // All of these full declarators require an identifier. If it doesn't have
6225 // one, the ParsedFreeStandingDeclSpec action should be used.
6226 if (D.isDecompositionDeclarator()) {
6227 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6228 } else if (!Name) {
6229 if (!D.isInvalidType()) // Reject this if we think it is valid.
6230 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6231 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6232 return nullptr;
6234 return nullptr;
6235
6236 DeclContext *DC = CurContext;
6237 if (D.getCXXScopeSpec().isInvalid())
6238 D.setInvalidType();
6239 else if (D.getCXXScopeSpec().isSet()) {
6240 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6242 return nullptr;
6243
6244 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6245 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6246 if (!DC || isa<EnumDecl>(DC)) {
6247 // If we could not compute the declaration context, it's because the
6248 // declaration context is dependent but does not refer to a class,
6249 // class template, or class template partial specialization. Complain
6250 // and return early, to avoid the coming semantic disaster.
6251 Diag(D.getIdentifierLoc(),
6252 diag::err_template_qualified_declarator_no_match)
6253 << D.getCXXScopeSpec().getScopeRep()
6254 << D.getCXXScopeSpec().getRange();
6255 return nullptr;
6256 }
6257 bool IsDependentContext = DC->isDependentContext();
6258
6259 if (!IsDependentContext &&
6260 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6261 return nullptr;
6262
6263 // If a class is incomplete, do not parse entities inside it.
6264 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6265 Diag(D.getIdentifierLoc(),
6266 diag::err_member_def_undefined_record)
6267 << Name << DC << D.getCXXScopeSpec().getRange();
6268 return nullptr;
6269 }
6270 if (!D.getDeclSpec().isFriendSpecified()) {
6271 TemplateIdAnnotation *TemplateId =
6273 ? D.getName().TemplateId
6274 : nullptr;
6275 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,
6276 D.getIdentifierLoc(), TemplateId,
6277 /*IsMemberSpecialization=*/false)) {
6278 if (DC->isRecord())
6279 return nullptr;
6280
6281 D.setInvalidType();
6282 }
6283 }
6284
6285 // Check whether we need to rebuild the type of the given
6286 // declaration in the current instantiation.
6287 if (EnteringContext && IsDependentContext &&
6288 TemplateParamLists.size() != 0) {
6289 ContextRAII SavedContext(*this, DC);
6291 D.setInvalidType();
6292 }
6293 }
6294
6296 QualType R = TInfo->getType();
6297
6298 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6300 D.setInvalidType();
6301
6302 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6304
6305 // See if this is a redefinition of a variable in the same scope.
6306 if (!D.getCXXScopeSpec().isSet()) {
6307 bool IsLinkageLookup = false;
6308 bool CreateBuiltins = false;
6309
6310 // If the declaration we're planning to build will be a function
6311 // or object with linkage, then look for another declaration with
6312 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6313 //
6314 // If the declaration we're planning to build will be declared with
6315 // external linkage in the translation unit, create any builtin with
6316 // the same name.
6317 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6318 /* Do nothing*/;
6319 else if (CurContext->isFunctionOrMethod() &&
6320 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6321 R->isFunctionType())) {
6322 IsLinkageLookup = true;
6323 CreateBuiltins =
6326 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6327 CreateBuiltins = true;
6328
6329 if (IsLinkageLookup) {
6331 Previous.setRedeclarationKind(
6332 RedeclarationKind::ForExternalRedeclaration);
6333 }
6334
6335 LookupName(Previous, S, CreateBuiltins);
6336 } else { // Something like "int foo::x;"
6338
6339 // C++ [dcl.meaning]p1:
6340 // When the declarator-id is qualified, the declaration shall refer to a
6341 // previously declared member of the class or namespace to which the
6342 // qualifier refers (or, in the case of a namespace, of an element of the
6343 // inline namespace set of that namespace (7.3.1)) or to a specialization
6344 // thereof; [...]
6345 //
6346 // Note that we already checked the context above, and that we do not have
6347 // enough information to make sure that Previous contains the declaration
6348 // we want to match. For example, given:
6349 //
6350 // class X {
6351 // void f();
6352 // void f(float);
6353 // };
6354 //
6355 // void X::f(int) { } // ill-formed
6356 //
6357 // In this case, Previous will point to the overload set
6358 // containing the two f's declared in X, but neither of them
6359 // matches.
6360
6362 }
6363
6364 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6365 TPD && TPD->isTemplateParameter()) {
6366 // Older versions of clang allowed the names of function/variable templates
6367 // to shadow the names of their template parameters. For the compatibility
6368 // purposes we detect such cases and issue a default-to-error warning that
6369 // can be disabled with -Wno-strict-primary-template-shadow.
6370 if (!D.isInvalidType()) {
6371 bool AllowForCompatibility = false;
6372 if (Scope *DeclParent = S->getDeclParent();
6373 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6374 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6375 TemplateParamParent->isDeclScope(TPD);
6376 }
6377 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6378 AllowForCompatibility);
6379 }
6380
6381 // Just pretend that we didn't see the previous declaration.
6382 Previous.clear();
6383 }
6384
6385 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6386 // Forget that the previous declaration is the injected-class-name.
6387 Previous.clear();
6388
6389 // In C++, the previous declaration we find might be a tag type
6390 // (class or enum). In this case, the new declaration will hide the
6391 // tag type. Note that this applies to functions, function templates, and
6392 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6393 if (Previous.isSingleTagDecl() &&
6394 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6395 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6396 Previous.clear();
6397
6398 // Check that there are no default arguments other than in the parameters
6399 // of a function declaration (C++ only).
6400 if (getLangOpts().CPlusPlus)
6402
6403 /// Get the innermost enclosing declaration scope.
6404 S = S->getDeclParent();
6405
6406 NamedDecl *New;
6407
6408 bool AddToScope = true;
6409 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6410 if (TemplateParamLists.size()) {
6411 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6412 return nullptr;
6413 }
6414
6415 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6416 } else if (R->isFunctionType()) {
6417 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6418 TemplateParamLists,
6419 AddToScope);
6420 } else {
6421 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6422 AddToScope);
6423 }
6424
6425 if (!New)
6426 return nullptr;
6427
6428 // If this has an identifier and is not a function template specialization,
6429 // add it to the scope stack.
6430 if (New->getDeclName() && AddToScope)
6431 PushOnScopeChains(New, S);
6432
6433 if (OpenMP().isInOpenMPDeclareTargetContext())
6435
6436 return New;
6437}
6438
6439/// Helper method to turn variable array types into constant array
6440/// types in certain situations which would otherwise be errors (for
6441/// GCC compatibility).
6443 ASTContext &Context,
6444 bool &SizeIsNegative,
6445 llvm::APSInt &Oversized) {
6446 // This method tries to turn a variable array into a constant
6447 // array even when the size isn't an ICE. This is necessary
6448 // for compatibility with code that depends on gcc's buggy
6449 // constant expression folding, like struct {char x[(int)(char*)2];}
6450 SizeIsNegative = false;
6451 Oversized = 0;
6452
6453 if (T->isDependentType())
6454 return QualType();
6455
6457 const Type *Ty = Qs.strip(T);
6458
6459 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6460 QualType Pointee = PTy->getPointeeType();
6461 QualType FixedType =
6462 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6463 Oversized);
6464 if (FixedType.isNull()) return FixedType;
6465 FixedType = Context.getPointerType(FixedType);
6466 return Qs.apply(Context, FixedType);
6467 }
6468 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6469 QualType Inner = PTy->getInnerType();
6470 QualType FixedType =
6471 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6472 Oversized);
6473 if (FixedType.isNull()) return FixedType;
6474 FixedType = Context.getParenType(FixedType);
6475 return Qs.apply(Context, FixedType);
6476 }
6477
6478 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6479 if (!VLATy)
6480 return QualType();
6481
6482 QualType ElemTy = VLATy->getElementType();
6483 if (ElemTy->isVariablyModifiedType()) {
6484 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6485 SizeIsNegative, Oversized);
6486 if (ElemTy.isNull())
6487 return QualType();
6488 }
6489
6491 if (!VLATy->getSizeExpr() ||
6492 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6493 return QualType();
6494
6495 llvm::APSInt Res = Result.Val.getInt();
6496
6497 // Check whether the array size is negative.
6498 if (Res.isSigned() && Res.isNegative()) {
6499 SizeIsNegative = true;
6500 return QualType();
6501 }
6502
6503 // Check whether the array is too large to be addressed.
6504 unsigned ActiveSizeBits =
6505 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6506 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6507 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6508 : Res.getActiveBits();
6509 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6510 Oversized = Res;
6511 return QualType();
6512 }
6513
6514 QualType FoldedArrayType = Context.getConstantArrayType(
6515 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6516 return Qs.apply(Context, FoldedArrayType);
6517}
6518
6519static void
6521 SrcTL = SrcTL.getUnqualifiedLoc();
6522 DstTL = DstTL.getUnqualifiedLoc();
6523 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6524 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6525 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6526 DstPTL.getPointeeLoc());
6527 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6528 return;
6529 }
6530 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6531 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6532 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6533 DstPTL.getInnerLoc());
6534 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6535 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6536 return;
6537 }
6538 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6539 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6540 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6541 TypeLoc DstElemTL = DstATL.getElementLoc();
6542 if (VariableArrayTypeLoc SrcElemATL =
6543 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6544 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6545 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6546 } else {
6547 DstElemTL.initializeFullCopy(SrcElemTL);
6548 }
6549 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6550 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6551 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6552}
6553
6554/// Helper method to turn variable array types into constant array
6555/// types in certain situations which would otherwise be errors (for
6556/// GCC compatibility).
6557static TypeSourceInfo*
6559 ASTContext &Context,
6560 bool &SizeIsNegative,
6561 llvm::APSInt &Oversized) {
6562 QualType FixedTy
6563 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6564 SizeIsNegative, Oversized);
6565 if (FixedTy.isNull())
6566 return nullptr;
6567 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6569 FixedTInfo->getTypeLoc());
6570 return FixedTInfo;
6571}
6572
6575 unsigned FailedFoldDiagID) {
6576 bool SizeIsNegative;
6577 llvm::APSInt Oversized;
6579 TInfo, Context, SizeIsNegative, Oversized);
6580 if (FixedTInfo) {
6581 Diag(Loc, diag::ext_vla_folded_to_constant);
6582 TInfo = FixedTInfo;
6583 T = FixedTInfo->getType();
6584 return true;
6585 }
6586
6587 if (SizeIsNegative)
6588 Diag(Loc, diag::err_typecheck_negative_array_size);
6589 else if (Oversized.getBoolValue())
6590 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6591 else if (FailedFoldDiagID)
6592 Diag(Loc, FailedFoldDiagID);
6593 return false;
6594}
6595
6596void
6598 if (!getLangOpts().CPlusPlus &&
6600 // Don't need to track declarations in the TU in C.
6601 return;
6602
6603 // Note that we have a locally-scoped external with this name.
6605}
6606
6608 // FIXME: We can have multiple results via __attribute__((overloadable)).
6610 return Result.empty() ? nullptr : *Result.begin();
6611}
6612
6614 // FIXME: We should probably indicate the identifier in question to avoid
6615 // confusion for constructs like "virtual int a(), b;"
6616 if (DS.isVirtualSpecified())
6618 diag::err_virtual_non_function);
6619
6620 if (DS.hasExplicitSpecifier())
6622 diag::err_explicit_non_function);
6623
6624 if (DS.isNoreturnSpecified())
6626 diag::err_noreturn_non_function);
6627}
6628
6629NamedDecl*
6632 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6633 if (D.getCXXScopeSpec().isSet()) {
6634 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6635 << D.getCXXScopeSpec().getRange();
6636 D.setInvalidType();
6637 // Pretend we didn't see the scope specifier.
6638 DC = CurContext;
6639 Previous.clear();
6640 }
6641
6642 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6643
6644 if (D.getDeclSpec().isInlineSpecified())
6645 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6646 << getLangOpts().CPlusPlus17;
6647 if (D.getDeclSpec().hasConstexprSpecifier())
6648 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6649 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6650
6651 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6653 Diag(D.getName().StartLocation,
6654 diag::err_deduction_guide_invalid_specifier)
6655 << "typedef";
6656 else
6657 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6658 << D.getName().getSourceRange();
6659 return nullptr;
6660 }
6661
6662 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6663 if (!NewTD) return nullptr;
6664
6665 // Handle attributes prior to checking for duplicates in MergeVarDecl
6666 ProcessDeclAttributes(S, NewTD, D);
6667
6669
6670 bool Redeclaration = D.isRedeclaration();
6671 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6672 D.setRedeclaration(Redeclaration);
6673 return ND;
6674}
6675
6676void
6678 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6679 // then it shall have block scope.
6680 // Note that variably modified types must be fixed before merging the decl so
6681 // that redeclarations will match.
6682 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6683 QualType T = TInfo->getType();
6684 if (T->isVariablyModifiedType()) {
6686
6687 if (S->getFnParent() == nullptr) {
6688 bool SizeIsNegative;
6689 llvm::APSInt Oversized;
6690 TypeSourceInfo *FixedTInfo =
6692 SizeIsNegative,
6693 Oversized);
6694 if (FixedTInfo) {
6695 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6696 NewTD->setTypeSourceInfo(FixedTInfo);
6697 } else {
6698 if (SizeIsNegative)
6699 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6700 else if (T->isVariableArrayType())
6701 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6702 else if (Oversized.getBoolValue())
6703 Diag(NewTD->getLocation(), diag::err_array_too_large)
6704 << toString(Oversized, 10);
6705 else
6706 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6707 NewTD->setInvalidDecl();
6708 }
6709 }
6710 }
6711}
6712
6713NamedDecl*
6715 LookupResult &Previous, bool &Redeclaration) {
6716
6717 // Find the shadowed declaration before filtering for scope.
6718 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6719
6720 // Merge the decl with the existing one if appropriate. If the decl is
6721 // in an outer scope, it isn't the same thing.
6722 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6723 /*AllowInlineNamespace*/false);
6725 if (!Previous.empty()) {
6726 Redeclaration = true;
6727 MergeTypedefNameDecl(S, NewTD, Previous);
6728 } else {
6730 }
6731
6732 if (ShadowedDecl && !Redeclaration)
6733 CheckShadow(NewTD, ShadowedDecl, Previous);
6734
6735 // If this is the C FILE type, notify the AST context.
6736 if (IdentifierInfo *II = NewTD->getIdentifier())
6737 if (!NewTD->isInvalidDecl() &&
6739 switch (II->getNotableIdentifierID()) {
6740 case tok::NotableIdentifierKind::FILE:
6741 Context.setFILEDecl(NewTD);
6742 break;
6743 case tok::NotableIdentifierKind::jmp_buf:
6744 Context.setjmp_bufDecl(NewTD);
6745 break;
6746 case tok::NotableIdentifierKind::sigjmp_buf:
6748 break;
6749 case tok::NotableIdentifierKind::ucontext_t:
6751 break;
6752 case tok::NotableIdentifierKind::float_t:
6753 case tok::NotableIdentifierKind::double_t:
6754 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6755 break;
6756 default:
6757 break;
6758 }
6759 }
6760
6761 return NewTD;
6762}
6763
6764/// Determines whether the given declaration is an out-of-scope
6765/// previous declaration.
6766///
6767/// This routine should be invoked when name lookup has found a
6768/// previous declaration (PrevDecl) that is not in the scope where a
6769/// new declaration by the same name is being introduced. If the new
6770/// declaration occurs in a local scope, previous declarations with
6771/// linkage may still be considered previous declarations (C99
6772/// 6.2.2p4-5, C++ [basic.link]p6).
6773///
6774/// \param PrevDecl the previous declaration found by name
6775/// lookup
6776///
6777/// \param DC the context in which the new declaration is being
6778/// declared.
6779///
6780/// \returns true if PrevDecl is an out-of-scope previous declaration
6781/// for a new delcaration with the same name.
6782static bool
6784 ASTContext &Context) {
6785 if (!PrevDecl)
6786 return false;
6787
6788 if (!PrevDecl->hasLinkage())
6789 return false;
6790
6791 if (Context.getLangOpts().CPlusPlus) {
6792 // C++ [basic.link]p6:
6793 // If there is a visible declaration of an entity with linkage
6794 // having the same name and type, ignoring entities declared
6795 // outside the innermost enclosing namespace scope, the block
6796 // scope declaration declares that same entity and receives the
6797 // linkage of the previous declaration.
6798 DeclContext *OuterContext = DC->getRedeclContext();
6799 if (!OuterContext->isFunctionOrMethod())
6800 // This rule only applies to block-scope declarations.
6801 return false;
6802
6803 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6804 if (PrevOuterContext->isRecord())
6805 // We found a member function: ignore it.
6806 return false;
6807
6808 // Find the innermost enclosing namespace for the new and
6809 // previous declarations.
6810 OuterContext = OuterContext->getEnclosingNamespaceContext();
6811 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6812
6813 // The previous declaration is in a different namespace, so it
6814 // isn't the same function.
6815 if (!OuterContext->Equals(PrevOuterContext))
6816 return false;
6817 }
6818
6819 return true;
6820}
6821
6823 CXXScopeSpec &SS = D.getCXXScopeSpec();
6824 if (!SS.isSet()) return;
6826}
6827
6829 if (Decl->getType().hasAddressSpace())
6830 return;
6831 if (Decl->getType()->isDependentType())
6832 return;
6833 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6834 QualType Type = Var->getType();
6835 if (Type->isSamplerT() || Type->isVoidType())
6836 return;
6838 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6839 // __opencl_c_program_scope_global_variables feature, the address space
6840 // for a variable at program scope or a static or extern variable inside
6841 // a function are inferred to be __global.
6842 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6843 Var->hasGlobalStorage())
6844 ImplAS = LangAS::opencl_global;
6845 // If the original type from a decayed type is an array type and that array
6846 // type has no address space yet, deduce it now.
6847 if (auto DT = dyn_cast<DecayedType>(Type)) {
6848 auto OrigTy = DT->getOriginalType();
6849 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6850 // Add the address space to the original array type and then propagate
6851 // that to the element type through `getAsArrayType`.
6852 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6853 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6854 // Re-generate the decayed type.
6855 Type = Context.getDecayedType(OrigTy);
6856 }
6857 }
6859 // Apply any qualifiers (including address space) from the array type to
6860 // the element type. This implements C99 6.7.3p8: "If the specification of
6861 // an array type includes any type qualifiers, the element type is so
6862 // qualified, not the array type."
6863 if (Type->isArrayType())
6865 Decl->setType(Type);
6866 }
6867}
6868
6869static void checkWeakAttr(Sema &S, NamedDecl &ND) {
6870 // 'weak' only applies to declarations with external linkage.
6871 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6872 if (!ND.isExternallyVisible()) {
6873 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6874 ND.dropAttr<WeakAttr>();
6875 }
6876 }
6877}
6878
6879static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
6880 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6881 if (ND.isExternallyVisible()) {
6882 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6883 ND.dropAttrs<WeakRefAttr, AliasAttr>();
6884 }
6885 }
6886}
6887
6888static void checkAliasAttr(Sema &S, NamedDecl &ND) {
6889 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6890 if (VD->hasInit()) {
6891 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6892 assert(VD->isThisDeclarationADefinition() &&
6893 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6894 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6895 VD->dropAttr<AliasAttr>();
6896 }
6897 }
6898 }
6899}
6900
6901static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
6902 // 'selectany' only applies to externally visible variable declarations.
6903 // It does not apply to functions.
6904 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6905 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6906 S.Diag(Attr->getLocation(),
6907 diag::err_attribute_selectany_non_extern_data);
6908 ND.dropAttr<SelectAnyAttr>();
6909 }
6910 }
6911}
6912
6914 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
6915 if (!ND.isExternallyVisible())
6916 S.Diag(Attr->getLocation(),
6917 diag::warn_attribute_hybrid_patchable_non_extern);
6918 }
6919}
6920
6922 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6923 auto *VD = dyn_cast<VarDecl>(&ND);
6924 bool IsAnonymousNS = false;
6925 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6926 if (VD) {
6927 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6928 while (NS && !IsAnonymousNS) {
6929 IsAnonymousNS = NS->isAnonymousNamespace();
6930 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6931 }
6932 }
6933 // dll attributes require external linkage. Static locals may have external
6934 // linkage but still cannot be explicitly imported or exported.
6935 // In Microsoft mode, a variable defined in anonymous namespace must have
6936 // external linkage in order to be exported.
6937 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6938 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6939 (!AnonNSInMicrosoftMode &&
6940 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6941 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6942 << &ND << Attr;
6943 ND.setInvalidDecl();
6944 }
6945 }
6946}
6947
6949 // Check the attributes on the function type and function params, if any.
6950 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6951 // Don't declare this variable in the second operand of the for-statement;
6952 // GCC miscompiles that by ending its lifetime before evaluating the
6953 // third operand. See gcc.gnu.org/PR86769.
6955 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6956 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6957 TL = ATL.getModifiedLoc()) {
6958 // The [[lifetimebound]] attribute can be applied to the implicit object
6959 // parameter of a non-static member function (other than a ctor or dtor)
6960 // by applying it to the function type.
6961 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6962 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6963 int NoImplicitObjectError = -1;
6964 if (!MD)
6965 NoImplicitObjectError = 0;
6966 else if (MD->isStatic())
6967 NoImplicitObjectError = 1;
6968 else if (MD->isExplicitObjectMemberFunction())
6969 NoImplicitObjectError = 2;
6970 if (NoImplicitObjectError != -1) {
6971 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6972 << NoImplicitObjectError << A->getRange();
6973 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6974 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6975 << isa<CXXDestructorDecl>(MD) << A->getRange();
6976 } else if (MD->getReturnType()->isVoidType()) {
6977 S.Diag(
6978 MD->getLocation(),
6979 diag::
6980 err_lifetimebound_implicit_object_parameter_void_return_type);
6981 }
6982 }
6983 }
6984
6985 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
6986 const ParmVarDecl *P = FD->getParamDecl(I);
6987
6988 // The [[lifetimebound]] attribute can be applied to a function parameter
6989 // only if the function returns a value.
6990 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
6991 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
6992 S.Diag(A->getLocation(),
6993 diag::err_lifetimebound_parameter_void_return_type);
6994 }
6995 }
6996 }
6997 }
6998}
6999
7001 // Ensure that an auto decl is deduced otherwise the checks below might cache
7002 // the wrong linkage.
7003 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7004
7005 checkWeakAttr(S, ND);
7006 checkWeakRefAttr(S, ND);
7007 checkAliasAttr(S, ND);
7008 checkSelectAnyAttr(S, ND);
7010 checkInheritableAttr(S, ND);
7012}
7013
7015 NamedDecl *NewDecl,
7016 bool IsSpecialization,
7017 bool IsDefinition) {
7018 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7019 return;
7020
7021 bool IsTemplate = false;
7022 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7023 OldDecl = OldTD->getTemplatedDecl();
7024 IsTemplate = true;
7025 if (!IsSpecialization)
7026 IsDefinition = false;
7027 }
7028 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7029 NewDecl = NewTD->getTemplatedDecl();
7030 IsTemplate = true;
7031 }
7032
7033 if (!OldDecl || !NewDecl)
7034 return;
7035
7036 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7037 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7038 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7039 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7040
7041 // dllimport and dllexport are inheritable attributes so we have to exclude
7042 // inherited attribute instances.
7043 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7044 (NewExportAttr && !NewExportAttr->isInherited());
7045
7046 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7047 // the only exception being explicit specializations.
7048 // Implicitly generated declarations are also excluded for now because there
7049 // is no other way to switch these to use dllimport or dllexport.
7050 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7051
7052 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7053 // Allow with a warning for free functions and global variables.
7054 bool JustWarn = false;
7055 if (!OldDecl->isCXXClassMember()) {
7056 auto *VD = dyn_cast<VarDecl>(OldDecl);
7057 if (VD && !VD->getDescribedVarTemplate())
7058 JustWarn = true;
7059 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7060 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7061 JustWarn = true;
7062 }
7063
7064 // We cannot change a declaration that's been used because IR has already
7065 // been emitted. Dllimported functions will still work though (modulo
7066 // address equality) as they can use the thunk.
7067 if (OldDecl->isUsed())
7068 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7069 JustWarn = false;
7070
7071 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7072 : diag::err_attribute_dll_redeclaration;
7073 S.Diag(NewDecl->getLocation(), DiagID)
7074 << NewDecl
7075 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7076 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7077 if (!JustWarn) {
7078 NewDecl->setInvalidDecl();
7079 return;
7080 }
7081 }
7082
7083 // A redeclaration is not allowed to drop a dllimport attribute, the only
7084 // exceptions being inline function definitions (except for function
7085 // templates), local extern declarations, qualified friend declarations or
7086 // special MSVC extension: in the last case, the declaration is treated as if
7087 // it were marked dllexport.
7088 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7089 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7090 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7091 // Ignore static data because out-of-line definitions are diagnosed
7092 // separately.
7093 IsStaticDataMember = VD->isStaticDataMember();
7094 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7096 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7097 IsInline = FD->isInlined();
7098 IsQualifiedFriend = FD->getQualifier() &&
7099 FD->getFriendObjectKind() == Decl::FOK_Declared;
7100 }
7101
7102 if (OldImportAttr && !HasNewAttr &&
7103 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7104 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7105 if (IsMicrosoftABI && IsDefinition) {
7106 if (IsSpecialization) {
7107 S.Diag(
7108 NewDecl->getLocation(),
7109 diag::err_attribute_dllimport_function_specialization_definition);
7110 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7111 NewDecl->dropAttr<DLLImportAttr>();
7112 } else {
7113 S.Diag(NewDecl->getLocation(),
7114 diag::warn_redeclaration_without_import_attribute)
7115 << NewDecl;
7116 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7117 NewDecl->dropAttr<DLLImportAttr>();
7118 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7119 S.Context, NewImportAttr->getRange()));
7120 }
7121 } else if (IsMicrosoftABI && IsSpecialization) {
7122 assert(!IsDefinition);
7123 // MSVC allows this. Keep the inherited attribute.
7124 } else {
7125 S.Diag(NewDecl->getLocation(),
7126 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7127 << NewDecl << OldImportAttr;
7128 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7129 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7130 OldDecl->dropAttr<DLLImportAttr>();
7131 NewDecl->dropAttr<DLLImportAttr>();
7132 }
7133 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7134 // In MinGW, seeing a function declared inline drops the dllimport
7135 // attribute.
7136 OldDecl->dropAttr<DLLImportAttr>();
7137 NewDecl->dropAttr<DLLImportAttr>();
7138 S.Diag(NewDecl->getLocation(),
7139 diag::warn_dllimport_dropped_from_inline_function)
7140 << NewDecl << OldImportAttr;
7141 }
7142
7143 // A specialization of a class template member function is processed here
7144 // since it's a redeclaration. If the parent class is dllexport, the
7145 // specialization inherits that attribute. This doesn't happen automatically
7146 // since the parent class isn't instantiated until later.
7147 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7148 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7149 !NewImportAttr && !NewExportAttr) {
7150 if (const DLLExportAttr *ParentExportAttr =
7151 MD->getParent()->getAttr<DLLExportAttr>()) {
7152 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7153 NewAttr->setInherited(true);
7154 NewDecl->addAttr(NewAttr);
7155 }
7156 }
7157 }
7158}
7159
7160/// Given that we are within the definition of the given function,
7161/// will that definition behave like C99's 'inline', where the
7162/// definition is discarded except for optimization purposes?
7164 // Try to avoid calling GetGVALinkageForFunction.
7165
7166 // All cases of this require the 'inline' keyword.
7167 if (!FD->isInlined()) return false;
7168
7169 // This is only possible in C++ with the gnu_inline attribute.
7170 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7171 return false;
7172
7173 // Okay, go ahead and call the relatively-more-expensive function.
7175}
7176
7177/// Determine whether a variable is extern "C" prior to attaching
7178/// an initializer. We can't just call isExternC() here, because that
7179/// will also compute and cache whether the declaration is externally
7180/// visible, which might change when we attach the initializer.
7181///
7182/// This can only be used if the declaration is known to not be a
7183/// redeclaration of an internal linkage declaration.
7184///
7185/// For instance:
7186///
7187/// auto x = []{};
7188///
7189/// Attaching the initializer here makes this declaration not externally
7190/// visible, because its type has internal linkage.
7191///
7192/// FIXME: This is a hack.
7193template<typename T>
7194static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7195 if (S.getLangOpts().CPlusPlus) {
7196 // In C++, the overloadable attribute negates the effects of extern "C".
7197 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7198 return false;
7199
7200 // So do CUDA's host/device attributes.
7201 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7202 D->template hasAttr<CUDAHostAttr>()))
7203 return false;
7204 }
7205 return D->isExternC();
7206}
7207
7208static bool shouldConsiderLinkage(const VarDecl *VD) {
7209 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7210 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7211 isa<OMPDeclareMapperDecl>(DC))
7212 return VD->hasExternalStorage();
7213 if (DC->isFileContext())
7214 return true;
7215 if (DC->isRecord())
7216 return false;
7217 if (DC->getDeclKind() == Decl::HLSLBuffer)
7218 return false;
7219
7220 if (isa<RequiresExprBodyDecl>(DC))
7221 return false;
7222 llvm_unreachable("Unexpected context");
7223}
7224
7225static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7226 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7227 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7228 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7229 return true;
7230 if (DC->isRecord())
7231 return false;
7232 llvm_unreachable("Unexpected context");
7233}
7234
7235static bool hasParsedAttr(Scope *S, const Declarator &PD,
7236 ParsedAttr::Kind Kind) {
7237 // Check decl attributes on the DeclSpec.
7238 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7239 return true;
7240
7241 // Walk the declarator structure, checking decl attributes that were in a type
7242 // position to the decl itself.
7243 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7244 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7245 return true;
7246 }
7247
7248 // Finally, check attributes on the decl itself.
7249 return PD.getAttributes().hasAttribute(Kind) ||
7251}
7252
7254 if (!DC->isFunctionOrMethod())
7255 return false;
7256
7257 // If this is a local extern function or variable declared within a function
7258 // template, don't add it into the enclosing namespace scope until it is
7259 // instantiated; it might have a dependent type right now.
7260 if (DC->isDependentContext())
7261 return true;
7262
7263 // C++11 [basic.link]p7:
7264 // When a block scope declaration of an entity with linkage is not found to
7265 // refer to some other declaration, then that entity is a member of the
7266 // innermost enclosing namespace.
7267 //
7268 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7269 // semantically-enclosing namespace, not a lexically-enclosing one.
7270 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7271 DC = DC->getParent();
7272 return true;
7273}
7274
7275/// Returns true if given declaration has external C language linkage.
7276static bool isDeclExternC(const Decl *D) {
7277 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7278 return FD->isExternC();
7279 if (const auto *VD = dyn_cast<VarDecl>(D))
7280 return VD->isExternC();
7281
7282 llvm_unreachable("Unknown type of decl!");
7283}
7284
7285/// Returns true if there hasn't been any invalid type diagnosed.
7286static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7287 DeclContext *DC = NewVD->getDeclContext();
7288 QualType R = NewVD->getType();
7289
7290 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7291 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7292 // argument.
7293 if (R->isImageType() || R->isPipeType()) {
7294 Se.Diag(NewVD->getLocation(),
7295 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7296 << R;
7297 NewVD->setInvalidDecl();
7298 return false;
7299 }
7300
7301 // OpenCL v1.2 s6.9.r:
7302 // The event type cannot be used to declare a program scope variable.
7303 // OpenCL v2.0 s6.9.q:
7304 // The clk_event_t and reserve_id_t types cannot be declared in program
7305 // scope.
7306 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7307 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7308 Se.Diag(NewVD->getLocation(),
7309 diag::err_invalid_type_for_program_scope_var)
7310 << R;
7311 NewVD->setInvalidDecl();
7312 return false;
7313 }
7314 }
7315
7316 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7317 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7318 Se.getLangOpts())) {
7319 QualType NR = R.getCanonicalType();
7320 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7321 NR->isReferenceType()) {
7324 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7325 << NR->isReferenceType();
7326 NewVD->setInvalidDecl();
7327 return false;
7328 }
7329 NR = NR->getPointeeType();
7330 }
7331 }
7332
7333 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7334 Se.getLangOpts())) {
7335 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7336 // half array type (unless the cl_khr_fp16 extension is enabled).
7337 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7338 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7339 NewVD->setInvalidDecl();
7340 return false;
7341 }
7342 }
7343
7344 // OpenCL v1.2 s6.9.r:
7345 // The event type cannot be used with the __local, __constant and __global
7346 // address space qualifiers.
7347 if (R->isEventT()) {
7349 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7350 NewVD->setInvalidDecl();
7351 return false;
7352 }
7353 }
7354
7355 if (R->isSamplerT()) {
7356 // OpenCL v1.2 s6.9.b p4:
7357 // The sampler type cannot be used with the __local and __global address
7358 // space qualifiers.
7361 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7362 NewVD->setInvalidDecl();
7363 }
7364
7365 // OpenCL v1.2 s6.12.14.1:
7366 // A global sampler must be declared with either the constant address
7367 // space qualifier or with the const qualifier.
7368 if (DC->isTranslationUnit() &&
7370 R.isConstQualified())) {
7371 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7372 NewVD->setInvalidDecl();
7373 }
7374 if (NewVD->isInvalidDecl())
7375 return false;
7376 }
7377
7378 return true;
7379}
7380
7381template <typename AttrTy>
7382static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7383 const TypedefNameDecl *TND = TT->getDecl();
7384 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7385 AttrTy *Clone = Attribute->clone(S.Context);
7386 Clone->setInherited(true);
7387 D->addAttr(Clone);
7388 }
7389}
7390
7391// This function emits warning and a corresponding note based on the
7392// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7393// declarations of an annotated type must be const qualified.
7395 QualType VarType = VD->getType().getCanonicalType();
7396
7397 // Ignore local declarations (for now) and those with const qualification.
7398 // TODO: Local variables should not be allowed if their type declaration has
7399 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7400 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7401 return;
7402
7403 if (VarType->isArrayType()) {
7404 // Retrieve element type for array declarations.
7405 VarType = S.getASTContext().getBaseElementType(VarType);
7406 }
7407
7408 const RecordDecl *RD = VarType->getAsRecordDecl();
7409
7410 // Check if the record declaration is present and if it has any attributes.
7411 if (RD == nullptr)
7412 return;
7413
7414 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7415 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7416 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7417 return;
7418 }
7419}
7420
7421// Checks if VD is declared at global scope or with C language linkage.
7422static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7423 return Name.getAsIdentifierInfo() &&
7424 Name.getAsIdentifierInfo()->isStr("main") &&
7425 !VD->getDescribedVarTemplate() &&
7427 VD->isExternC());
7428}
7429
7431 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7432 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7433 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7434 QualType R = TInfo->getType();
7436
7437 IdentifierInfo *II = Name.getAsIdentifierInfo();
7438 bool IsPlaceholderVariable = false;
7439
7440 if (D.isDecompositionDeclarator()) {
7441 // Take the name of the first declarator as our name for diagnostic
7442 // purposes.
7443 auto &Decomp = D.getDecompositionDeclarator();
7444 if (!Decomp.bindings().empty()) {
7445 II = Decomp.bindings()[0].Name;
7446 Name = II;
7447 }
7448 } else if (!II) {
7449 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7450 return nullptr;
7451 }
7452
7453
7454 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7456
7457 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7458 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7459 IsPlaceholderVariable = true;
7460 if (!Previous.empty()) {
7461 NamedDecl *PrevDecl = *Previous.begin();
7462 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7463 DC->getRedeclContext());
7464 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7465 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7466 }
7467 }
7468
7469 // dllimport globals without explicit storage class are treated as extern. We
7470 // have to change the storage class this early to get the right DeclContext.
7471 if (SC == SC_None && !DC->isRecord() &&
7472 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7473 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7474 SC = SC_Extern;
7475
7476 DeclContext *OriginalDC = DC;
7477 bool IsLocalExternDecl = SC == SC_Extern &&
7479
7480 if (SCSpec == DeclSpec::SCS_mutable) {
7481 // mutable can only appear on non-static class members, so it's always
7482 // an error here
7483 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7484 D.setInvalidType();
7485 SC = SC_None;
7486 }
7487
7488 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7489 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7490 D.getDeclSpec().getStorageClassSpecLoc())) {
7491 // In C++11, the 'register' storage class specifier is deprecated.
7492 // Suppress the warning in system macros, it's used in macros in some
7493 // popular C system headers, such as in glibc's htonl() macro.
7494 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7495 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7496 : diag::warn_deprecated_register)
7497 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7498 }
7499
7500 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7501
7502 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7503 // C99 6.9p2: The storage-class specifiers auto and register shall not
7504 // appear in the declaration specifiers in an external declaration.
7505 // Global Register+Asm is a GNU extension we support.
7506 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7507 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7508 D.setInvalidType();
7509 }
7510 }
7511
7512 // If this variable has a VLA type and an initializer, try to
7513 // fold to a constant-sized type. This is otherwise invalid.
7514 if (D.hasInitializer() && R->isVariableArrayType())
7515 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7516 /*DiagID=*/0);
7517
7518 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7519 const AutoType *AT = TL.getTypePtr();
7520 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7521 }
7522
7523 bool IsMemberSpecialization = false;
7524 bool IsVariableTemplateSpecialization = false;
7525 bool IsPartialSpecialization = false;
7526 bool IsVariableTemplate = false;
7527 VarDecl *NewVD = nullptr;
7528 VarTemplateDecl *NewTemplate = nullptr;
7529 TemplateParameterList *TemplateParams = nullptr;
7530 if (!getLangOpts().CPlusPlus) {
7531 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7532 II, R, TInfo, SC);
7533
7534 if (R->getContainedDeducedType())
7535 ParsingInitForAutoVars.insert(NewVD);
7536
7537 if (D.isInvalidType())
7538 NewVD->setInvalidDecl();
7539
7541 NewVD->hasLocalStorage())
7542 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7544 } else {
7545 bool Invalid = false;
7546 // Match up the template parameter lists with the scope specifier, then
7547 // determine whether we have a template or a template specialization.
7549 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7550 D.getCXXScopeSpec(),
7552 ? D.getName().TemplateId
7553 : nullptr,
7554 TemplateParamLists,
7555 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7556
7557 if (TemplateParams) {
7558 if (DC->isDependentContext()) {
7559 ContextRAII SavedContext(*this, DC);
7561 Invalid = true;
7562 }
7563
7564 if (!TemplateParams->size() &&
7566 // There is an extraneous 'template<>' for this variable. Complain
7567 // about it, but allow the declaration of the variable.
7568 Diag(TemplateParams->getTemplateLoc(),
7569 diag::err_template_variable_noparams)
7570 << II
7571 << SourceRange(TemplateParams->getTemplateLoc(),
7572 TemplateParams->getRAngleLoc());
7573 TemplateParams = nullptr;
7574 } else {
7575 // Check that we can declare a template here.
7576 if (CheckTemplateDeclScope(S, TemplateParams))
7577 return nullptr;
7578
7579 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7580 // This is an explicit specialization or a partial specialization.
7581 IsVariableTemplateSpecialization = true;
7582 IsPartialSpecialization = TemplateParams->size() > 0;
7583 } else { // if (TemplateParams->size() > 0)
7584 // This is a template declaration.
7585 IsVariableTemplate = true;
7586
7587 // Only C++1y supports variable templates (N3651).
7588 Diag(D.getIdentifierLoc(),
7590 ? diag::warn_cxx11_compat_variable_template
7591 : diag::ext_variable_template);
7592 }
7593 }
7594 } else {
7595 // Check that we can declare a member specialization here.
7596 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7597 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7598 return nullptr;
7599 assert((Invalid ||
7600 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7601 "should have a 'template<>' for this decl");
7602 }
7603
7604 bool IsExplicitSpecialization =
7605 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7606
7607 // C++ [temp.expl.spec]p2:
7608 // The declaration in an explicit-specialization shall not be an
7609 // export-declaration. An explicit specialization shall not use a
7610 // storage-class-specifier other than thread_local.
7611 //
7612 // We use the storage-class-specifier from DeclSpec because we may have
7613 // added implicit 'extern' for declarations with __declspec(dllimport)!
7614 if (SCSpec != DeclSpec::SCS_unspecified &&
7615 (IsExplicitSpecialization || IsMemberSpecialization)) {
7616 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7617 diag::ext_explicit_specialization_storage_class)
7618 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7619 }
7620
7621 if (CurContext->isRecord()) {
7622 if (SC == SC_Static) {
7623 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7624 // Walk up the enclosing DeclContexts to check for any that are
7625 // incompatible with static data members.
7626 const DeclContext *FunctionOrMethod = nullptr;
7627 const CXXRecordDecl *AnonStruct = nullptr;
7628 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7629 if (Ctxt->isFunctionOrMethod()) {
7630 FunctionOrMethod = Ctxt;
7631 break;
7632 }
7633 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7634 if (ParentDecl && !ParentDecl->getDeclName()) {
7635 AnonStruct = ParentDecl;
7636 break;
7637 }
7638 }
7639 if (FunctionOrMethod) {
7640 // C++ [class.static.data]p5: A local class shall not have static
7641 // data members.
7642 Diag(D.getIdentifierLoc(),
7643 diag::err_static_data_member_not_allowed_in_local_class)
7644 << Name << RD->getDeclName()
7645 << llvm::to_underlying(RD->getTagKind());
7646 } else if (AnonStruct) {
7647 // C++ [class.static.data]p4: Unnamed classes and classes contained
7648 // directly or indirectly within unnamed classes shall not contain
7649 // static data members.
7650 Diag(D.getIdentifierLoc(),
7651 diag::err_static_data_member_not_allowed_in_anon_struct)
7652 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7653 Invalid = true;
7654 } else if (RD->isUnion()) {
7655 // C++98 [class.union]p1: If a union contains a static data member,
7656 // the program is ill-formed. C++11 drops this restriction.
7657 Diag(D.getIdentifierLoc(),
7659 ? diag::warn_cxx98_compat_static_data_member_in_union
7660 : diag::ext_static_data_member_in_union)
7661 << Name;
7662 }
7663 }
7664 } else if (IsVariableTemplate || IsPartialSpecialization) {
7665 // There is no such thing as a member field template.
7666 Diag(D.getIdentifierLoc(), diag::err_template_member)
7667 << II << TemplateParams->getSourceRange();
7668 // Recover by pretending this is a static data member template.
7669 SC = SC_Static;
7670 }
7671 } else if (DC->isRecord()) {
7672 // This is an out-of-line definition of a static data member.
7673 switch (SC) {
7674 case SC_None:
7675 break;
7676 case SC_Static:
7677 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7678 diag::err_static_out_of_line)
7680 D.getDeclSpec().getStorageClassSpecLoc());
7681 break;
7682 case SC_Auto:
7683 case SC_Register:
7684 case SC_Extern:
7685 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7686 // to names of variables declared in a block or to function parameters.
7687 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7688 // of class members
7689
7690 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7691 diag::err_storage_class_for_static_member)
7693 D.getDeclSpec().getStorageClassSpecLoc());
7694 break;
7695 case SC_PrivateExtern:
7696 llvm_unreachable("C storage class in c++!");
7697 }
7698 }
7699
7700 if (IsVariableTemplateSpecialization) {
7701 SourceLocation TemplateKWLoc =
7702 TemplateParamLists.size() > 0
7703 ? TemplateParamLists[0]->getTemplateLoc()
7704 : SourceLocation();
7706 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7708 if (Res.isInvalid())
7709 return nullptr;
7710 NewVD = cast<VarDecl>(Res.get());
7711 AddToScope = false;
7712 } else if (D.isDecompositionDeclarator()) {
7714 D.getIdentifierLoc(), R, TInfo, SC,
7715 Bindings);
7716 } else
7717 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7718 D.getIdentifierLoc(), II, R, TInfo, SC);
7719
7720 // If this is supposed to be a variable template, create it as such.
7721 if (IsVariableTemplate) {
7722 NewTemplate =
7723 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7724 TemplateParams, NewVD);
7725 NewVD->setDescribedVarTemplate(NewTemplate);
7726 }
7727
7728 // If this decl has an auto type in need of deduction, make a note of the
7729 // Decl so we can diagnose uses of it in its own initializer.
7730 if (R->getContainedDeducedType())
7731 ParsingInitForAutoVars.insert(NewVD);
7732
7733 if (D.isInvalidType() || Invalid) {
7734 NewVD->setInvalidDecl();
7735 if (NewTemplate)
7736 NewTemplate->setInvalidDecl();
7737 }
7738
7739 SetNestedNameSpecifier(*this, NewVD, D);
7740
7741 // If we have any template parameter lists that don't directly belong to
7742 // the variable (matching the scope specifier), store them.
7743 // An explicit variable template specialization does not own any template
7744 // parameter lists.
7745 unsigned VDTemplateParamLists =
7746 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7747 if (TemplateParamLists.size() > VDTemplateParamLists)
7749 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7750 }
7751
7752 if (D.getDeclSpec().isInlineSpecified()) {
7753 if (!getLangOpts().CPlusPlus) {
7754 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7755 << 0;
7756 } else if (CurContext->isFunctionOrMethod()) {
7757 // 'inline' is not allowed on block scope variable declaration.
7758 Diag(D.getDeclSpec().getInlineSpecLoc(),
7759 diag::err_inline_declaration_block_scope) << Name
7760 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7761 } else {
7762 Diag(D.getDeclSpec().getInlineSpecLoc(),
7763 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7764 : diag::ext_inline_variable);
7765 NewVD->setInlineSpecified();
7766 }
7767 }
7768
7769 // Set the lexical context. If the declarator has a C++ scope specifier, the
7770 // lexical context will be different from the semantic context.
7772 if (NewTemplate)
7773 NewTemplate->setLexicalDeclContext(CurContext);
7774
7775 if (IsLocalExternDecl) {
7776 if (D.isDecompositionDeclarator())
7777 for (auto *B : Bindings)
7778 B->setLocalExternDecl();
7779 else
7780 NewVD->setLocalExternDecl();
7781 }
7782
7783 bool EmitTLSUnsupportedError = false;
7784 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7785 // C++11 [dcl.stc]p4:
7786 // When thread_local is applied to a variable of block scope the
7787 // storage-class-specifier static is implied if it does not appear
7788 // explicitly.
7789 // Core issue: 'static' is not implied if the variable is declared
7790 // 'extern'.
7791 if (NewVD->hasLocalStorage() &&
7792 (SCSpec != DeclSpec::SCS_unspecified ||
7794 !DC->isFunctionOrMethod()))
7795 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7796 diag::err_thread_non_global)
7798 else if (!Context.getTargetInfo().isTLSSupported()) {
7799 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7800 getLangOpts().SYCLIsDevice) {
7801 // Postpone error emission until we've collected attributes required to
7802 // figure out whether it's a host or device variable and whether the
7803 // error should be ignored.
7804 EmitTLSUnsupportedError = true;
7805 // We still need to mark the variable as TLS so it shows up in AST with
7806 // proper storage class for other tools to use even if we're not going
7807 // to emit any code for it.
7808 NewVD->setTSCSpec(TSCS);
7809 } else
7810 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7811 diag::err_thread_unsupported);
7812 } else
7813 NewVD->setTSCSpec(TSCS);
7814 }
7815
7816 switch (D.getDeclSpec().getConstexprSpecifier()) {
7818 break;
7819
7821 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7822 diag::err_constexpr_wrong_decl_kind)
7823 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7824 [[fallthrough]];
7825
7827 NewVD->setConstexpr(true);
7828 // C++1z [dcl.spec.constexpr]p1:
7829 // A static data member declared with the constexpr specifier is
7830 // implicitly an inline variable.
7831 if (NewVD->isStaticDataMember() &&
7832 (getLangOpts().CPlusPlus17 ||
7834 NewVD->setImplicitlyInline();
7835 break;
7836
7838 if (!NewVD->hasGlobalStorage())
7839 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7840 diag::err_constinit_local_variable);
7841 else
7842 NewVD->addAttr(
7843 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7844 ConstInitAttr::Keyword_constinit));
7845 break;
7846 }
7847
7848 // C99 6.7.4p3
7849 // An inline definition of a function with external linkage shall
7850 // not contain a definition of a modifiable object with static or
7851 // thread storage duration...
7852 // We only apply this when the function is required to be defined
7853 // elsewhere, i.e. when the function is not 'extern inline'. Note
7854 // that a local variable with thread storage duration still has to
7855 // be marked 'static'. Also note that it's possible to get these
7856 // semantics in C++ using __attribute__((gnu_inline)).
7857 if (SC == SC_Static && S->getFnParent() != nullptr &&
7858 !NewVD->getType().isConstQualified()) {
7860 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7861 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7862 diag::warn_static_local_in_extern_inline);
7864 }
7865 }
7866
7867 if (D.getDeclSpec().isModulePrivateSpecified()) {
7868 if (IsVariableTemplateSpecialization)
7869 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7870 << (IsPartialSpecialization ? 1 : 0)
7872 D.getDeclSpec().getModulePrivateSpecLoc());
7873 else if (IsMemberSpecialization)
7874 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7875 << 2
7876 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7877 else if (NewVD->hasLocalStorage())
7878 Diag(NewVD->getLocation(), diag::err_module_private_local)
7879 << 0 << NewVD
7880 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7882 D.getDeclSpec().getModulePrivateSpecLoc());
7883 else {
7884 NewVD->setModulePrivate();
7885 if (NewTemplate)
7886 NewTemplate->setModulePrivate();
7887 for (auto *B : Bindings)
7888 B->setModulePrivate();
7889 }
7890 }
7891
7892 if (getLangOpts().OpenCL) {
7894
7895 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7896 if (TSC != TSCS_unspecified) {
7897 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7898 diag::err_opencl_unknown_type_specifier)
7900 << DeclSpec::getSpecifierName(TSC) << 1;
7901 NewVD->setInvalidDecl();
7902 }
7903 }
7904
7905 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7906 // address space if the table has local storage (semantic checks elsewhere
7907 // will produce an error anyway).
7908 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7909 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7910 !NewVD->hasLocalStorage()) {
7913 NewVD->setType(Type);
7914 }
7915 }
7916
7917 // Handle attributes prior to checking for duplicates in MergeVarDecl
7918 ProcessDeclAttributes(S, NewVD, D);
7919
7920 if (getLangOpts().HLSL)
7922
7923 // FIXME: This is probably the wrong location to be doing this and we should
7924 // probably be doing this for more attributes (especially for function
7925 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7926 // the code to copy attributes would be generated by TableGen.
7927 if (R->isFunctionPointerType())
7928 if (const auto *TT = R->getAs<TypedefType>())
7929 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7930
7931 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7932 getLangOpts().SYCLIsDevice) {
7933 if (EmitTLSUnsupportedError &&
7935 (getLangOpts().OpenMPIsTargetDevice &&
7936 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7937 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7938 diag::err_thread_unsupported);
7939
7940 if (EmitTLSUnsupportedError &&
7941 (LangOpts.SYCLIsDevice ||
7942 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7943 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7944 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7945 // storage [duration]."
7946 if (SC == SC_None && S->getFnParent() != nullptr &&
7947 (NewVD->hasAttr<CUDASharedAttr>() ||
7948 NewVD->hasAttr<CUDAConstantAttr>())) {
7949 NewVD->setStorageClass(SC_Static);
7950 }
7951 }
7952
7953 // Ensure that dllimport globals without explicit storage class are treated as
7954 // extern. The storage class is set above using parsed attributes. Now we can
7955 // check the VarDecl itself.
7956 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7957 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7958 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7959
7960 // In auto-retain/release, infer strong retension for variables of
7961 // retainable type.
7962 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
7963 NewVD->setInvalidDecl();
7964
7965 // Handle GNU asm-label extension (encoded as an attribute).
7966 if (Expr *E = (Expr*)D.getAsmLabel()) {
7967 // The parser guarantees this is a string.
7968 StringLiteral *SE = cast<StringLiteral>(E);
7969 StringRef Label = SE->getString();
7970 if (S->getFnParent() != nullptr) {
7971 switch (SC) {
7972 case SC_None:
7973 case SC_Auto:
7974 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7975 break;
7976 case SC_Register:
7977 // Local Named register
7980 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7981 break;
7982 case SC_Static:
7983 case SC_Extern:
7984 case SC_PrivateExtern:
7985 break;
7986 }
7987 } else if (SC == SC_Register) {
7988 // Global Named register
7989 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7990 const auto &TI = Context.getTargetInfo();
7991 bool HasSizeMismatch;
7992
7993 if (!TI.isValidGCCRegisterName(Label))
7994 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7995 else if (!TI.validateGlobalRegisterVariable(Label,
7997 HasSizeMismatch))
7998 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7999 else if (HasSizeMismatch)
8000 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
8001 }
8002
8003 if (!R->isIntegralType(Context) && !R->isPointerType()) {
8004 Diag(TInfo->getTypeLoc().getBeginLoc(),
8005 diag::err_asm_unsupported_register_type)
8006 << TInfo->getTypeLoc().getSourceRange();
8007 NewVD->setInvalidDecl(true);
8008 }
8009 }
8010
8011 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
8012 /*IsLiteralLabel=*/true,
8013 SE->getStrTokenLoc(0)));
8014 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8015 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8017 if (I != ExtnameUndeclaredIdentifiers.end()) {
8018 if (isDeclExternC(NewVD)) {
8019 NewVD->addAttr(I->second);
8021 } else
8022 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8023 << /*Variable*/1 << NewVD;
8024 }
8025 }
8026
8027 // Find the shadowed declaration before filtering for scope.
8028 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8030 : nullptr;
8031
8032 // Don't consider existing declarations that are in a different
8033 // scope and are out-of-semantic-context declarations (if the new
8034 // declaration has linkage).
8036 D.getCXXScopeSpec().isNotEmpty() ||
8037 IsMemberSpecialization ||
8038 IsVariableTemplateSpecialization);
8039
8040 // Check whether the previous declaration is in the same block scope. This
8041 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8042 if (getLangOpts().CPlusPlus &&
8043 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8045 Previous.isSingleResult() && !Previous.isShadowed() &&
8046 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8047
8048 if (!getLangOpts().CPlusPlus) {
8049 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8050 } else {
8051 // If this is an explicit specialization of a static data member, check it.
8052 if (IsMemberSpecialization && !IsVariableTemplate &&
8053 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8055 NewVD->setInvalidDecl();
8056
8057 // Merge the decl with the existing one if appropriate.
8058 if (!Previous.empty()) {
8059 if (Previous.isSingleResult() &&
8060 isa<FieldDecl>(Previous.getFoundDecl()) &&
8061 D.getCXXScopeSpec().isSet()) {
8062 // The user tried to define a non-static data member
8063 // out-of-line (C++ [dcl.meaning]p1).
8064 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8065 << D.getCXXScopeSpec().getRange();
8066 Previous.clear();
8067 NewVD->setInvalidDecl();
8068 }
8069 } else if (D.getCXXScopeSpec().isSet() &&
8070 !IsVariableTemplateSpecialization) {
8071 // No previous declaration in the qualifying scope.
8072 Diag(D.getIdentifierLoc(), diag::err_no_member)
8073 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8074 << D.getCXXScopeSpec().getRange();
8075 NewVD->setInvalidDecl();
8076 }
8077
8078 if (!IsPlaceholderVariable)
8079 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
8080
8081 // CheckVariableDeclaration will set NewVD as invalid if something is in
8082 // error like WebAssembly tables being declared as arrays with a non-zero
8083 // size, but then parsing continues and emits further errors on that line.
8084 // To avoid that we check here if it happened and return nullptr.
8085 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8086 return nullptr;
8087
8088 if (NewTemplate) {
8089 VarTemplateDecl *PrevVarTemplate =
8090 NewVD->getPreviousDecl()
8092 : nullptr;
8093
8094 // Check the template parameter list of this declaration, possibly
8095 // merging in the template parameter list from the previous variable
8096 // template declaration.
8098 TemplateParams,
8099 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8100 : nullptr,
8101 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8102 DC->isDependentContext())
8104 : TPC_VarTemplate))
8105 NewVD->setInvalidDecl();
8106
8107 // If we are providing an explicit specialization of a static variable
8108 // template, make a note of that.
8109 if (PrevVarTemplate &&
8110 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8111 PrevVarTemplate->setMemberSpecialization();
8112 }
8113 }
8114
8115 // Diagnose shadowed variables iff this isn't a redeclaration.
8116 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8117 CheckShadow(NewVD, ShadowedDecl, Previous);
8118
8119 ProcessPragmaWeak(S, NewVD);
8120
8121 // If this is the first declaration of an extern C variable, update
8122 // the map of such variables.
8123 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8124 isIncompleteDeclExternC(*this, NewVD))
8126
8127 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8129 Decl *ManglingContextDecl;
8130 std::tie(MCtx, ManglingContextDecl) =
8132 if (MCtx) {
8134 NewVD, MCtx->getManglingNumber(
8135 NewVD, getMSManglingNumber(getLangOpts(), S)));
8137 }
8138 }
8139
8140 // Special handling of variable named 'main'.
8141 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8142 // C++ [basic.start.main]p3:
8143 // A program that declares
8144 // - a variable main at global scope, or
8145 // - an entity named main with C language linkage (in any namespace)
8146 // is ill-formed
8147 if (getLangOpts().CPlusPlus)
8148 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8149 << NewVD->isExternC();
8150
8151 // In C, and external-linkage variable named main results in undefined
8152 // behavior.
8153 else if (NewVD->hasExternalFormalLinkage())
8154 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8155 }
8156
8157 if (D.isRedeclaration() && !Previous.empty()) {
8158 NamedDecl *Prev = Previous.getRepresentativeDecl();
8159 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8160 D.isFunctionDefinition());
8161 }
8162
8163 if (NewTemplate) {
8164 if (NewVD->isInvalidDecl())
8165 NewTemplate->setInvalidDecl();
8166 ActOnDocumentableDecl(NewTemplate);
8167 return NewTemplate;
8168 }
8169
8170 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8172
8174
8175 return NewVD;
8176}
8177
8178/// Enum describing the %select options in diag::warn_decl_shadow.
8188
8189/// Determine what kind of declaration we're shadowing.
8191 const DeclContext *OldDC) {
8192 if (isa<TypeAliasDecl>(ShadowedDecl))
8193 return SDK_Using;
8194 else if (isa<TypedefDecl>(ShadowedDecl))
8195 return SDK_Typedef;
8196 else if (isa<BindingDecl>(ShadowedDecl))
8197 return SDK_StructuredBinding;
8198 else if (isa<RecordDecl>(OldDC))
8199 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8200
8201 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8202}
8203
8204/// Return the location of the capture if the given lambda captures the given
8205/// variable \p VD, or an invalid source location otherwise.
8207 const VarDecl *VD) {
8208 for (const Capture &Capture : LSI->Captures) {
8210 return Capture.getLocation();
8211 }
8212 return SourceLocation();
8213}
8214
8216 const LookupResult &R) {
8217 // Only diagnose if we're shadowing an unambiguous field or variable.
8219 return false;
8220
8221 // Return false if warning is ignored.
8222 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8223}
8224
8226 const LookupResult &R) {
8228 return nullptr;
8229
8230 // Don't diagnose declarations at file scope.
8231 if (D->hasGlobalStorage() && !D->isStaticLocal())
8232 return nullptr;
8233
8234 NamedDecl *ShadowedDecl = R.getFoundDecl();
8235 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8236 : nullptr;
8237}
8238
8240 const LookupResult &R) {
8241 // Don't warn if typedef declaration is part of a class
8242 if (D->getDeclContext()->isRecord())
8243 return nullptr;
8244
8246 return nullptr;
8247
8248 NamedDecl *ShadowedDecl = R.getFoundDecl();
8249 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8250}
8251
8253 const LookupResult &R) {
8255 return nullptr;
8256
8257 NamedDecl *ShadowedDecl = R.getFoundDecl();
8258 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8259 : nullptr;
8260}
8261
8263 const LookupResult &R) {
8264 DeclContext *NewDC = D->getDeclContext();
8265
8266 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8267 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) {
8268 // Fields are not shadowed by variables in C++ static methods.
8269 if (MD->isStatic())
8270 return;
8271
8272 if (!MD->getParent()->isLambda() && MD->isExplicitObjectMemberFunction())
8273 return;
8274 }
8275 // Fields shadowed by constructor parameters are a special case. Usually
8276 // the constructor initializes the field with the parameter.
8277 if (isa<CXXConstructorDecl>(NewDC))
8278 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8279 // Remember that this was shadowed so we can either warn about its
8280 // modification or its existence depending on warning settings.
8281 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8282 return;
8283 }
8284 }
8285
8286 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8287 if (shadowedVar->isExternC()) {
8288 // For shadowing external vars, make sure that we point to the global
8289 // declaration, not a locally scoped extern declaration.
8290 for (auto *I : shadowedVar->redecls())
8291 if (I->isFileVarDecl()) {
8292 ShadowedDecl = I;
8293 break;
8294 }
8295 }
8296
8297 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8298
8299 unsigned WarningDiag = diag::warn_decl_shadow;
8300 SourceLocation CaptureLoc;
8301 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8302 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8303 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8304 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8305 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8306 if (RD->getLambdaCaptureDefault() == LCD_None) {
8307 // Try to avoid warnings for lambdas with an explicit capture
8308 // list. Warn only when the lambda captures the shadowed decl
8309 // explicitly.
8310 CaptureLoc = getCaptureLocation(LSI, VD);
8311 if (CaptureLoc.isInvalid())
8312 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8313 } else {
8314 // Remember that this was shadowed so we can avoid the warning if
8315 // the shadowed decl isn't captured and the warning settings allow
8316 // it.
8317 cast<LambdaScopeInfo>(getCurFunction())
8318 ->ShadowingDecls.push_back({D, VD});
8319 return;
8320 }
8321 }
8322 if (isa<FieldDecl>(ShadowedDecl)) {
8323 // If lambda can capture this, then emit default shadowing warning,
8324 // Otherwise it is not really a shadowing case since field is not
8325 // available in lambda's body.
8326 // At this point we don't know that lambda can capture this, so
8327 // remember that this was shadowed and delay until we know.
8328 cast<LambdaScopeInfo>(getCurFunction())
8329 ->ShadowingDecls.push_back({D, ShadowedDecl});
8330 return;
8331 }
8332 }
8333 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8334 VD && VD->hasLocalStorage()) {
8335 // A variable can't shadow a local variable in an enclosing scope, if
8336 // they are separated by a non-capturing declaration context.
8337 for (DeclContext *ParentDC = NewDC;
8338 ParentDC && !ParentDC->Equals(OldDC);
8339 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8340 // Only block literals, captured statements, and lambda expressions
8341 // can capture; other scopes don't.
8342 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8343 !isLambdaCallOperator(ParentDC)) {
8344 return;
8345 }
8346 }
8347 }
8348 }
8349 }
8350
8351 // Never warn about shadowing a placeholder variable.
8352 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8353 return;
8354
8355 // Only warn about certain kinds of shadowing for class members.
8356 if (NewDC) {
8357 // In particular, don't warn about shadowing non-class members.
8358 if (NewDC->isRecord() && !OldDC->isRecord())
8359 return;
8360
8361 // Skip shadowing check if we're in a class scope, dealing with an enum
8362 // constant in a different context.
8363 DeclContext *ReDC = NewDC->getRedeclContext();
8364 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8365 return;
8366
8367 // TODO: should we warn about static data members shadowing
8368 // static data members from base classes?
8369
8370 // TODO: don't diagnose for inaccessible shadowed members.
8371 // This is hard to do perfectly because we might friend the
8372 // shadowing context, but that's just a false negative.
8373 }
8374
8375 DeclarationName Name = R.getLookupName();
8376
8377 // Emit warning and note.
8378 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8379 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8380 if (!CaptureLoc.isInvalid())
8381 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8382 << Name << /*explicitly*/ 1;
8383 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8384}
8385
8387 for (const auto &Shadow : LSI->ShadowingDecls) {
8388 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8389 // Try to avoid the warning when the shadowed decl isn't captured.
8390 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8391 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8392 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8393 Diag(Shadow.VD->getLocation(),
8394 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8395 : diag::warn_decl_shadow)
8396 << Shadow.VD->getDeclName()
8397 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8398 if (CaptureLoc.isValid())
8399 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8400 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8401 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8402 } else if (isa<FieldDecl>(ShadowedDecl)) {
8403 Diag(Shadow.VD->getLocation(),
8404 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8405 : diag::warn_decl_shadow_uncaptured_local)
8406 << Shadow.VD->getDeclName()
8407 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8408 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8409 }
8410 }
8411}
8412
8414 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8415 return;
8416
8417 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8419 RedeclarationKind::ForVisibleRedeclaration);
8420 LookupName(R, S);
8421 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8422 CheckShadow(D, ShadowedDecl, R);
8423}
8424
8425/// Check if 'E', which is an expression that is about to be modified, refers
8426/// to a constructor parameter that shadows a field.
8428 // Quickly ignore expressions that can't be shadowing ctor parameters.
8429 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8430 return;
8431 E = E->IgnoreParenImpCasts();
8432 auto *DRE = dyn_cast<DeclRefExpr>(E);
8433 if (!DRE)
8434 return;
8435 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8436 auto I = ShadowingDecls.find(D);
8437 if (I == ShadowingDecls.end())
8438 return;
8439 const NamedDecl *ShadowedDecl = I->second;
8440 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8441 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8442 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8443 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8444
8445 // Avoid issuing multiple warnings about the same decl.
8446 ShadowingDecls.erase(I);
8447}
8448
8449/// Check for conflict between this global or extern "C" declaration and
8450/// previous global or extern "C" declarations. This is only used in C++.
8451template<typename T>
8453 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8454 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8455 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8456
8457 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8458 // The common case: this global doesn't conflict with any extern "C"
8459 // declaration.
8460 return false;
8461 }
8462
8463 if (Prev) {
8464 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8465 // Both the old and new declarations have C language linkage. This is a
8466 // redeclaration.
8467 Previous.clear();
8468 Previous.addDecl(Prev);
8469 return true;
8470 }
8471
8472 // This is a global, non-extern "C" declaration, and there is a previous
8473 // non-global extern "C" declaration. Diagnose if this is a variable
8474 // declaration.
8475 if (!isa<VarDecl>(ND))
8476 return false;
8477 } else {
8478 // The declaration is extern "C". Check for any declaration in the
8479 // translation unit which might conflict.
8480 if (IsGlobal) {
8481 // We have already performed the lookup into the translation unit.
8482 IsGlobal = false;
8483 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8484 I != E; ++I) {
8485 if (isa<VarDecl>(*I)) {
8486 Prev = *I;
8487 break;
8488 }
8489 }
8490 } else {
8492 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8493 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8494 I != E; ++I) {
8495 if (isa<VarDecl>(*I)) {
8496 Prev = *I;
8497 break;
8498 }
8499 // FIXME: If we have any other entity with this name in global scope,
8500 // the declaration is ill-formed, but that is a defect: it breaks the
8501 // 'stat' hack, for instance. Only variables can have mangled name
8502 // clashes with extern "C" declarations, so only they deserve a
8503 // diagnostic.
8504 }
8505 }
8506
8507 if (!Prev)
8508 return false;
8509 }
8510
8511 // Use the first declaration's location to ensure we point at something which
8512 // is lexically inside an extern "C" linkage-spec.
8513 assert(Prev && "should have found a previous declaration to diagnose");
8514 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8515 Prev = FD->getFirstDecl();
8516 else
8517 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8518
8519 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8520 << IsGlobal << ND;
8521 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8522 << IsGlobal;
8523 return false;
8524}
8525
8526/// Apply special rules for handling extern "C" declarations. Returns \c true
8527/// if we have found that this is a redeclaration of some prior entity.
8528///
8529/// Per C++ [dcl.link]p6:
8530/// Two declarations [for a function or variable] with C language linkage
8531/// with the same name that appear in different scopes refer to the same
8532/// [entity]. An entity with C language linkage shall not be declared with
8533/// the same name as an entity in global scope.
8534template<typename T>
8537 if (!S.getLangOpts().CPlusPlus) {
8538 // In C, when declaring a global variable, look for a corresponding 'extern'
8539 // variable declared in function scope. We don't need this in C++, because
8540 // we find local extern decls in the surrounding file-scope DeclContext.
8541 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8542 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8543 Previous.clear();
8544 Previous.addDecl(Prev);
8545 return true;
8546 }
8547 }
8548 return false;
8549 }
8550
8551 // A declaration in the translation unit can conflict with an extern "C"
8552 // declaration.
8553 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8554 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8555
8556 // An extern "C" declaration can conflict with a declaration in the
8557 // translation unit or can be a redeclaration of an extern "C" declaration
8558 // in another scope.
8559 if (isIncompleteDeclExternC(S,ND))
8560 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8561
8562 // Neither global nor extern "C": nothing to do.
8563 return false;
8564}
8565
8566static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8567 QualType T) {
8568 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8569 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8570 // any of its members, even recursively, shall not have an atomic type, or a
8571 // variably modified type, or a type that is volatile or restrict qualified.
8572 if (CanonT->isVariablyModifiedType()) {
8573 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8574 return true;
8575 }
8576
8577 // Arrays are qualified by their element type, so get the base type (this
8578 // works on non-arrays as well).
8579 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8580
8581 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8582 CanonT.isRestrictQualified()) {
8583 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8584 return true;
8585 }
8586
8587 if (CanonT->isRecordType()) {
8588 const RecordDecl *RD = CanonT->getAsRecordDecl();
8589 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8590 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8591 }))
8592 return true;
8593 }
8594
8595 return false;
8596}
8597
8599 // If the decl is already known invalid, don't check it.
8600 if (NewVD->isInvalidDecl())
8601 return;
8602
8603 QualType T = NewVD->getType();
8604
8605 // Defer checking an 'auto' type until its initializer is attached.
8606 if (T->isUndeducedType())
8607 return;
8608
8609 if (NewVD->hasAttrs())
8611
8612 if (T->isObjCObjectType()) {
8613 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8614 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8616 NewVD->setType(T);
8617 }
8618
8619 // Emit an error if an address space was applied to decl with local storage.
8620 // This includes arrays of objects with address space qualifiers, but not
8621 // automatic variables that point to other address spaces.
8622 // ISO/IEC TR 18037 S5.1.2
8623 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8624 T.getAddressSpace() != LangAS::Default) {
8625 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8626 NewVD->setInvalidDecl();
8627 return;
8628 }
8629
8630 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8631 // scope.
8632 if (getLangOpts().OpenCLVersion == 120 &&
8633 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8634 getLangOpts()) &&
8635 NewVD->isStaticLocal()) {
8636 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8637 NewVD->setInvalidDecl();
8638 return;
8639 }
8640
8641 if (getLangOpts().OpenCL) {
8642 if (!diagnoseOpenCLTypes(*this, NewVD))
8643 return;
8644
8645 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8646 if (NewVD->hasAttr<BlocksAttr>()) {
8647 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8648 return;
8649 }
8650
8651 if (T->isBlockPointerType()) {
8652 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8653 // can't use 'extern' storage class.
8654 if (!T.isConstQualified()) {
8655 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8656 << 0 /*const*/;
8657 NewVD->setInvalidDecl();
8658 return;
8659 }
8660 if (NewVD->hasExternalStorage()) {
8661 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8662 NewVD->setInvalidDecl();
8663 return;
8664 }
8665 }
8666
8667 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8668 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8669 NewVD->hasExternalStorage()) {
8670 if (!T->isSamplerT() && !T->isDependentType() &&
8671 !(T.getAddressSpace() == LangAS::opencl_constant ||
8672 (T.getAddressSpace() == LangAS::opencl_global &&
8673 getOpenCLOptions().areProgramScopeVariablesSupported(
8674 getLangOpts())))) {
8675 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8676 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8677 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8678 << Scope << "global or constant";
8679 else
8680 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8681 << Scope << "constant";
8682 NewVD->setInvalidDecl();
8683 return;
8684 }
8685 } else {
8686 if (T.getAddressSpace() == LangAS::opencl_global) {
8687 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8688 << 1 /*is any function*/ << "global";
8689 NewVD->setInvalidDecl();
8690 return;
8691 }
8692 if (T.getAddressSpace() == LangAS::opencl_constant ||
8693 T.getAddressSpace() == LangAS::opencl_local) {
8695 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8696 // in functions.
8697 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8698 if (T.getAddressSpace() == LangAS::opencl_constant)
8699 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8700 << 0 /*non-kernel only*/ << "constant";
8701 else
8702 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8703 << 0 /*non-kernel only*/ << "local";
8704 NewVD->setInvalidDecl();
8705 return;
8706 }
8707 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8708 // in the outermost scope of a kernel function.
8709 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8710 if (!getCurScope()->isFunctionScope()) {
8711 if (T.getAddressSpace() == LangAS::opencl_constant)
8712 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8713 << "constant";
8714 else
8715 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8716 << "local";
8717 NewVD->setInvalidDecl();
8718 return;
8719 }
8720 }
8721 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8722 // If we are parsing a template we didn't deduce an addr
8723 // space yet.
8724 T.getAddressSpace() != LangAS::Default) {
8725 // Do not allow other address spaces on automatic variable.
8726 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8727 NewVD->setInvalidDecl();
8728 return;
8729 }
8730 }
8731 }
8732
8733 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8734 && !NewVD->hasAttr<BlocksAttr>()) {
8735 if (getLangOpts().getGC() != LangOptions::NonGC)
8736 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8737 else {
8738 assert(!getLangOpts().ObjCAutoRefCount);
8739 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8740 }
8741 }
8742
8743 // WebAssembly tables must be static with a zero length and can't be
8744 // declared within functions.
8745 if (T->isWebAssemblyTableType()) {
8746 if (getCurScope()->getParent()) { // Parent is null at top-level
8747 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8748 NewVD->setInvalidDecl();
8749 return;
8750 }
8751 if (NewVD->getStorageClass() != SC_Static) {
8752 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8753 NewVD->setInvalidDecl();
8754 return;
8755 }
8756 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8757 if (!ATy || ATy->getZExtSize() != 0) {
8758 Diag(NewVD->getLocation(),
8759 diag::err_typecheck_wasm_table_must_have_zero_length);
8760 NewVD->setInvalidDecl();
8761 return;
8762 }
8763 }
8764
8765 // zero sized static arrays are not allowed in HIP device functions
8766 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
8767 if (FunctionDecl *FD = getCurFunctionDecl();
8768 FD &&
8769 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
8770 if (const ConstantArrayType *ArrayT =
8772 ArrayT && ArrayT->isZeroSize()) {
8773 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
8774 }
8775 }
8776 }
8777
8778 bool isVM = T->isVariablyModifiedType();
8779 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8780 NewVD->hasAttr<BlocksAttr>())
8782
8783 if ((isVM && NewVD->hasLinkage()) ||
8784 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8785 bool SizeIsNegative;
8786 llvm::APSInt Oversized;
8788 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8789 QualType FixedT;
8790 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8791 FixedT = FixedTInfo->getType();
8792 else if (FixedTInfo) {
8793 // Type and type-as-written are canonically different. We need to fix up
8794 // both types separately.
8795 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8796 Oversized);
8797 }
8798 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8800 // FIXME: This won't give the correct result for
8801 // int a[10][n];
8802 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8803
8804 if (NewVD->isFileVarDecl())
8805 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8806 << SizeRange;
8807 else if (NewVD->isStaticLocal())
8808 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8809 << SizeRange;
8810 else
8811 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8812 << SizeRange;
8813 NewVD->setInvalidDecl();
8814 return;
8815 }
8816
8817 if (!FixedTInfo) {
8818 if (NewVD->isFileVarDecl())
8819 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8820 else
8821 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8822 NewVD->setInvalidDecl();
8823 return;
8824 }
8825
8826 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8827 NewVD->setType(FixedT);
8828 NewVD->setTypeSourceInfo(FixedTInfo);
8829 }
8830
8831 if (T->isVoidType()) {
8832 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8833 // of objects and functions.
8835 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8836 << T;
8837 NewVD->setInvalidDecl();
8838 return;
8839 }
8840 }
8841
8842 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8843 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8844 NewVD->setInvalidDecl();
8845 return;
8846 }
8847
8848 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8849 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
8850 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8851 NewVD->setInvalidDecl();
8852 return;
8853 }
8854
8855 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8856 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8857 NewVD->setInvalidDecl();
8858 return;
8859 }
8860
8861 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8862 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8863 NewVD->setInvalidDecl();
8864 return;
8865 }
8866
8867 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
8868 !T->isDependentType() &&
8870 diag::err_constexpr_var_non_literal)) {
8871 NewVD->setInvalidDecl();
8872 return;
8873 }
8874
8875 // PPC MMA non-pointer types are not allowed as non-local variable types.
8876 if (Context.getTargetInfo().getTriple().isPPC64() &&
8877 !NewVD->isLocalVarDecl() &&
8878 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
8879 NewVD->setInvalidDecl();
8880 return;
8881 }
8882
8883 // Check that SVE types are only used in functions with SVE available.
8884 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8885 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8886 llvm::StringMap<bool> CallerFeatureMap;
8887 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8888
8889 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
8890 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
8891 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8892 NewVD->setInvalidDecl();
8893 return;
8894 } else if (!IsArmStreamingFunction(FD,
8895 /*IncludeLocallyStreaming=*/true)) {
8896 Diag(NewVD->getLocation(),
8897 diag::err_sve_vector_in_non_streaming_function)
8898 << T;
8899 NewVD->setInvalidDecl();
8900 return;
8901 }
8902 }
8903 }
8904
8905 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8906 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8907 llvm::StringMap<bool> CallerFeatureMap;
8908 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8909 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
8910 CallerFeatureMap);
8911 }
8912}
8913
8916
8917 // If the decl is already known invalid, don't check it.
8918 if (NewVD->isInvalidDecl())
8919 return false;
8920
8921 // If we did not find anything by this name, look for a non-visible
8922 // extern "C" declaration with the same name.
8923 if (Previous.empty() &&
8925 Previous.setShadowed();
8926
8927 if (!Previous.empty()) {
8928 MergeVarDecl(NewVD, Previous);
8929 return true;
8930 }
8931 return false;
8932}
8933
8936
8937 // Look for methods in base classes that this method might override.
8938 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8939 /*DetectVirtual=*/false);
8940 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8941 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8942 DeclarationName Name = MD->getDeclName();
8943
8944 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8945 // We really want to find the base class destructor here.
8946 QualType T = Context.getTypeDeclType(BaseRecord);
8949 }
8950
8951 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8952 CXXMethodDecl *BaseMD =
8953 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8954 if (!BaseMD || !BaseMD->isVirtual() ||
8955 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8956 /*ConsiderCudaAttrs=*/true))
8957 continue;
8958 if (!CheckExplicitObjectOverride(MD, BaseMD))
8959 continue;
8960 if (Overridden.insert(BaseMD).second) {
8961 MD->addOverriddenMethod(BaseMD);
8966 }
8967
8968 // A method can only override one function from each base class. We
8969 // don't track indirectly overridden methods from bases of bases.
8970 return true;
8971 }
8972
8973 return false;
8974 };
8975
8976 DC->lookupInBases(VisitBase, Paths);
8977 return !Overridden.empty();
8978}
8979
8980namespace {
8981 // Struct for holding all of the extra arguments needed by
8982 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8983 struct ActOnFDArgs {
8984 Scope *S;
8985 Declarator &D;
8986 MultiTemplateParamsArg TemplateParamLists;
8987 bool AddToScope;
8988 };
8989} // end anonymous namespace
8990
8991namespace {
8992
8993// Callback to only accept typo corrections that have a non-zero edit distance.
8994// Also only accept corrections that have the same parent decl.
8995class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8996 public:
8997 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8999 : Context(Context), OriginalFD(TypoFD),
9000 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9001
9002 bool ValidateCandidate(const TypoCorrection &candidate) override {
9003 if (candidate.getEditDistance() == 0)
9004 return false;
9005
9006 SmallVector<unsigned, 1> MismatchedParams;
9007 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9008 CDeclEnd = candidate.end();
9009 CDecl != CDeclEnd; ++CDecl) {
9010 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9011
9012 if (FD && !FD->hasBody() &&
9013 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9015 CXXRecordDecl *Parent = MD->getParent();
9016 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9017 return true;
9018 } else if (!ExpectedParent) {
9019 return true;
9020 }
9021 }
9022 }
9023
9024 return false;
9025 }
9026
9027 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9028 return std::make_unique<DifferentNameValidatorCCC>(*this);
9029 }
9030
9031 private:
9032 ASTContext &Context;
9033 FunctionDecl *OriginalFD;
9034 CXXRecordDecl *ExpectedParent;
9035};
9036
9037} // end anonymous namespace
9038
9041}
9042
9043/// Generate diagnostics for an invalid function redeclaration.
9044///
9045/// This routine handles generating the diagnostic messages for an invalid
9046/// function redeclaration, including finding possible similar declarations
9047/// or performing typo correction if there are no previous declarations with
9048/// the same name.
9049///
9050/// Returns a NamedDecl iff typo correction was performed and substituting in
9051/// the new declaration name does not cause new errors.
9053 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9054 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9055 DeclarationName Name = NewFD->getDeclName();
9056 DeclContext *NewDC = NewFD->getDeclContext();
9057 SmallVector<unsigned, 1> MismatchedParams;
9059 TypoCorrection Correction;
9060 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9061 unsigned DiagMsg =
9062 IsLocalFriend ? diag::err_no_matching_local_friend :
9063 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9064 diag::err_member_decl_does_not_match;
9065 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9066 IsLocalFriend ? Sema::LookupLocalFriendName
9068 RedeclarationKind::ForVisibleRedeclaration);
9069
9070 NewFD->setInvalidDecl();
9071 if (IsLocalFriend)
9072 SemaRef.LookupName(Prev, S);
9073 else
9074 SemaRef.LookupQualifiedName(Prev, NewDC);
9075 assert(!Prev.isAmbiguous() &&
9076 "Cannot have an ambiguity in previous-declaration lookup");
9077 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9078 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9079 MD ? MD->getParent() : nullptr);
9080 if (!Prev.empty()) {
9081 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9082 Func != FuncEnd; ++Func) {
9083 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9084 if (FD &&
9085 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9086 // Add 1 to the index so that 0 can mean the mismatch didn't
9087 // involve a parameter
9088 unsigned ParamNum =
9089 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9090 NearMatches.push_back(std::make_pair(FD, ParamNum));
9091 }
9092 }
9093 // If the qualified name lookup yielded nothing, try typo correction
9094 } else if ((Correction = SemaRef.CorrectTypo(
9095 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9096 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
9097 IsLocalFriend ? nullptr : NewDC))) {
9098 // Set up everything for the call to ActOnFunctionDeclarator
9099 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9100 ExtraArgs.D.getIdentifierLoc());
9101 Previous.clear();
9102 Previous.setLookupName(Correction.getCorrection());
9103 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9104 CDeclEnd = Correction.end();
9105 CDecl != CDeclEnd; ++CDecl) {
9106 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9107 if (FD && !FD->hasBody() &&
9108 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9109 Previous.addDecl(FD);
9110 }
9111 }
9112 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9113
9115 // Retry building the function declaration with the new previous
9116 // declarations, and with errors suppressed.
9117 {
9118 // Trap errors.
9119 Sema::SFINAETrap Trap(SemaRef);
9120
9121 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9122 // pieces need to verify the typo-corrected C++ declaration and hopefully
9123 // eliminate the need for the parameter pack ExtraArgs.
9125 ExtraArgs.S, ExtraArgs.D,
9126 Correction.getCorrectionDecl()->getDeclContext(),
9127 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9128 ExtraArgs.AddToScope);
9129
9130 if (Trap.hasErrorOccurred())
9131 Result = nullptr;
9132 }
9133
9134 if (Result) {
9135 // Determine which correction we picked.
9136 Decl *Canonical = Result->getCanonicalDecl();
9137 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9138 I != E; ++I)
9139 if ((*I)->getCanonicalDecl() == Canonical)
9140 Correction.setCorrectionDecl(*I);
9141
9142 // Let Sema know about the correction.
9144 SemaRef.diagnoseTypo(
9145 Correction,
9146 SemaRef.PDiag(IsLocalFriend
9147 ? diag::err_no_matching_local_friend_suggest
9148 : diag::err_member_decl_does_not_match_suggest)
9149 << Name << NewDC << IsDefinition);
9150 return Result;
9151 }
9152
9153 // Pretend the typo correction never occurred
9154 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9155 ExtraArgs.D.getIdentifierLoc());
9156 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9157 Previous.clear();
9158 Previous.setLookupName(Name);
9159 }
9160
9161 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9162 << Name << NewDC << IsDefinition << NewFD->getLocation();
9163
9164 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9165 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9166 CXXRecordDecl *RD = NewMD->getParent();
9167 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9168 << RD->getName() << RD->getLocation();
9169 }
9170
9171 bool NewFDisConst = NewMD && NewMD->isConst();
9172
9173 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9174 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9175 NearMatch != NearMatchEnd; ++NearMatch) {
9176 FunctionDecl *FD = NearMatch->first;
9177 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9178 bool FDisConst = MD && MD->isConst();
9179 bool IsMember = MD || !IsLocalFriend;
9180
9181 // FIXME: These notes are poorly worded for the local friend case.
9182 if (unsigned Idx = NearMatch->second) {
9183 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9185 if (Loc.isInvalid()) Loc = FD->getLocation();
9186 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9187 : diag::note_local_decl_close_param_match)
9188 << Idx << FDParam->getType()
9189 << NewFD->getParamDecl(Idx - 1)->getType();
9190 } else if (FDisConst != NewFDisConst) {
9191 auto DB = SemaRef.Diag(FD->getLocation(),
9192 diag::note_member_def_close_const_match)
9193 << NewFDisConst << FD->getSourceRange().getEnd();
9194 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9195 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9196 " const");
9197 else if (FTI.hasMethodTypeQualifiers() &&
9198 FTI.getConstQualifierLoc().isValid())
9199 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9200 } else {
9201 SemaRef.Diag(FD->getLocation(),
9202 IsMember ? diag::note_member_def_close_match
9203 : diag::note_local_decl_close_match);
9204 }
9205 }
9206 return nullptr;
9207}
9208
9210 switch (D.getDeclSpec().getStorageClassSpec()) {
9211 default: llvm_unreachable("Unknown storage class!");
9212 case DeclSpec::SCS_auto:
9215 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9216 diag::err_typecheck_sclass_func);
9217 D.getMutableDeclSpec().ClearStorageClassSpecs();
9218 D.setInvalidType();
9219 break;
9220 case DeclSpec::SCS_unspecified: break;
9222 if (D.getDeclSpec().isExternInLinkageSpec())
9223 return SC_None;
9224 return SC_Extern;
9225 case DeclSpec::SCS_static: {
9227 // C99 6.7.1p5:
9228 // The declaration of an identifier for a function that has
9229 // block scope shall have no explicit storage-class specifier
9230 // other than extern
9231 // See also (C++ [dcl.stc]p4).
9232 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9233 diag::err_static_block_func);
9234 break;
9235 } else
9236 return SC_Static;
9237 }
9239 }
9240
9241 // No explicit storage class has already been returned
9242 return SC_None;
9243}
9244
9246 DeclContext *DC, QualType &R,
9247 TypeSourceInfo *TInfo,
9248 StorageClass SC,
9249 bool &IsVirtualOkay) {
9250 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9251 DeclarationName Name = NameInfo.getName();
9252
9253 FunctionDecl *NewFD = nullptr;
9254 bool isInline = D.getDeclSpec().isInlineSpecified();
9255
9256 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9257 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9258 (SemaRef.getLangOpts().C23 &&
9259 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9260
9261 if (SemaRef.getLangOpts().C23)
9262 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9263 diag::err_c23_constexpr_not_variable);
9264 else
9265 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9266 diag::err_constexpr_wrong_decl_kind)
9267 << static_cast<int>(ConstexprKind);
9268 ConstexprKind = ConstexprSpecKind::Unspecified;
9269 D.getMutableDeclSpec().ClearConstexprSpec();
9270 }
9271
9272 if (!SemaRef.getLangOpts().CPlusPlus) {
9273 // Determine whether the function was written with a prototype. This is
9274 // true when:
9275 // - there is a prototype in the declarator, or
9276 // - the type R of the function is some kind of typedef or other non-
9277 // attributed reference to a type name (which eventually refers to a
9278 // function type). Note, we can't always look at the adjusted type to
9279 // check this case because attributes may cause a non-function
9280 // declarator to still have a function type. e.g.,
9281 // typedef void func(int a);
9282 // __attribute__((noreturn)) func other_func; // This has a prototype
9283 bool HasPrototype =
9284 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9285 (D.getDeclSpec().isTypeRep() &&
9286 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9287 ->isFunctionProtoType()) ||
9289 assert(
9290 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9291 "Strict prototypes are required");
9292
9293 NewFD = FunctionDecl::Create(
9294 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9295 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9297 /*TrailingRequiresClause=*/nullptr);
9298 if (D.isInvalidType())
9299 NewFD->setInvalidDecl();
9300
9301 return NewFD;
9302 }
9303
9304 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9305 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9306
9307 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9308
9309 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9310 // This is a C++ constructor declaration.
9311 assert(DC->isRecord() &&
9312 "Constructors can only be declared in a member context");
9313
9314 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9316 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9318 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9319 InheritedConstructor(), TrailingRequiresClause);
9320
9321 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9322 // This is a C++ destructor declaration.
9323 if (DC->isRecord()) {
9324 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9325 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9327 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9328 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9329 /*isImplicitlyDeclared=*/false, ConstexprKind,
9330 TrailingRequiresClause);
9331 // User defined destructors start as not selected if the class definition is still
9332 // not done.
9333 if (Record->isBeingDefined())
9334 NewDD->setIneligibleOrNotSelected(true);
9335
9336 // If the destructor needs an implicit exception specification, set it
9337 // now. FIXME: It'd be nice to be able to create the right type to start
9338 // with, but the type needs to reference the destructor declaration.
9339 if (SemaRef.getLangOpts().CPlusPlus11)
9340 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9341
9342 IsVirtualOkay = true;
9343 return NewDD;
9344
9345 } else {
9346 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9347 D.setInvalidType();
9348
9349 // Create a FunctionDecl to satisfy the function definition parsing
9350 // code path.
9351 return FunctionDecl::Create(
9352 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9353 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9354 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9355 }
9356
9357 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9358 if (!DC->isRecord()) {
9359 SemaRef.Diag(D.getIdentifierLoc(),
9360 diag::err_conv_function_not_member);
9361 return nullptr;
9362 }
9363
9364 SemaRef.CheckConversionDeclarator(D, R, SC);
9365 if (D.isInvalidType())
9366 return nullptr;
9367
9368 IsVirtualOkay = true;
9370 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9371 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9372 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9373 TrailingRequiresClause);
9374
9375 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9376 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9377 return nullptr;
9379 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9380 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9381 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9382 } else if (DC->isRecord()) {
9383 // If the name of the function is the same as the name of the record,
9384 // then this must be an invalid constructor that has a return type.
9385 // (The parser checks for a return type and makes the declarator a
9386 // constructor if it has no return type).
9387 if (Name.getAsIdentifierInfo() &&
9388 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9389 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9390 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9391 << SourceRange(D.getIdentifierLoc());
9392 return nullptr;
9393 }
9394
9395 // This is a C++ method declaration.
9397 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9398 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9399 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9400 IsVirtualOkay = !Ret->isStatic();
9401 return Ret;
9402 } else {
9403 bool isFriend =
9404 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9405 if (!isFriend && SemaRef.CurContext->isRecord())
9406 return nullptr;
9407
9408 // Determine whether the function was written with a
9409 // prototype. This true when:
9410 // - we're in C++ (where every function has a prototype),
9411 return FunctionDecl::Create(
9412 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9413 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9414 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9415 }
9416}
9417
9426
9428 // Size dependent types are just typedefs to normal integer types
9429 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9430 // integers other than by their names.
9431 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9432
9433 // Remove typedefs one by one until we reach a typedef
9434 // for a size dependent type.
9435 QualType DesugaredTy = Ty;
9436 do {
9437 ArrayRef<StringRef> Names(SizeTypeNames);
9438 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9439 if (Names.end() != Match)
9440 return true;
9441
9442 Ty = DesugaredTy;
9443 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9444 } while (DesugaredTy != Ty);
9445
9446 return false;
9447}
9448
9450 if (PT->isDependentType())
9451 return InvalidKernelParam;
9452
9453 if (PT->isPointerOrReferenceType()) {
9454 QualType PointeeType = PT->getPointeeType();
9455 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9456 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9457 PointeeType.getAddressSpace() == LangAS::Default)
9459
9460 if (PointeeType->isPointerType()) {
9461 // This is a pointer to pointer parameter.
9462 // Recursively check inner type.
9463 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9464 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9465 ParamKind == InvalidKernelParam)
9466 return ParamKind;
9467
9468 // OpenCL v3.0 s6.11.a:
9469 // A restriction to pass pointers to pointers only applies to OpenCL C
9470 // v1.2 or below.
9472 return ValidKernelParam;
9473
9474 return PtrPtrKernelParam;
9475 }
9476
9477 // C++ for OpenCL v1.0 s2.4:
9478 // Moreover the types used in parameters of the kernel functions must be:
9479 // Standard layout types for pointer parameters. The same applies to
9480 // reference if an implementation supports them in kernel parameters.
9481 if (S.getLangOpts().OpenCLCPlusPlus &&
9483 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9484 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9485 bool IsStandardLayoutType = true;
9486 if (CXXRec) {
9487 // If template type is not ODR-used its definition is only available
9488 // in the template definition not its instantiation.
9489 // FIXME: This logic doesn't work for types that depend on template
9490 // parameter (PR58590).
9491 if (!CXXRec->hasDefinition())
9492 CXXRec = CXXRec->getTemplateInstantiationPattern();
9493 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9494 IsStandardLayoutType = false;
9495 }
9496 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9497 !IsStandardLayoutType)
9498 return InvalidKernelParam;
9499 }
9500
9501 // OpenCL v1.2 s6.9.p:
9502 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9504 return ValidKernelParam;
9505
9506 return PtrKernelParam;
9507 }
9508
9509 // OpenCL v1.2 s6.9.k:
9510 // Arguments to kernel functions in a program cannot be declared with the
9511 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9512 // uintptr_t or a struct and/or union that contain fields declared to be one
9513 // of these built-in scalar types.
9515 return InvalidKernelParam;
9516
9517 if (PT->isImageType())
9518 return PtrKernelParam;
9519
9520 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9521 return InvalidKernelParam;
9522
9523 // OpenCL extension spec v1.2 s9.5:
9524 // This extension adds support for half scalar and vector types as built-in
9525 // types that can be used for arithmetic operations, conversions etc.
9526 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9527 PT->isHalfType())
9528 return InvalidKernelParam;
9529
9530 // Look into an array argument to check if it has a forbidden type.
9531 if (PT->isArrayType()) {
9532 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9533 // Call ourself to check an underlying type of an array. Since the
9534 // getPointeeOrArrayElementType returns an innermost type which is not an
9535 // array, this recursive call only happens once.
9536 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9537 }
9538
9539 // C++ for OpenCL v1.0 s2.4:
9540 // Moreover the types used in parameters of the kernel functions must be:
9541 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9542 // types) for parameters passed by value;
9543 if (S.getLangOpts().OpenCLCPlusPlus &&
9545 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9546 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9547 return InvalidKernelParam;
9548
9549 if (PT->isRecordType())
9550 return RecordKernelParam;
9551
9552 return ValidKernelParam;
9553}
9554
9556 Sema &S,
9557 Declarator &D,
9558 ParmVarDecl *Param,
9559 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9560 QualType PT = Param->getType();
9561
9562 // Cache the valid types we encounter to avoid rechecking structs that are
9563 // used again
9564 if (ValidTypes.count(PT.getTypePtr()))
9565 return;
9566
9567 switch (getOpenCLKernelParameterType(S, PT)) {
9568 case PtrPtrKernelParam:
9569 // OpenCL v3.0 s6.11.a:
9570 // A kernel function argument cannot be declared as a pointer to a pointer
9571 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9572 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9573 D.setInvalidType();
9574 return;
9575
9577 // OpenCL v1.0 s6.5:
9578 // __kernel function arguments declared to be a pointer of a type can point
9579 // to one of the following address spaces only : __global, __local or
9580 // __constant.
9581 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9582 D.setInvalidType();
9583 return;
9584
9585 // OpenCL v1.2 s6.9.k:
9586 // Arguments to kernel functions in a program cannot be declared with the
9587 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9588 // uintptr_t or a struct and/or union that contain fields declared to be
9589 // one of these built-in scalar types.
9590
9591 case InvalidKernelParam:
9592 // OpenCL v1.2 s6.8 n:
9593 // A kernel function argument cannot be declared
9594 // of event_t type.
9595 // Do not diagnose half type since it is diagnosed as invalid argument
9596 // type for any function elsewhere.
9597 if (!PT->isHalfType()) {
9598 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9599
9600 // Explain what typedefs are involved.
9601 const TypedefType *Typedef = nullptr;
9602 while ((Typedef = PT->getAs<TypedefType>())) {
9603 SourceLocation Loc = Typedef->getDecl()->getLocation();
9604 // SourceLocation may be invalid for a built-in type.
9605 if (Loc.isValid())
9606 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9607 PT = Typedef->desugar();
9608 }
9609 }
9610
9611 D.setInvalidType();
9612 return;
9613
9614 case PtrKernelParam:
9615 case ValidKernelParam:
9616 ValidTypes.insert(PT.getTypePtr());
9617 return;
9618
9619 case RecordKernelParam:
9620 break;
9621 }
9622
9623 // Track nested structs we will inspect
9625
9626 // Track where we are in the nested structs. Items will migrate from
9627 // VisitStack to HistoryStack as we do the DFS for bad field.
9629 HistoryStack.push_back(nullptr);
9630
9631 // At this point we already handled everything except of a RecordType or
9632 // an ArrayType of a RecordType.
9633 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9634 const RecordType *RecTy =
9636 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9637
9638 VisitStack.push_back(RecTy->getDecl());
9639 assert(VisitStack.back() && "First decl null?");
9640
9641 do {
9642 const Decl *Next = VisitStack.pop_back_val();
9643 if (!Next) {
9644 assert(!HistoryStack.empty());
9645 // Found a marker, we have gone up a level
9646 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9647 ValidTypes.insert(Hist->getType().getTypePtr());
9648
9649 continue;
9650 }
9651
9652 // Adds everything except the original parameter declaration (which is not a
9653 // field itself) to the history stack.
9654 const RecordDecl *RD;
9655 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9656 HistoryStack.push_back(Field);
9657
9658 QualType FieldTy = Field->getType();
9659 // Other field types (known to be valid or invalid) are handled while we
9660 // walk around RecordDecl::fields().
9661 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9662 "Unexpected type.");
9663 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9664
9665 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9666 } else {
9667 RD = cast<RecordDecl>(Next);
9668 }
9669
9670 // Add a null marker so we know when we've gone back up a level
9671 VisitStack.push_back(nullptr);
9672
9673 for (const auto *FD : RD->fields()) {
9674 QualType QT = FD->getType();
9675
9676 if (ValidTypes.count(QT.getTypePtr()))
9677 continue;
9678
9680 if (ParamType == ValidKernelParam)
9681 continue;
9682
9683 if (ParamType == RecordKernelParam) {
9684 VisitStack.push_back(FD);
9685 continue;
9686 }
9687
9688 // OpenCL v1.2 s6.9.p:
9689 // Arguments to kernel functions that are declared to be a struct or union
9690 // do not allow OpenCL objects to be passed as elements of the struct or
9691 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9692 // of SVM.
9693 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9694 ParamType == InvalidAddrSpacePtrKernelParam) {
9695 S.Diag(Param->getLocation(),
9696 diag::err_record_with_pointers_kernel_param)
9697 << PT->isUnionType()
9698 << PT;
9699 } else {
9700 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9701 }
9702
9703 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9704 << OrigRecDecl->getDeclName();
9705
9706 // We have an error, now let's go back up through history and show where
9707 // the offending field came from
9709 I = HistoryStack.begin() + 1,
9710 E = HistoryStack.end();
9711 I != E; ++I) {
9712 const FieldDecl *OuterField = *I;
9713 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9714 << OuterField->getType();
9715 }
9716
9717 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9718 << QT->isPointerType()
9719 << QT;
9720 D.setInvalidType();
9721 return;
9722 }
9723 } while (!VisitStack.empty());
9724}
9725
9726/// Find the DeclContext in which a tag is implicitly declared if we see an
9727/// elaborated type specifier in the specified context, and lookup finds
9728/// nothing.
9730 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9731 DC = DC->getParent();
9732 return DC;
9733}
9734
9735/// Find the Scope in which a tag is implicitly declared if we see an
9736/// elaborated type specifier in the specified context, and lookup finds
9737/// nothing.
9738static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9739 while (S->isClassScope() ||
9740 (LangOpts.CPlusPlus &&
9741 S->isFunctionPrototypeScope()) ||
9742 ((S->getFlags() & Scope::DeclScope) == 0) ||
9743 (S->getEntity() && S->getEntity()->isTransparentContext()))
9744 S = S->getParent();
9745 return S;
9746}
9747
9748/// Determine whether a declaration matches a known function in namespace std.
9750 unsigned BuiltinID) {
9751 switch (BuiltinID) {
9752 case Builtin::BI__GetExceptionInfo:
9753 // No type checking whatsoever.
9754 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9755
9756 case Builtin::BIaddressof:
9757 case Builtin::BI__addressof:
9758 case Builtin::BIforward:
9759 case Builtin::BIforward_like:
9760 case Builtin::BImove:
9761 case Builtin::BImove_if_noexcept:
9762 case Builtin::BIas_const: {
9763 // Ensure that we don't treat the algorithm
9764 // OutputIt std::move(InputIt, InputIt, OutputIt)
9765 // as the builtin std::move.
9766 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9767 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9768 }
9769
9770 default:
9771 return false;
9772 }
9773}
9774
9775NamedDecl*
9778 MultiTemplateParamsArg TemplateParamListsRef,
9779 bool &AddToScope) {
9780 QualType R = TInfo->getType();
9781
9782 assert(R->isFunctionType());
9784 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9785
9786 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9787 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9788 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9789 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9790 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9791 TemplateParamLists.back() = Invented;
9792 else
9793 TemplateParamLists.push_back(Invented);
9794 }
9795
9796 // TODO: consider using NameInfo for diagnostic.
9798 DeclarationName Name = NameInfo.getName();
9800
9801 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9802 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9803 diag::err_invalid_thread)
9805
9806 if (D.isFirstDeclarationOfMember())
9808 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9809 D.isCtorOrDtor(), D.getIdentifierLoc());
9810
9811 bool isFriend = false;
9813 bool isMemberSpecialization = false;
9814 bool isFunctionTemplateSpecialization = false;
9815
9816 bool HasExplicitTemplateArgs = false;
9817 TemplateArgumentListInfo TemplateArgs;
9818
9819 bool isVirtualOkay = false;
9820
9821 DeclContext *OriginalDC = DC;
9822 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9823
9824 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9825 isVirtualOkay);
9826 if (!NewFD) return nullptr;
9827
9830
9831 // Set the lexical context. If this is a function-scope declaration, or has a
9832 // C++ scope specifier, or is the object of a friend declaration, the lexical
9833 // context will be different from the semantic context.
9835
9836 if (IsLocalExternDecl)
9837 NewFD->setLocalExternDecl();
9838
9839 if (getLangOpts().CPlusPlus) {
9840 // The rules for implicit inlines changed in C++20 for methods and friends
9841 // with an in-class definition (when such a definition is not attached to
9842 // the global module). This does not affect declarations that are already
9843 // inline (whether explicitly or implicitly by being declared constexpr,
9844 // consteval, etc).
9845 // FIXME: We need a better way to separate C++ standard and clang modules.
9846 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9847 !NewFD->getOwningModule() ||
9848 NewFD->isFromGlobalModule() ||
9850 bool isInline = D.getDeclSpec().isInlineSpecified();
9851 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9852 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9853 isFriend = D.getDeclSpec().isFriendSpecified();
9854 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
9855 // Pre-C++20 [class.friend]p5
9856 // A function can be defined in a friend declaration of a
9857 // class . . . . Such a function is implicitly inline.
9858 // Post C++20 [class.friend]p7
9859 // Such a function is implicitly an inline function if it is attached
9860 // to the global module.
9861 NewFD->setImplicitlyInline();
9862 }
9863
9864 // If this is a method defined in an __interface, and is not a constructor
9865 // or an overloaded operator, then set the pure flag (isVirtual will already
9866 // return true).
9867 if (const CXXRecordDecl *Parent =
9868 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9869 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9870 NewFD->setIsPureVirtual(true);
9871
9872 // C++ [class.union]p2
9873 // A union can have member functions, but not virtual functions.
9874 if (isVirtual && Parent->isUnion()) {
9875 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9876 NewFD->setInvalidDecl();
9877 }
9878 if ((Parent->isClass() || Parent->isStruct()) &&
9879 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9880 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9881 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9882 if (auto *Def = Parent->getDefinition())
9883 Def->setInitMethod(true);
9884 }
9885 }
9886
9887 SetNestedNameSpecifier(*this, NewFD, D);
9888 isMemberSpecialization = false;
9889 isFunctionTemplateSpecialization = false;
9890 if (D.isInvalidType())
9891 NewFD->setInvalidDecl();
9892
9893 // Match up the template parameter lists with the scope specifier, then
9894 // determine whether we have a template or a template specialization.
9895 bool Invalid = false;
9896 TemplateIdAnnotation *TemplateId =
9898 ? D.getName().TemplateId
9899 : nullptr;
9900 TemplateParameterList *TemplateParams =
9902 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9903 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9904 isMemberSpecialization, Invalid);
9905 if (TemplateParams) {
9906 // Check that we can declare a template here.
9907 if (CheckTemplateDeclScope(S, TemplateParams))
9908 NewFD->setInvalidDecl();
9909
9910 if (TemplateParams->size() > 0) {
9911 // This is a function template
9912
9913 // A destructor cannot be a template.
9914 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9915 Diag(NewFD->getLocation(), diag::err_destructor_template);
9916 NewFD->setInvalidDecl();
9917 // Function template with explicit template arguments.
9918 } else if (TemplateId) {
9919 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9920 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9921 NewFD->setInvalidDecl();
9922 }
9923
9924 // If we're adding a template to a dependent context, we may need to
9925 // rebuilding some of the types used within the template parameter list,
9926 // now that we know what the current instantiation is.
9927 if (DC->isDependentContext()) {
9928 ContextRAII SavedContext(*this, DC);
9930 Invalid = true;
9931 }
9932
9934 NewFD->getLocation(),
9935 Name, TemplateParams,
9936 NewFD);
9937 FunctionTemplate->setLexicalDeclContext(CurContext);
9939
9940 // For source fidelity, store the other template param lists.
9941 if (TemplateParamLists.size() > 1) {
9943 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9944 .drop_back(1));
9945 }
9946 } else {
9947 // This is a function template specialization.
9948 isFunctionTemplateSpecialization = true;
9949 // For source fidelity, store all the template param lists.
9950 if (TemplateParamLists.size() > 0)
9951 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9952
9953 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9954 if (isFriend) {
9955 // We want to remove the "template<>", found here.
9956 SourceRange RemoveRange = TemplateParams->getSourceRange();
9957
9958 // If we remove the template<> and the name is not a
9959 // template-id, we're actually silently creating a problem:
9960 // the friend declaration will refer to an untemplated decl,
9961 // and clearly the user wants a template specialization. So
9962 // we need to insert '<>' after the name.
9963 SourceLocation InsertLoc;
9964 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9965 InsertLoc = D.getName().getSourceRange().getEnd();
9966 InsertLoc = getLocForEndOfToken(InsertLoc);
9967 }
9968
9969 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9970 << Name << RemoveRange
9971 << FixItHint::CreateRemoval(RemoveRange)
9972 << FixItHint::CreateInsertion(InsertLoc, "<>");
9973 Invalid = true;
9974
9975 // Recover by faking up an empty template argument list.
9976 HasExplicitTemplateArgs = true;
9977 TemplateArgs.setLAngleLoc(InsertLoc);
9978 TemplateArgs.setRAngleLoc(InsertLoc);
9979 }
9980 }
9981 } else {
9982 // Check that we can declare a template here.
9983 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9984 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9985 NewFD->setInvalidDecl();
9986
9987 // All template param lists were matched against the scope specifier:
9988 // this is NOT (an explicit specialization of) a template.
9989 if (TemplateParamLists.size() > 0)
9990 // For source fidelity, store all the template param lists.
9991 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9992
9993 // "friend void foo<>(int);" is an implicit specialization decl.
9994 if (isFriend && TemplateId)
9995 isFunctionTemplateSpecialization = true;
9996 }
9997
9998 // If this is a function template specialization and the unqualified-id of
9999 // the declarator-id is a template-id, convert the template argument list
10000 // into our AST format and check for unexpanded packs.
10001 if (isFunctionTemplateSpecialization && TemplateId) {
10002 HasExplicitTemplateArgs = true;
10003
10004 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10005 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10006 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10007 TemplateId->NumArgs);
10008 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10009
10010 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10011 // declaration of a function template partial specialization? Should we
10012 // consider the unexpanded pack context to be a partial specialization?
10013 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10015 ArgLoc, isFriend ? UPPC_FriendDeclaration
10017 NewFD->setInvalidDecl();
10018 }
10019 }
10020
10021 if (Invalid) {
10022 NewFD->setInvalidDecl();
10023 if (FunctionTemplate)
10024 FunctionTemplate->setInvalidDecl();
10025 }
10026
10027 // C++ [dcl.fct.spec]p5:
10028 // The virtual specifier shall only be used in declarations of
10029 // nonstatic class member functions that appear within a
10030 // member-specification of a class declaration; see 10.3.
10031 //
10032 if (isVirtual && !NewFD->isInvalidDecl()) {
10033 if (!isVirtualOkay) {
10034 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10035 diag::err_virtual_non_function);
10036 } else if (!CurContext->isRecord()) {
10037 // 'virtual' was specified outside of the class.
10038 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10039 diag::err_virtual_out_of_class)
10040 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10041 } else if (NewFD->getDescribedFunctionTemplate()) {
10042 // C++ [temp.mem]p3:
10043 // A member function template shall not be virtual.
10044 Diag(D.getDeclSpec().getVirtualSpecLoc(),
10045 diag::err_virtual_member_function_template)
10046 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
10047 } else {
10048 // Okay: Add virtual to the method.
10049 NewFD->setVirtualAsWritten(true);
10050 }
10051
10052 if (getLangOpts().CPlusPlus14 &&
10053 NewFD->getReturnType()->isUndeducedType())
10054 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10055 }
10056
10057 // C++ [dcl.fct.spec]p3:
10058 // The inline specifier shall not appear on a block scope function
10059 // declaration.
10060 if (isInline && !NewFD->isInvalidDecl()) {
10062 // 'inline' is not allowed on block scope function declaration.
10063 Diag(D.getDeclSpec().getInlineSpecLoc(),
10064 diag::err_inline_declaration_block_scope) << Name
10065 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10066 }
10067 }
10068
10069 // C++ [dcl.fct.spec]p6:
10070 // The explicit specifier shall be used only in the declaration of a
10071 // constructor or conversion function within its class definition;
10072 // see 12.3.1 and 12.3.2.
10073 if (hasExplicit && !NewFD->isInvalidDecl() &&
10074 !isa<CXXDeductionGuideDecl>(NewFD)) {
10075 if (!CurContext->isRecord()) {
10076 // 'explicit' was specified outside of the class.
10077 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10078 diag::err_explicit_out_of_class)
10079 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10080 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10081 !isa<CXXConversionDecl>(NewFD)) {
10082 // 'explicit' was specified on a function that wasn't a constructor
10083 // or conversion function.
10084 Diag(D.getDeclSpec().getExplicitSpecLoc(),
10085 diag::err_explicit_non_ctor_or_conv_function)
10086 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
10087 }
10088 }
10089
10090 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
10091 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10092 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10093 // are implicitly inline.
10094 NewFD->setImplicitlyInline();
10095
10096 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10097 // be either constructors or to return a literal type. Therefore,
10098 // destructors cannot be declared constexpr.
10099 if (isa<CXXDestructorDecl>(NewFD) &&
10101 ConstexprKind == ConstexprSpecKind::Consteval)) {
10102 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10103 << static_cast<int>(ConstexprKind);
10104 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
10107 }
10108 // C++20 [dcl.constexpr]p2: An allocation function, or a
10109 // deallocation function shall not be declared with the consteval
10110 // specifier.
10111 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10112 (NewFD->getOverloadedOperator() == OO_New ||
10113 NewFD->getOverloadedOperator() == OO_Array_New ||
10114 NewFD->getOverloadedOperator() == OO_Delete ||
10115 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
10116 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10117 diag::err_invalid_consteval_decl_kind)
10118 << NewFD;
10120 }
10121 }
10122
10123 // If __module_private__ was specified, mark the function accordingly.
10124 if (D.getDeclSpec().isModulePrivateSpecified()) {
10125 if (isFunctionTemplateSpecialization) {
10126 SourceLocation ModulePrivateLoc
10127 = D.getDeclSpec().getModulePrivateSpecLoc();
10128 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10129 << 0
10130 << FixItHint::CreateRemoval(ModulePrivateLoc);
10131 } else {
10132 NewFD->setModulePrivate();
10133 if (FunctionTemplate)
10134 FunctionTemplate->setModulePrivate();
10135 }
10136 }
10137
10138 if (isFriend) {
10139 if (FunctionTemplate) {
10140 FunctionTemplate->setObjectOfFriendDecl();
10141 FunctionTemplate->setAccess(AS_public);
10142 }
10143 NewFD->setObjectOfFriendDecl();
10144 NewFD->setAccess(AS_public);
10145 }
10146
10147 // If a function is defined as defaulted or deleted, mark it as such now.
10148 // We'll do the relevant checks on defaulted / deleted functions later.
10149 switch (D.getFunctionDefinitionKind()) {
10152 break;
10153
10155 NewFD->setDefaulted();
10156 break;
10157
10159 NewFD->setDeletedAsWritten();
10160 break;
10161 }
10162
10163 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10164 D.isFunctionDefinition()) {
10165 // Pre C++20 [class.mfct]p2:
10166 // A member function may be defined (8.4) in its class definition, in
10167 // which case it is an inline member function (7.1.2)
10168 // Post C++20 [class.mfct]p1:
10169 // If a member function is attached to the global module and is defined
10170 // in its class definition, it is inline.
10171 NewFD->setImplicitlyInline();
10172 }
10173
10174 if (!isFriend && SC != SC_None) {
10175 // C++ [temp.expl.spec]p2:
10176 // The declaration in an explicit-specialization shall not be an
10177 // export-declaration. An explicit specialization shall not use a
10178 // storage-class-specifier other than thread_local.
10179 //
10180 // We diagnose friend declarations with storage-class-specifiers
10181 // elsewhere.
10182 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10183 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10184 diag::ext_explicit_specialization_storage_class)
10186 D.getDeclSpec().getStorageClassSpecLoc());
10187 }
10188
10189 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10190 assert(isa<CXXMethodDecl>(NewFD) &&
10191 "Out-of-line member function should be a CXXMethodDecl");
10192 // C++ [class.static]p1:
10193 // A data or function member of a class may be declared static
10194 // in a class definition, in which case it is a static member of
10195 // the class.
10196
10197 // Complain about the 'static' specifier if it's on an out-of-line
10198 // member function definition.
10199
10200 // MSVC permits the use of a 'static' storage specifier on an
10201 // out-of-line member function template declaration and class member
10202 // template declaration (MSVC versions before 2015), warn about this.
10203 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10204 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10205 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10206 (getLangOpts().MSVCCompat &&
10208 ? diag::ext_static_out_of_line
10209 : diag::err_static_out_of_line)
10211 D.getDeclSpec().getStorageClassSpecLoc());
10212 }
10213 }
10214
10215 // C++11 [except.spec]p15:
10216 // A deallocation function with no exception-specification is treated
10217 // as if it were specified with noexcept(true).
10218 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10219 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10220 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10221 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10223 FPT->getReturnType(), FPT->getParamTypes(),
10225
10226 // C++20 [dcl.inline]/7
10227 // If an inline function or variable that is attached to a named module
10228 // is declared in a definition domain, it shall be defined in that
10229 // domain.
10230 // So, if the current declaration does not have a definition, we must
10231 // check at the end of the TU (or when the PMF starts) to see that we
10232 // have a definition at that point.
10233 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10234 NewFD->isInNamedModule()) {
10235 PendingInlineFuncDecls.insert(NewFD);
10236 }
10237 }
10238
10239 // Filter out previous declarations that don't match the scope.
10241 D.getCXXScopeSpec().isNotEmpty() ||
10242 isMemberSpecialization ||
10243 isFunctionTemplateSpecialization);
10244
10245 // Handle GNU asm-label extension (encoded as an attribute).
10246 if (Expr *E = (Expr*) D.getAsmLabel()) {
10247 // The parser guarantees this is a string.
10248 StringLiteral *SE = cast<StringLiteral>(E);
10249 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10250 /*IsLiteralLabel=*/true,
10251 SE->getStrTokenLoc(0)));
10252 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10253 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10255 if (I != ExtnameUndeclaredIdentifiers.end()) {
10256 if (isDeclExternC(NewFD)) {
10257 NewFD->addAttr(I->second);
10259 } else
10260 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10261 << /*Variable*/0 << NewFD;
10262 }
10263 }
10264
10265 // Copy the parameter declarations from the declarator D to the function
10266 // declaration NewFD, if they are available. First scavenge them into Params.
10268 unsigned FTIIdx;
10269 if (D.isFunctionDeclarator(FTIIdx)) {
10270 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10271
10272 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10273 // function that takes no arguments, not a function that takes a
10274 // single void argument.
10275 // We let through "const void" here because Sema::GetTypeForDeclarator
10276 // already checks for that case.
10277 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10278 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10279 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10280 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10281 Param->setDeclContext(NewFD);
10282 Params.push_back(Param);
10283
10284 if (Param->isInvalidDecl())
10285 NewFD->setInvalidDecl();
10286 }
10287 }
10288
10289 if (!getLangOpts().CPlusPlus) {
10290 // In C, find all the tag declarations from the prototype and move them
10291 // into the function DeclContext. Remove them from the surrounding tag
10292 // injection context of the function, which is typically but not always
10293 // the TU.
10294 DeclContext *PrototypeTagContext =
10296 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10297 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10298
10299 // We don't want to reparent enumerators. Look at their parent enum
10300 // instead.
10301 if (!TD) {
10302 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10303 TD = cast<EnumDecl>(ECD->getDeclContext());
10304 }
10305 if (!TD)
10306 continue;
10307 DeclContext *TagDC = TD->getLexicalDeclContext();
10308 if (!TagDC->containsDecl(TD))
10309 continue;
10310 TagDC->removeDecl(TD);
10311 TD->setDeclContext(NewFD);
10312 NewFD->addDecl(TD);
10313
10314 // Preserve the lexical DeclContext if it is not the surrounding tag
10315 // injection context of the FD. In this example, the semantic context of
10316 // E will be f and the lexical context will be S, while both the
10317 // semantic and lexical contexts of S will be f:
10318 // void f(struct S { enum E { a } f; } s);
10319 if (TagDC != PrototypeTagContext)
10320 TD->setLexicalDeclContext(TagDC);
10321 }
10322 }
10323 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10324 // When we're declaring a function with a typedef, typeof, etc as in the
10325 // following example, we'll need to synthesize (unnamed)
10326 // parameters for use in the declaration.
10327 //
10328 // @code
10329 // typedef void fn(int);
10330 // fn f;
10331 // @endcode
10332
10333 // Synthesize a parameter for each argument type.
10334 for (const auto &AI : FT->param_types()) {
10335 ParmVarDecl *Param =
10336 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10337 Param->setScopeInfo(0, Params.size());
10338 Params.push_back(Param);
10339 }
10340 } else {
10341 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10342 "Should not need args for typedef of non-prototype fn");
10343 }
10344
10345 // Finally, we know we have the right number of parameters, install them.
10346 NewFD->setParams(Params);
10347
10348 if (D.getDeclSpec().isNoreturnSpecified())
10349 NewFD->addAttr(
10350 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10351
10352 // Functions returning a variably modified type violate C99 6.7.5.2p2
10353 // because all functions have linkage.
10354 if (!NewFD->isInvalidDecl() &&
10356 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10357 NewFD->setInvalidDecl();
10358 }
10359
10360 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10361 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10362 !NewFD->hasAttr<SectionAttr>())
10363 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10366
10367 // Apply an implicit SectionAttr if #pragma code_seg is active.
10368 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10369 !NewFD->hasAttr<SectionAttr>()) {
10370 NewFD->addAttr(SectionAttr::CreateImplicit(
10371 Context, CodeSegStack.CurrentValue->getString(),
10372 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10373 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10376 NewFD))
10377 NewFD->dropAttr<SectionAttr>();
10378 }
10379
10380 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10381 // active.
10382 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10383 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10384 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10386
10387 // Apply an implicit CodeSegAttr from class declspec or
10388 // apply an implicit SectionAttr from #pragma code_seg if active.
10389 if (!NewFD->hasAttr<CodeSegAttr>()) {
10391 D.isFunctionDefinition())) {
10392 NewFD->addAttr(SAttr);
10393 }
10394 }
10395
10396 // Handle attributes.
10397 ProcessDeclAttributes(S, NewFD, D);
10398 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10399 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10400 !NewTVA->isDefaultVersion() &&
10401 !Context.getTargetInfo().hasFeature("fmv")) {
10402 // Don't add to scope fmv functions declarations if fmv disabled
10403 AddToScope = false;
10404 return NewFD;
10405 }
10406
10407 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10408 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10409 // type.
10410 //
10411 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10412 // type declaration will generate a compilation error.
10413 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10414 if (AddressSpace != LangAS::Default) {
10415 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10416 NewFD->setInvalidDecl();
10417 }
10418 }
10419
10420 if (!getLangOpts().CPlusPlus) {
10421 // Perform semantic checking on the function declaration.
10422 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10423 CheckMain(NewFD, D.getDeclSpec());
10424
10425 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10426 CheckMSVCRTEntryPoint(NewFD);
10427
10428 if (!NewFD->isInvalidDecl())
10429 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10430 isMemberSpecialization,
10431 D.isFunctionDefinition()));
10432 else if (!Previous.empty())
10433 // Recover gracefully from an invalid redeclaration.
10434 D.setRedeclaration(true);
10435 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10436 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10437 "previous declaration set still overloaded");
10438
10439 // Diagnose no-prototype function declarations with calling conventions that
10440 // don't support variadic calls. Only do this in C and do it after merging
10441 // possibly prototyped redeclarations.
10442 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10443 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10444 CallingConv CC = FT->getExtInfo().getCC();
10445 if (!supportsVariadicCall(CC)) {
10446 // Windows system headers sometimes accidentally use stdcall without
10447 // (void) parameters, so we relax this to a warning.
10448 int DiagID =
10449 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10450 Diag(NewFD->getLocation(), DiagID)
10452 }
10453 }
10454
10460 } else {
10461 // C++11 [replacement.functions]p3:
10462 // The program's definitions shall not be specified as inline.
10463 //
10464 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10465 //
10466 // Suppress the diagnostic if the function is __attribute__((used)), since
10467 // that forces an external definition to be emitted.
10468 if (D.getDeclSpec().isInlineSpecified() &&
10470 !NewFD->hasAttr<UsedAttr>())
10471 Diag(D.getDeclSpec().getInlineSpecLoc(),
10472 diag::ext_operator_new_delete_declared_inline)
10473 << NewFD->getDeclName();
10474
10475 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10476 // C++20 [dcl.decl.general]p4:
10477 // The optional requires-clause in an init-declarator or
10478 // member-declarator shall be present only if the declarator declares a
10479 // templated function.
10480 //
10481 // C++20 [temp.pre]p8:
10482 // An entity is templated if it is
10483 // - a template,
10484 // - an entity defined or created in a templated entity,
10485 // - a member of a templated entity,
10486 // - an enumerator for an enumeration that is a templated entity, or
10487 // - the closure type of a lambda-expression appearing in the
10488 // declaration of a templated entity.
10489 //
10490 // [Note 6: A local class, a local or block variable, or a friend
10491 // function defined in a templated entity is a templated entity.
10492 // — end note]
10493 //
10494 // A templated function is a function template or a function that is
10495 // templated. A templated class is a class template or a class that is
10496 // templated. A templated variable is a variable template or a variable
10497 // that is templated.
10498 if (!FunctionTemplate) {
10499 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10500 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10501 // An explicit specialization shall not have a trailing
10502 // requires-clause unless it declares a function template.
10503 //
10504 // Since a friend function template specialization cannot be
10505 // definition, and since a non-template friend declaration with a
10506 // trailing requires-clause must be a definition, we diagnose
10507 // friend function template specializations with trailing
10508 // requires-clauses on the same path as explicit specializations
10509 // even though they aren't necessarily prohibited by the same
10510 // language rule.
10511 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10512 << isFriend;
10513 } else if (isFriend && NewFD->isTemplated() &&
10514 !D.isFunctionDefinition()) {
10515 // C++ [temp.friend]p9:
10516 // A non-template friend declaration with a requires-clause shall be
10517 // a definition.
10518 Diag(NewFD->getBeginLoc(),
10519 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10520 NewFD->setInvalidDecl();
10521 } else if (!NewFD->isTemplated() ||
10522 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10523 Diag(TRC->getBeginLoc(),
10524 diag::err_constrained_non_templated_function);
10525 }
10526 }
10527 }
10528
10529 // We do not add HD attributes to specializations here because
10530 // they may have different constexpr-ness compared to their
10531 // templates and, after maybeAddHostDeviceAttrs() is applied,
10532 // may end up with different effective targets. Instead, a
10533 // specialization inherits its target attributes from its template
10534 // in the CheckFunctionTemplateSpecialization() call below.
10535 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10537
10538 // Handle explicit specializations of function templates
10539 // and friend function declarations with an explicit
10540 // template argument list.
10541 if (isFunctionTemplateSpecialization) {
10542 bool isDependentSpecialization = false;
10543 if (isFriend) {
10544 // For friend function specializations, this is a dependent
10545 // specialization if its semantic context is dependent, its
10546 // type is dependent, or if its template-id is dependent.
10547 isDependentSpecialization =
10548 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10549 (HasExplicitTemplateArgs &&
10552 TemplateArgs.arguments()));
10553 assert((!isDependentSpecialization ||
10554 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10555 "dependent friend function specialization without template "
10556 "args");
10557 } else {
10558 // For class-scope explicit specializations of function templates,
10559 // if the lexical context is dependent, then the specialization
10560 // is dependent.
10561 isDependentSpecialization =
10563 }
10564
10565 TemplateArgumentListInfo *ExplicitTemplateArgs =
10566 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10567 if (isDependentSpecialization) {
10568 // If it's a dependent specialization, it may not be possible
10569 // to determine the primary template (for explicit specializations)
10570 // or befriended declaration (for friends) until the enclosing
10571 // template is instantiated. In such cases, we store the declarations
10572 // found by name lookup and defer resolution until instantiation.
10574 NewFD, ExplicitTemplateArgs, Previous))
10575 NewFD->setInvalidDecl();
10576 } else if (!NewFD->isInvalidDecl()) {
10577 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10578 Previous))
10579 NewFD->setInvalidDecl();
10580 }
10581 } else if (isMemberSpecialization && !FunctionTemplate) {
10583 NewFD->setInvalidDecl();
10584 }
10585
10586 // Perform semantic checking on the function declaration.
10587 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10588 CheckMain(NewFD, D.getDeclSpec());
10589
10590 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10591 CheckMSVCRTEntryPoint(NewFD);
10592
10593 if (!NewFD->isInvalidDecl())
10594 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10595 isMemberSpecialization,
10596 D.isFunctionDefinition()));
10597 else if (!Previous.empty())
10598 // Recover gracefully from an invalid redeclaration.
10599 D.setRedeclaration(true);
10600
10601 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10602 !D.isRedeclaration() ||
10603 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10604 "previous declaration set still overloaded");
10605
10606 NamedDecl *PrincipalDecl = (FunctionTemplate
10607 ? cast<NamedDecl>(FunctionTemplate)
10608 : NewFD);
10609
10610 if (isFriend && NewFD->getPreviousDecl()) {
10611 AccessSpecifier Access = AS_public;
10612 if (!NewFD->isInvalidDecl())
10613 Access = NewFD->getPreviousDecl()->getAccess();
10614
10615 NewFD->setAccess(Access);
10616 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10617 }
10618
10619 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10621 PrincipalDecl->setNonMemberOperator();
10622
10623 // If we have a function template, check the template parameter
10624 // list. This will check and merge default template arguments.
10625 if (FunctionTemplate) {
10626 FunctionTemplateDecl *PrevTemplate =
10627 FunctionTemplate->getPreviousDecl();
10628 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10629 PrevTemplate ? PrevTemplate->getTemplateParameters()
10630 : nullptr,
10631 D.getDeclSpec().isFriendSpecified()
10632 ? (D.isFunctionDefinition()
10635 : (D.getCXXScopeSpec().isSet() &&
10636 DC && DC->isRecord() &&
10637 DC->isDependentContext())
10640 }
10641
10642 if (NewFD->isInvalidDecl()) {
10643 // Ignore all the rest of this.
10644 } else if (!D.isRedeclaration()) {
10645 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10646 AddToScope };
10647 // Fake up an access specifier if it's supposed to be a class member.
10648 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10649 NewFD->setAccess(AS_public);
10650
10651 // Qualified decls generally require a previous declaration.
10652 if (D.getCXXScopeSpec().isSet()) {
10653 // ...with the major exception of templated-scope or
10654 // dependent-scope friend declarations.
10655
10656 // TODO: we currently also suppress this check in dependent
10657 // contexts because (1) the parameter depth will be off when
10658 // matching friend templates and (2) we might actually be
10659 // selecting a friend based on a dependent factor. But there
10660 // are situations where these conditions don't apply and we
10661 // can actually do this check immediately.
10662 //
10663 // Unless the scope is dependent, it's always an error if qualified
10664 // redeclaration lookup found nothing at all. Diagnose that now;
10665 // nothing will diagnose that error later.
10666 if (isFriend &&
10667 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10668 (!Previous.empty() && CurContext->isDependentContext()))) {
10669 // ignore these
10670 } else if (NewFD->isCPUDispatchMultiVersion() ||
10671 NewFD->isCPUSpecificMultiVersion()) {
10672 // ignore this, we allow the redeclaration behavior here to create new
10673 // versions of the function.
10674 } else {
10675 // The user tried to provide an out-of-line definition for a
10676 // function that is a member of a class or namespace, but there
10677 // was no such member function declared (C++ [class.mfct]p2,
10678 // C++ [namespace.memdef]p2). For example:
10679 //
10680 // class X {
10681 // void f() const;
10682 // };
10683 //
10684 // void X::f() { } // ill-formed
10685 //
10686 // Complain about this problem, and attempt to suggest close
10687 // matches (e.g., those that differ only in cv-qualifiers and
10688 // whether the parameter types are references).
10689
10691 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10692 AddToScope = ExtraArgs.AddToScope;
10693 return Result;
10694 }
10695 }
10696
10697 // Unqualified local friend declarations are required to resolve
10698 // to something.
10699 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10701 *this, Previous, NewFD, ExtraArgs, true, S)) {
10702 AddToScope = ExtraArgs.AddToScope;
10703 return Result;
10704 }
10705 }
10706 } else if (!D.isFunctionDefinition() &&
10707 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10708 !isFriend && !isFunctionTemplateSpecialization &&
10709 !isMemberSpecialization) {
10710 // An out-of-line member function declaration must also be a
10711 // definition (C++ [class.mfct]p2).
10712 // Note that this is not the case for explicit specializations of
10713 // function templates or member functions of class templates, per
10714 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10715 // extension for compatibility with old SWIG code which likes to
10716 // generate them.
10717 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10718 << D.getCXXScopeSpec().getRange();
10719 }
10720 }
10721
10722 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10723 // Any top level function could potentially be specified as an entry.
10724 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10725 HLSL().ActOnTopLevelFunction(NewFD);
10726
10727 if (NewFD->hasAttr<HLSLShaderAttr>())
10728 HLSL().CheckEntryPoint(NewFD);
10729 }
10730
10731 // If this is the first declaration of a library builtin function, add
10732 // attributes as appropriate.
10733 if (!D.isRedeclaration()) {
10734 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10735 if (unsigned BuiltinID = II->getBuiltinID()) {
10736 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10737 if (!InStdNamespace &&
10739 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10740 // Validate the type matches unless this builtin is specified as
10741 // matching regardless of its declared type.
10742 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10743 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10744 } else {
10746 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10747 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10748
10749 if (!Error && !BuiltinType.isNull() &&
10751 NewFD->getType(), BuiltinType))
10752 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10753 }
10754 }
10755 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10756 isStdBuiltin(Context, NewFD, BuiltinID)) {
10757 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10758 }
10759 }
10760 }
10761 }
10762
10763 ProcessPragmaWeak(S, NewFD);
10764 checkAttributesAfterMerging(*this, *NewFD);
10765
10767
10768 if (NewFD->hasAttr<OverloadableAttr>() &&
10769 !NewFD->getType()->getAs<FunctionProtoType>()) {
10770 Diag(NewFD->getLocation(),
10771 diag::err_attribute_overloadable_no_prototype)
10772 << NewFD;
10773 NewFD->dropAttr<OverloadableAttr>();
10774 }
10775
10776 // If there's a #pragma GCC visibility in scope, and this isn't a class
10777 // member, set the visibility of this function.
10778 if (!DC->isRecord() && NewFD->isExternallyVisible())
10780
10781 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10782 // marking the function.
10783 ObjC().AddCFAuditedAttribute(NewFD);
10784
10785 // If this is a function definition, check if we have to apply any
10786 // attributes (i.e. optnone and no_builtin) due to a pragma.
10787 if (D.isFunctionDefinition()) {
10788 AddRangeBasedOptnone(NewFD);
10790 AddSectionMSAllocText(NewFD);
10792 }
10793
10794 // If this is the first declaration of an extern C variable, update
10795 // the map of such variables.
10796 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10797 isIncompleteDeclExternC(*this, NewFD))
10799
10800 // Set this FunctionDecl's range up to the right paren.
10801 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10802
10803 if (D.isRedeclaration() && !Previous.empty()) {
10804 NamedDecl *Prev = Previous.getRepresentativeDecl();
10805 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10806 isMemberSpecialization ||
10807 isFunctionTemplateSpecialization,
10808 D.isFunctionDefinition());
10809 }
10810
10811 if (getLangOpts().CUDA) {
10812 IdentifierInfo *II = NewFD->getIdentifier();
10813 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10814 !NewFD->isInvalidDecl() &&
10817 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10820 }
10821
10822 // Variadic functions, other than a *declaration* of printf, are not allowed
10823 // in device-side CUDA code, unless someone passed
10824 // -fcuda-allow-variadic-functions.
10825 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10826 (NewFD->hasAttr<CUDADeviceAttr>() ||
10827 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10828 !(II && II->isStr("printf") && NewFD->isExternC() &&
10829 !D.isFunctionDefinition())) {
10830 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10831 }
10832 }
10833
10835
10836
10837
10838 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10839 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10840 if (SC == SC_Static) {
10841 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10842 D.setInvalidType();
10843 }
10844
10845 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10846 if (!NewFD->getReturnType()->isVoidType()) {
10847 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10848 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10849 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10850 : FixItHint());
10851 D.setInvalidType();
10852 }
10853
10855 for (auto *Param : NewFD->parameters())
10856 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10857
10858 if (getLangOpts().OpenCLCPlusPlus) {
10859 if (DC->isRecord()) {
10860 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10861 D.setInvalidType();
10862 }
10863 if (FunctionTemplate) {
10864 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10865 D.setInvalidType();
10866 }
10867 }
10868 }
10869
10870 if (getLangOpts().CPlusPlus) {
10871 // Precalculate whether this is a friend function template with a constraint
10872 // that depends on an enclosing template, per [temp.friend]p9.
10873 if (isFriend && FunctionTemplate &&
10876
10877 // C++ [temp.friend]p9:
10878 // A friend function template with a constraint that depends on a
10879 // template parameter from an enclosing template shall be a definition.
10880 if (!D.isFunctionDefinition()) {
10881 Diag(NewFD->getBeginLoc(),
10882 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10883 NewFD->setInvalidDecl();
10884 }
10885 }
10886
10887 if (FunctionTemplate) {
10888 if (NewFD->isInvalidDecl())
10889 FunctionTemplate->setInvalidDecl();
10890 return FunctionTemplate;
10891 }
10892
10893 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10895 }
10896
10897 for (const ParmVarDecl *Param : NewFD->parameters()) {
10898 QualType PT = Param->getType();
10899
10900 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10901 // types.
10902 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10903 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10904 QualType ElemTy = PipeTy->getElementType();
10905 if (ElemTy->isPointerOrReferenceType()) {
10906 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
10907 D.setInvalidType();
10908 }
10909 }
10910 }
10911 // WebAssembly tables can't be used as function parameters.
10912 if (Context.getTargetInfo().getTriple().isWasm()) {
10914 Diag(Param->getTypeSpecStartLoc(),
10915 diag::err_wasm_table_as_function_parameter);
10916 D.setInvalidType();
10917 }
10918 }
10919 }
10920
10921 // Diagnose availability attributes. Availability cannot be used on functions
10922 // that are run during load/unload.
10923 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10924 if (NewFD->hasAttr<ConstructorAttr>()) {
10925 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10926 << 1;
10927 NewFD->dropAttr<AvailabilityAttr>();
10928 }
10929 if (NewFD->hasAttr<DestructorAttr>()) {
10930 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10931 << 2;
10932 NewFD->dropAttr<AvailabilityAttr>();
10933 }
10934 }
10935
10936 // Diagnose no_builtin attribute on function declaration that are not a
10937 // definition.
10938 // FIXME: We should really be doing this in
10939 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10940 // the FunctionDecl and at this point of the code
10941 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10942 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10943 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10944 switch (D.getFunctionDefinitionKind()) {
10947 Diag(NBA->getLocation(),
10948 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10949 << NBA->getSpelling();
10950 break;
10952 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10953 << NBA->getSpelling();
10954 break;
10956 break;
10957 }
10958
10959 // Similar to no_builtin logic above, at this point of the code
10960 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
10961 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10963 !NewFD->isInvalidDecl() &&
10964 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
10965 ExternalDeclarations.push_back(NewFD);
10966
10967 return NewFD;
10968}
10969
10970/// Return a CodeSegAttr from a containing class. The Microsoft docs say
10971/// when __declspec(code_seg) "is applied to a class, all member functions of
10972/// the class and nested classes -- this includes compiler-generated special
10973/// member functions -- are put in the specified segment."
10974/// The actual behavior is a little more complicated. The Microsoft compiler
10975/// won't check outer classes if there is an active value from #pragma code_seg.
10976/// The CodeSeg is always applied from the direct parent but only from outer
10977/// classes when the #pragma code_seg stack is empty. See:
10978/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10979/// available since MS has removed the page.
10981 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10982 if (!Method)
10983 return nullptr;
10984 const CXXRecordDecl *Parent = Method->getParent();
10985 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10986 Attr *NewAttr = SAttr->clone(S.getASTContext());
10987 NewAttr->setImplicit(true);
10988 return NewAttr;
10989 }
10990
10991 // The Microsoft compiler won't check outer classes for the CodeSeg
10992 // when the #pragma code_seg stack is active.
10993 if (S.CodeSegStack.CurrentValue)
10994 return nullptr;
10995
10996 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10997 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10998 Attr *NewAttr = SAttr->clone(S.getASTContext());
10999 NewAttr->setImplicit(true);
11000 return NewAttr;
11001 }
11002 }
11003 return nullptr;
11004}
11005
11007 bool IsDefinition) {
11008 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11009 return A;
11010 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11011 CodeSegStack.CurrentValue)
11012 return SectionAttr::CreateImplicit(
11013 getASTContext(), CodeSegStack.CurrentValue->getString(),
11014 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11015 return nullptr;
11016}
11017
11019 QualType NewT, QualType OldT) {
11021 return true;
11022
11023 // For dependently-typed local extern declarations and friends, we can't
11024 // perform a correct type check in general until instantiation:
11025 //
11026 // int f();
11027 // template<typename T> void g() { T f(); }
11028 //
11029 // (valid if g() is only instantiated with T = int).
11030 if (NewT->isDependentType() &&
11031 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11032 return false;
11033
11034 // Similarly, if the previous declaration was a dependent local extern
11035 // declaration, we don't really know its type yet.
11036 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11037 return false;
11038
11039 return true;
11040}
11041
11044 return true;
11045
11046 // Don't chain dependent friend function definitions until instantiation, to
11047 // permit cases like
11048 //
11049 // void func();
11050 // template<typename T> class C1 { friend void func() {} };
11051 // template<typename T> class C2 { friend void func() {} };
11052 //
11053 // ... which is valid if only one of C1 and C2 is ever instantiated.
11054 //
11055 // FIXME: This need only apply to function definitions. For now, we proxy
11056 // this by checking for a file-scope function. We do not want this to apply
11057 // to friend declarations nominating member functions, because that gets in
11058 // the way of access checks.
11060 return false;
11061
11062 auto *VD = dyn_cast<ValueDecl>(D);
11063 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11064 return !VD || !PrevVD ||
11065 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11066 PrevVD->getType());
11067}
11068
11069/// Check the target or target_version attribute of the function for
11070/// MultiVersion validity.
11071///
11072/// Returns true if there was an error, false otherwise.
11073static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11074 const auto *TA = FD->getAttr<TargetAttr>();
11075 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11076
11077 assert((TA || TVA) && "Expecting target or target_version attribute");
11078
11080 enum ErrType { Feature = 0, Architecture = 1 };
11081
11082 if (TA) {
11083 ParsedTargetAttr ParseInfo =
11084 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11085 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11086 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11087 << Architecture << ParseInfo.CPU;
11088 return true;
11089 }
11090 for (const auto &Feat : ParseInfo.Features) {
11091 auto BareFeat = StringRef{Feat}.substr(1);
11092 if (Feat[0] == '-') {
11093 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11094 << Feature << ("no-" + BareFeat).str();
11095 return true;
11096 }
11097
11098 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11099 !TargetInfo.isValidFeatureName(BareFeat)) {
11100 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11101 << Feature << BareFeat;
11102 return true;
11103 }
11104 }
11105 }
11106
11107 if (TVA) {
11109 ParsedTargetAttr ParseInfo;
11110 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11111 ParseInfo =
11112 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11113 for (auto &Feat : ParseInfo.Features)
11114 Feats.push_back(StringRef{Feat}.substr(1));
11115 } else {
11116 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11117 TVA->getFeatures(Feats);
11118 }
11119 for (const auto &Feat : Feats) {
11120 if (!TargetInfo.validateCpuSupports(Feat)) {
11121 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11122 << Feature << Feat;
11123 return true;
11124 }
11125 }
11126 }
11127 return false;
11128}
11129
11130// Provide a white-list of attributes that are allowed to be combined with
11131// multiversion functions.
11133 MultiVersionKind MVKind) {
11134 // Note: this list/diagnosis must match the list in
11135 // checkMultiversionAttributesAllSame.
11136 switch (Kind) {
11137 default:
11138 return false;
11139 case attr::ArmLocallyStreaming:
11140 return MVKind == MultiVersionKind::TargetVersion ||
11142 case attr::Used:
11143 return MVKind == MultiVersionKind::Target;
11144 case attr::NonNull:
11145 case attr::NoThrow:
11146 return true;
11147 }
11148}
11149
11151 const FunctionDecl *FD,
11152 const FunctionDecl *CausedFD,
11153 MultiVersionKind MVKind) {
11154 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11155 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11156 << static_cast<unsigned>(MVKind) << A;
11157 if (CausedFD)
11158 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11159 return true;
11160 };
11161
11162 for (const Attr *A : FD->attrs()) {
11163 switch (A->getKind()) {
11164 case attr::CPUDispatch:
11165 case attr::CPUSpecific:
11166 if (MVKind != MultiVersionKind::CPUDispatch &&
11168 return Diagnose(S, A);
11169 break;
11170 case attr::Target:
11171 if (MVKind != MultiVersionKind::Target)
11172 return Diagnose(S, A);
11173 break;
11174 case attr::TargetVersion:
11175 if (MVKind != MultiVersionKind::TargetVersion &&
11177 return Diagnose(S, A);
11178 break;
11179 case attr::TargetClones:
11180 if (MVKind != MultiVersionKind::TargetClones &&
11182 return Diagnose(S, A);
11183 break;
11184 default:
11185 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11186 return Diagnose(S, A);
11187 break;
11188 }
11189 }
11190 return false;
11191}
11192
11194 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11195 const PartialDiagnostic &NoProtoDiagID,
11196 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11197 const PartialDiagnosticAt &NoSupportDiagIDAt,
11198 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11199 bool ConstexprSupported, bool CLinkageMayDiffer) {
11200 enum DoesntSupport {
11201 FuncTemplates = 0,
11202 VirtFuncs = 1,
11203 DeducedReturn = 2,
11204 Constructors = 3,
11205 Destructors = 4,
11206 DeletedFuncs = 5,
11207 DefaultedFuncs = 6,
11208 ConstexprFuncs = 7,
11209 ConstevalFuncs = 8,
11210 Lambda = 9,
11211 };
11212 enum Different {
11213 CallingConv = 0,
11214 ReturnType = 1,
11215 ConstexprSpec = 2,
11216 InlineSpec = 3,
11217 Linkage = 4,
11218 LanguageLinkage = 5,
11219 };
11220
11221 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11222 !OldFD->getType()->getAs<FunctionProtoType>()) {
11223 Diag(OldFD->getLocation(), NoProtoDiagID);
11224 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11225 return true;
11226 }
11227
11228 if (NoProtoDiagID.getDiagID() != 0 &&
11229 !NewFD->getType()->getAs<FunctionProtoType>())
11230 return Diag(NewFD->getLocation(), NoProtoDiagID);
11231
11232 if (!TemplatesSupported &&
11234 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11235 << FuncTemplates;
11236
11237 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11238 if (NewCXXFD->isVirtual())
11239 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11240 << VirtFuncs;
11241
11242 if (isa<CXXConstructorDecl>(NewCXXFD))
11243 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11244 << Constructors;
11245
11246 if (isa<CXXDestructorDecl>(NewCXXFD))
11247 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11248 << Destructors;
11249 }
11250
11251 if (NewFD->isDeleted())
11252 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11253 << DeletedFuncs;
11254
11255 if (NewFD->isDefaulted())
11256 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11257 << DefaultedFuncs;
11258
11259 if (!ConstexprSupported && NewFD->isConstexpr())
11260 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11261 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11262
11263 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11264 const auto *NewType = cast<FunctionType>(NewQType);
11265 QualType NewReturnType = NewType->getReturnType();
11266
11267 if (NewReturnType->isUndeducedType())
11268 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11269 << DeducedReturn;
11270
11271 // Ensure the return type is identical.
11272 if (OldFD) {
11273 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11274 const auto *OldType = cast<FunctionType>(OldQType);
11275 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11276 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11277
11278 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11279 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11280
11281 bool ArmStreamingCCMismatched = false;
11282 if (OldFPT && NewFPT) {
11283 unsigned Diff =
11285 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11286 // cannot be mixed.
11289 ArmStreamingCCMismatched = true;
11290 }
11291
11292 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11293 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11294
11295 QualType OldReturnType = OldType->getReturnType();
11296
11297 if (OldReturnType != NewReturnType)
11298 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11299
11300 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11301 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11302
11303 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11304 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11305
11306 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11307 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11308
11309 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11310 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11311
11312 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11313 NewFD->getLocation()))
11314 return true;
11315 }
11316 return false;
11317}
11318
11320 const FunctionDecl *NewFD,
11321 bool CausesMV,
11322 MultiVersionKind MVKind) {
11324 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11325 if (OldFD)
11326 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11327 return true;
11328 }
11329
11330 bool IsCPUSpecificCPUDispatchMVKind =
11333
11334 if (CausesMV && OldFD &&
11335 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11336 return true;
11337
11338 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11339 return true;
11340
11341 // Only allow transition to MultiVersion if it hasn't been used.
11342 if (OldFD && CausesMV && OldFD->isUsed(false))
11343 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11344
11346 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11348 S.PDiag(diag::note_multiversioning_caused_here)),
11350 S.PDiag(diag::err_multiversion_doesnt_support)
11351 << static_cast<unsigned>(MVKind)),
11353 S.PDiag(diag::err_multiversion_diff)),
11354 /*TemplatesSupported=*/false,
11355 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11356 /*CLinkageMayDiffer=*/false);
11357}
11358
11359/// Check the validity of a multiversion function declaration that is the
11360/// first of its kind. Also sets the multiversion'ness' of the function itself.
11361///
11362/// This sets NewFD->isInvalidDecl() to true if there was an error.
11363///
11364/// Returns true if there was an error, false otherwise.
11367 assert(MVKind != MultiVersionKind::None &&
11368 "Function lacks multiversion attribute");
11369 const auto *TA = FD->getAttr<TargetAttr>();
11370 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11371 // The target attribute only causes MV if this declaration is the default,
11372 // otherwise it is treated as a normal function.
11373 if (TA && !TA->isDefaultVersion())
11374 return false;
11375
11376 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11377 FD->setInvalidDecl();
11378 return true;
11379 }
11380
11381 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11382 FD->setInvalidDecl();
11383 return true;
11384 }
11385
11386 FD->setIsMultiVersion();
11387 return false;
11388}
11389
11391 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11393 return true;
11394 }
11395
11396 return false;
11397}
11398
11400 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11401 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11402 return;
11403
11404 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11405 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11406
11407 if (MVKindTo == MultiVersionKind::None &&
11408 (MVKindFrom == MultiVersionKind::TargetVersion ||
11409 MVKindFrom == MultiVersionKind::TargetClones))
11410 To->addAttr(TargetVersionAttr::CreateImplicit(
11411 To->getASTContext(), "default", To->getSourceRange()));
11412}
11413
11415 FunctionDecl *NewFD,
11416 bool &Redeclaration,
11417 NamedDecl *&OldDecl,
11419 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11420
11421 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11422 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11423 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11424 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11425
11426 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11427
11428 // The definitions should be allowed in any order. If we have discovered
11429 // a new target version and the preceeding was the default, then add the
11430 // corresponding attribute to it.
11431 patchDefaultTargetVersion(NewFD, OldFD);
11432
11433 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11434 // to change, this is a simple redeclaration.
11435 if (NewTA && !NewTA->isDefaultVersion() &&
11436 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11437 return false;
11438
11439 // Otherwise, this decl causes MultiVersioning.
11440 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11443 NewFD->setInvalidDecl();
11444 return true;
11445 }
11446
11447 if (CheckMultiVersionValue(S, NewFD)) {
11448 NewFD->setInvalidDecl();
11449 return true;
11450 }
11451
11452 // If this is 'default', permit the forward declaration.
11453 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11454 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11455 Redeclaration = true;
11456 OldDecl = OldFD;
11457 OldFD->setIsMultiVersion();
11458 NewFD->setIsMultiVersion();
11459 return false;
11460 }
11461
11462 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11463 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11464 NewFD->setInvalidDecl();
11465 return true;
11466 }
11467
11468 if (NewTA) {
11469 ParsedTargetAttr OldParsed =
11471 OldTA->getFeaturesStr());
11472 llvm::sort(OldParsed.Features);
11473 ParsedTargetAttr NewParsed =
11475 NewTA->getFeaturesStr());
11476 // Sort order doesn't matter, it just needs to be consistent.
11477 llvm::sort(NewParsed.Features);
11478 if (OldParsed == NewParsed) {
11479 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11480 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11481 NewFD->setInvalidDecl();
11482 return true;
11483 }
11484 }
11485
11486 for (const auto *FD : OldFD->redecls()) {
11487 const auto *CurTA = FD->getAttr<TargetAttr>();
11488 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11489 // We allow forward declarations before ANY multiversioning attributes, but
11490 // nothing after the fact.
11492 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11493 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11494 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11495 << (NewTA ? 0 : 2);
11496 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11497 NewFD->setInvalidDecl();
11498 return true;
11499 }
11500 }
11501
11502 OldFD->setIsMultiVersion();
11503 NewFD->setIsMultiVersion();
11504 Redeclaration = false;
11505 OldDecl = nullptr;
11506 Previous.clear();
11507 return false;
11508}
11509
11511 MultiVersionKind OldKind = Old->getMultiVersionKind();
11512 MultiVersionKind NewKind = New->getMultiVersionKind();
11513
11514 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11515 NewKind == MultiVersionKind::None)
11516 return true;
11517
11518 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11519 switch (OldKind) {
11521 return NewKind == MultiVersionKind::TargetClones;
11523 return NewKind == MultiVersionKind::TargetVersion;
11524 default:
11525 return false;
11526 }
11527 } else {
11528 switch (OldKind) {
11530 return NewKind == MultiVersionKind::CPUSpecific;
11532 return NewKind == MultiVersionKind::CPUDispatch;
11533 default:
11534 return false;
11535 }
11536 }
11537}
11538
11539/// Check the validity of a new function declaration being added to an existing
11540/// multiversioned declaration collection.
11542 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11543 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11544 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11546
11547 // Disallow mixing of multiversioning types.
11548 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11549 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11550 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11551 NewFD->setInvalidDecl();
11552 return true;
11553 }
11554
11555 // Add the default target_version attribute if it's missing.
11556 patchDefaultTargetVersion(OldFD, NewFD);
11557 patchDefaultTargetVersion(NewFD, OldFD);
11558
11559 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11560 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11561 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11562 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11563
11564 ParsedTargetAttr NewParsed;
11565 if (NewTA) {
11567 NewTA->getFeaturesStr());
11568 llvm::sort(NewParsed.Features);
11569 }
11571 if (NewTVA) {
11572 NewTVA->getFeatures(NewFeats);
11573 llvm::sort(NewFeats);
11574 }
11575
11576 bool UseMemberUsingDeclRules =
11577 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11578
11579 bool MayNeedOverloadableChecks =
11581
11582 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11583 // of a previous member of the MultiVersion set.
11584 for (NamedDecl *ND : Previous) {
11585 FunctionDecl *CurFD = ND->getAsFunction();
11586 if (!CurFD || CurFD->isInvalidDecl())
11587 continue;
11588 if (MayNeedOverloadableChecks &&
11589 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11590 continue;
11591
11592 switch (NewMVKind) {
11594 assert(OldMVKind == MultiVersionKind::TargetClones &&
11595 "Only target_clones can be omitted in subsequent declarations");
11596 break;
11598 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11599 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11600 NewFD->setIsMultiVersion();
11601 Redeclaration = true;
11602 OldDecl = ND;
11603 return false;
11604 }
11605
11606 ParsedTargetAttr CurParsed =
11608 CurTA->getFeaturesStr());
11609 llvm::sort(CurParsed.Features);
11610 if (CurParsed == NewParsed) {
11611 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11612 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11613 NewFD->setInvalidDecl();
11614 return true;
11615 }
11616 break;
11617 }
11619 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11620 if (CurTVA->getName() == NewTVA->getName()) {
11621 NewFD->setIsMultiVersion();
11622 Redeclaration = true;
11623 OldDecl = ND;
11624 return false;
11625 }
11627 CurTVA->getFeatures(CurFeats);
11628 llvm::sort(CurFeats);
11629
11630 if (CurFeats == NewFeats) {
11631 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11632 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11633 NewFD->setInvalidDecl();
11634 return true;
11635 }
11636 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11637 // Default
11638 if (NewFeats.empty())
11639 break;
11640
11641 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11643 CurClones->getFeatures(CurFeats, I);
11644 llvm::sort(CurFeats);
11645
11646 if (CurFeats == NewFeats) {
11647 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11648 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11649 NewFD->setInvalidDecl();
11650 return true;
11651 }
11652 }
11653 }
11654 break;
11655 }
11657 assert(NewClones && "MultiVersionKind does not match attribute type");
11658 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11659 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11660 !std::equal(CurClones->featuresStrs_begin(),
11661 CurClones->featuresStrs_end(),
11662 NewClones->featuresStrs_begin())) {
11663 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11664 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11665 NewFD->setInvalidDecl();
11666 return true;
11667 }
11668 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11670 CurTVA->getFeatures(CurFeats);
11671 llvm::sort(CurFeats);
11672
11673 // Default
11674 if (CurFeats.empty())
11675 break;
11676
11677 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11678 NewFeats.clear();
11679 NewClones->getFeatures(NewFeats, I);
11680 llvm::sort(NewFeats);
11681
11682 if (CurFeats == NewFeats) {
11683 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11684 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11685 NewFD->setInvalidDecl();
11686 return true;
11687 }
11688 }
11689 break;
11690 }
11691 Redeclaration = true;
11692 OldDecl = CurFD;
11693 NewFD->setIsMultiVersion();
11694 return false;
11695 }
11698 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11699 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11700 // Handle CPUDispatch/CPUSpecific versions.
11701 // Only 1 CPUDispatch function is allowed, this will make it go through
11702 // the redeclaration errors.
11703 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11704 CurFD->hasAttr<CPUDispatchAttr>()) {
11705 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11706 std::equal(
11707 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11708 NewCPUDisp->cpus_begin(),
11709 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11710 return Cur->getName() == New->getName();
11711 })) {
11712 NewFD->setIsMultiVersion();
11713 Redeclaration = true;
11714 OldDecl = ND;
11715 return false;
11716 }
11717
11718 // If the declarations don't match, this is an error condition.
11719 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11720 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11721 NewFD->setInvalidDecl();
11722 return true;
11723 }
11724 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11725 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11726 std::equal(
11727 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11728 NewCPUSpec->cpus_begin(),
11729 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11730 return Cur->getName() == New->getName();
11731 })) {
11732 NewFD->setIsMultiVersion();
11733 Redeclaration = true;
11734 OldDecl = ND;
11735 return false;
11736 }
11737
11738 // Only 1 version of CPUSpecific is allowed for each CPU.
11739 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11740 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11741 if (CurII == NewII) {
11742 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11743 << NewII;
11744 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11745 NewFD->setInvalidDecl();
11746 return true;
11747 }
11748 }
11749 }
11750 }
11751 break;
11752 }
11753 }
11754 }
11755
11756 // Else, this is simply a non-redecl case. Checking the 'value' is only
11757 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11758 // handled in the attribute adding step.
11759 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
11760 NewFD->setInvalidDecl();
11761 return true;
11762 }
11763
11764 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11765 !OldFD->isMultiVersion(), NewMVKind)) {
11766 NewFD->setInvalidDecl();
11767 return true;
11768 }
11769
11770 // Permit forward declarations in the case where these two are compatible.
11771 if (!OldFD->isMultiVersion()) {
11772 OldFD->setIsMultiVersion();
11773 NewFD->setIsMultiVersion();
11774 Redeclaration = true;
11775 OldDecl = OldFD;
11776 return false;
11777 }
11778
11779 NewFD->setIsMultiVersion();
11780 Redeclaration = false;
11781 OldDecl = nullptr;
11782 Previous.clear();
11783 return false;
11784}
11785
11786/// Check the validity of a mulitversion function declaration.
11787/// Also sets the multiversion'ness' of the function itself.
11788///
11789/// This sets NewFD->isInvalidDecl() to true if there was an error.
11790///
11791/// Returns true if there was an error, false otherwise.
11793 bool &Redeclaration, NamedDecl *&OldDecl,
11795 const TargetInfo &TI = S.getASTContext().getTargetInfo();
11796
11797 // Check if FMV is disabled.
11798 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
11799 return false;
11800
11801 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11802 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11803 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11804 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11805 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11806 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11807
11808 // Main isn't allowed to become a multiversion function, however it IS
11809 // permitted to have 'main' be marked with the 'target' optimization hint,
11810 // for 'target_version' only default is allowed.
11811 if (NewFD->isMain()) {
11812 if (MVKind != MultiVersionKind::None &&
11813 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11814 !(MVKind == MultiVersionKind::TargetVersion &&
11815 NewTVA->isDefaultVersion())) {
11816 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11817 NewFD->setInvalidDecl();
11818 return true;
11819 }
11820 return false;
11821 }
11822
11823 // Target attribute on AArch64 is not used for multiversioning
11824 if (NewTA && TI.getTriple().isAArch64())
11825 return false;
11826
11827 // Target attribute on RISCV is not used for multiversioning
11828 if (NewTA && TI.getTriple().isRISCV())
11829 return false;
11830
11831 if (!OldDecl || !OldDecl->getAsFunction() ||
11832 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11833 NewFD->getDeclContext()->getRedeclContext())) {
11834 // If there's no previous declaration, AND this isn't attempting to cause
11835 // multiversioning, this isn't an error condition.
11836 if (MVKind == MultiVersionKind::None)
11837 return false;
11838 return CheckMultiVersionFirstFunction(S, NewFD);
11839 }
11840
11841 FunctionDecl *OldFD = OldDecl->getAsFunction();
11842
11843 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11844 return false;
11845
11846 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11847 // for target_clones and target_version.
11848 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11851 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11853 NewFD->setInvalidDecl();
11854 return true;
11855 }
11856
11857 if (!OldFD->isMultiVersion()) {
11858 switch (MVKind) {
11862 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11864 if (OldFD->isUsed(false)) {
11865 NewFD->setInvalidDecl();
11866 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11867 }
11868 OldFD->setIsMultiVersion();
11869 break;
11870
11874 break;
11875 }
11876 }
11877
11878 // At this point, we have a multiversion function decl (in OldFD) AND an
11879 // appropriate attribute in the current function decl. Resolve that these are
11880 // still compatible with previous declarations.
11881 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11882 NewCPUSpec, NewClones, Redeclaration,
11883 OldDecl, Previous);
11884}
11885
11887 bool IsPure = NewFD->hasAttr<PureAttr>();
11888 bool IsConst = NewFD->hasAttr<ConstAttr>();
11889
11890 // If there are no pure or const attributes, there's nothing to check.
11891 if (!IsPure && !IsConst)
11892 return;
11893
11894 // If the function is marked both pure and const, we retain the const
11895 // attribute because it makes stronger guarantees than the pure attribute, and
11896 // we drop the pure attribute explicitly to prevent later confusion about
11897 // semantics.
11898 if (IsPure && IsConst) {
11899 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11900 NewFD->dropAttrs<PureAttr>();
11901 }
11902
11903 // Constructors and destructors are functions which return void, so are
11904 // handled here as well.
11905 if (NewFD->getReturnType()->isVoidType()) {
11906 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11907 << IsConst;
11908 NewFD->dropAttrs<PureAttr, ConstAttr>();
11909 }
11910}
11911
11914 bool IsMemberSpecialization,
11915 bool DeclIsDefn) {
11916 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11917 "Variably modified return types are not handled here");
11918
11919 // Determine whether the type of this function should be merged with
11920 // a previous visible declaration. This never happens for functions in C++,
11921 // and always happens in C if the previous declaration was visible.
11922 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11923 !Previous.isShadowed();
11924
11925 bool Redeclaration = false;
11926 NamedDecl *OldDecl = nullptr;
11927 bool MayNeedOverloadableChecks = false;
11928
11930 // Merge or overload the declaration with an existing declaration of
11931 // the same name, if appropriate.
11932 if (!Previous.empty()) {
11933 // Determine whether NewFD is an overload of PrevDecl or
11934 // a declaration that requires merging. If it's an overload,
11935 // there's no more work to do here; we'll just add the new
11936 // function to the scope.
11938 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11939 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11940 Redeclaration = true;
11941 OldDecl = Candidate;
11942 }
11943 } else {
11944 MayNeedOverloadableChecks = true;
11945 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11946 /*NewIsUsingDecl*/ false)) {
11947 case Ovl_Match:
11948 Redeclaration = true;
11949 break;
11950
11951 case Ovl_NonFunction:
11952 Redeclaration = true;
11953 break;
11954
11955 case Ovl_Overload:
11956 Redeclaration = false;
11957 break;
11958 }
11959 }
11960 }
11961
11962 // Check for a previous extern "C" declaration with this name.
11963 if (!Redeclaration &&
11965 if (!Previous.empty()) {
11966 // This is an extern "C" declaration with the same name as a previous
11967 // declaration, and thus redeclares that entity...
11968 Redeclaration = true;
11969 OldDecl = Previous.getFoundDecl();
11970 MergeTypeWithPrevious = false;
11971
11972 // ... except in the presence of __attribute__((overloadable)).
11973 if (OldDecl->hasAttr<OverloadableAttr>() ||
11974 NewFD->hasAttr<OverloadableAttr>()) {
11975 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11976 MayNeedOverloadableChecks = true;
11977 Redeclaration = false;
11978 OldDecl = nullptr;
11979 }
11980 }
11981 }
11982 }
11983
11984 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11985 return Redeclaration;
11986
11987 // PPC MMA non-pointer types are not allowed as function return types.
11988 if (Context.getTargetInfo().getTriple().isPPC64() &&
11989 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11990 NewFD->setInvalidDecl();
11991 }
11992
11993 CheckConstPureAttributesUsage(*this, NewFD);
11994
11995 // C++ [dcl.spec.auto.general]p12:
11996 // Return type deduction for a templated function with a placeholder in its
11997 // declared type occurs when the definition is instantiated even if the
11998 // function body contains a return statement with a non-type-dependent
11999 // operand.
12000 //
12001 // C++ [temp.dep.expr]p3:
12002 // An id-expression is type-dependent if it is a template-id that is not a
12003 // concept-id and is dependent; or if its terminal name is:
12004 // - [...]
12005 // - associated by name lookup with one or more declarations of member
12006 // functions of a class that is the current instantiation declared with a
12007 // return type that contains a placeholder type,
12008 // - [...]
12009 //
12010 // If this is a templated function with a placeholder in its return type,
12011 // make the placeholder type dependent since it won't be deduced until the
12012 // definition is instantiated. We do this here because it needs to happen
12013 // for implicitly instantiated member functions/member function templates.
12014 if (getLangOpts().CPlusPlus14 &&
12015 (NewFD->isDependentContext() &&
12016 NewFD->getReturnType()->isUndeducedType())) {
12017 const FunctionProtoType *FPT =
12018 NewFD->getType()->castAs<FunctionProtoType>();
12019 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12020 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12021 FPT->getExtProtoInfo()));
12022 }
12023
12024 // C++11 [dcl.constexpr]p8:
12025 // A constexpr specifier for a non-static member function that is not
12026 // a constructor declares that member function to be const.
12027 //
12028 // This needs to be delayed until we know whether this is an out-of-line
12029 // definition of a static member function.
12030 //
12031 // This rule is not present in C++1y, so we produce a backwards
12032 // compatibility warning whenever it happens in C++11.
12033 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12034 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12035 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12036 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
12037 CXXMethodDecl *OldMD = nullptr;
12038 if (OldDecl)
12039 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12040 if (!OldMD || !OldMD->isStatic()) {
12041 const FunctionProtoType *FPT =
12044 EPI.TypeQuals.addConst();
12046 FPT->getParamTypes(), EPI));
12047
12048 // Warn that we did this, if we're not performing template instantiation.
12049 // In that case, we'll have warned already when the template was defined.
12050 if (!inTemplateInstantiation()) {
12051 SourceLocation AddConstLoc;
12054 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12055
12056 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12057 << FixItHint::CreateInsertion(AddConstLoc, " const");
12058 }
12059 }
12060 }
12061
12062 if (Redeclaration) {
12063 // NewFD and OldDecl represent declarations that need to be
12064 // merged.
12065 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12066 DeclIsDefn)) {
12067 NewFD->setInvalidDecl();
12068 return Redeclaration;
12069 }
12070
12071 Previous.clear();
12072 Previous.addDecl(OldDecl);
12073
12074 if (FunctionTemplateDecl *OldTemplateDecl =
12075 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12076 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12077 FunctionTemplateDecl *NewTemplateDecl
12079 assert(NewTemplateDecl && "Template/non-template mismatch");
12080
12081 // The call to MergeFunctionDecl above may have created some state in
12082 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12083 // can add it as a redeclaration.
12084 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12085
12086 NewFD->setPreviousDeclaration(OldFD);
12087 if (NewFD->isCXXClassMember()) {
12088 NewFD->setAccess(OldTemplateDecl->getAccess());
12089 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12090 }
12091
12092 // If this is an explicit specialization of a member that is a function
12093 // template, mark it as a member specialization.
12094 if (IsMemberSpecialization &&
12095 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12096 NewTemplateDecl->setMemberSpecialization();
12097 assert(OldTemplateDecl->isMemberSpecialization());
12098 // Explicit specializations of a member template do not inherit deleted
12099 // status from the parent member template that they are specializing.
12100 if (OldFD->isDeleted()) {
12101 // FIXME: This assert will not hold in the presence of modules.
12102 assert(OldFD->getCanonicalDecl() == OldFD);
12103 // FIXME: We need an update record for this AST mutation.
12104 OldFD->setDeletedAsWritten(false);
12105 }
12106 }
12107
12108 } else {
12109 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12110 auto *OldFD = cast<FunctionDecl>(OldDecl);
12111 // This needs to happen first so that 'inline' propagates.
12112 NewFD->setPreviousDeclaration(OldFD);
12113 if (NewFD->isCXXClassMember())
12114 NewFD->setAccess(OldFD->getAccess());
12115 }
12116 }
12117 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12118 !NewFD->getAttr<OverloadableAttr>()) {
12119 assert((Previous.empty() ||
12120 llvm::any_of(Previous,
12121 [](const NamedDecl *ND) {
12122 return ND->hasAttr<OverloadableAttr>();
12123 })) &&
12124 "Non-redecls shouldn't happen without overloadable present");
12125
12126 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12127 const auto *FD = dyn_cast<FunctionDecl>(ND);
12128 return FD && !FD->hasAttr<OverloadableAttr>();
12129 });
12130
12131 if (OtherUnmarkedIter != Previous.end()) {
12132 Diag(NewFD->getLocation(),
12133 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12134 Diag((*OtherUnmarkedIter)->getLocation(),
12135 diag::note_attribute_overloadable_prev_overload)
12136 << false;
12137
12138 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12139 }
12140 }
12141
12142 if (LangOpts.OpenMP)
12144
12145 if (LangOpts.isSYCL() && NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12147
12148 // Semantic checking for this function declaration (in isolation).
12149
12150 if (getLangOpts().CPlusPlus) {
12151 // C++-specific checks.
12152 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12153 CheckConstructor(Constructor);
12154 } else if (CXXDestructorDecl *Destructor =
12155 dyn_cast<CXXDestructorDecl>(NewFD)) {
12156 // We check here for invalid destructor names.
12157 // If we have a friend destructor declaration that is dependent, we can't
12158 // diagnose right away because cases like this are still valid:
12159 // template <class T> struct A { friend T::X::~Y(); };
12160 // struct B { struct Y { ~Y(); }; using X = Y; };
12161 // template struct A<B>;
12163 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12164 CXXRecordDecl *Record = Destructor->getParent();
12166
12168 Context.getCanonicalType(ClassType));
12169 if (NewFD->getDeclName() != Name) {
12170 Diag(NewFD->getLocation(), diag::err_destructor_name);
12171 NewFD->setInvalidDecl();
12172 return Redeclaration;
12173 }
12174 }
12175 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12176 if (auto *TD = Guide->getDescribedFunctionTemplate())
12178
12179 // A deduction guide is not on the list of entities that can be
12180 // explicitly specialized.
12181 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12182 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12183 << /*explicit specialization*/ 1;
12184 }
12185
12186 // Find any virtual functions that this function overrides.
12187 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12188 if (!Method->isFunctionTemplateSpecialization() &&
12189 !Method->getDescribedFunctionTemplate() &&
12190 Method->isCanonicalDecl()) {
12191 AddOverriddenMethods(Method->getParent(), Method);
12192 }
12193 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12194 // C++2a [class.virtual]p6
12195 // A virtual method shall not have a requires-clause.
12197 diag::err_constrained_virtual_method);
12198
12199 if (Method->isStatic())
12201 }
12202
12203 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12204 ActOnConversionDeclarator(Conversion);
12205
12206 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12207 if (NewFD->isOverloadedOperator() &&
12209 NewFD->setInvalidDecl();
12210 return Redeclaration;
12211 }
12212
12213 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12214 if (NewFD->getLiteralIdentifier() &&
12216 NewFD->setInvalidDecl();
12217 return Redeclaration;
12218 }
12219
12220 // In C++, check default arguments now that we have merged decls. Unless
12221 // the lexical context is the class, because in this case this is done
12222 // during delayed parsing anyway.
12223 if (!CurContext->isRecord())
12225
12226 // If this function is declared as being extern "C", then check to see if
12227 // the function returns a UDT (class, struct, or union type) that is not C
12228 // compatible, and if it does, warn the user.
12229 // But, issue any diagnostic on the first declaration only.
12230 if (Previous.empty() && NewFD->isExternC()) {
12231 QualType R = NewFD->getReturnType();
12232 if (R->isIncompleteType() && !R->isVoidType())
12233 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12234 << NewFD << R;
12235 else if (!R.isPODType(Context) && !R->isVoidType() &&
12237 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12238 }
12239
12240 // C++1z [dcl.fct]p6:
12241 // [...] whether the function has a non-throwing exception-specification
12242 // [is] part of the function type
12243 //
12244 // This results in an ABI break between C++14 and C++17 for functions whose
12245 // declared type includes an exception-specification in a parameter or
12246 // return type. (Exception specifications on the function itself are OK in
12247 // most cases, and exception specifications are not permitted in most other
12248 // contexts where they could make it into a mangling.)
12249 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12250 auto HasNoexcept = [&](QualType T) -> bool {
12251 // Strip off declarator chunks that could be between us and a function
12252 // type. We don't need to look far, exception specifications are very
12253 // restricted prior to C++17.
12254 if (auto *RT = T->getAs<ReferenceType>())
12255 T = RT->getPointeeType();
12256 else if (T->isAnyPointerType())
12257 T = T->getPointeeType();
12258 else if (auto *MPT = T->getAs<MemberPointerType>())
12259 T = MPT->getPointeeType();
12260 if (auto *FPT = T->getAs<FunctionProtoType>())
12261 if (FPT->isNothrow())
12262 return true;
12263 return false;
12264 };
12265
12266 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12267 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12268 for (QualType T : FPT->param_types())
12269 AnyNoexcept |= HasNoexcept(T);
12270 if (AnyNoexcept)
12271 Diag(NewFD->getLocation(),
12272 diag::warn_cxx17_compat_exception_spec_in_signature)
12273 << NewFD;
12274 }
12275
12276 if (!Redeclaration && LangOpts.CUDA) {
12277 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12278 for (auto *Parm : NewFD->parameters()) {
12279 if (!Parm->getType()->isDependentType() &&
12280 Parm->hasAttr<CUDAGridConstantAttr>() &&
12281 !(IsKernel && Parm->getType().isConstQualified()))
12282 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12283 diag::err_cuda_grid_constant_not_allowed);
12284 }
12286 }
12287 }
12288
12289 // Check if the function definition uses any AArch64 SME features without
12290 // having the '+sme' feature enabled and warn user if sme locally streaming
12291 // function returns or uses arguments with VL-based types.
12292 if (DeclIsDefn) {
12293 const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12294 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12295 bool UsesZA = Attr && Attr->isNewZA();
12296 bool UsesZT0 = Attr && Attr->isNewZT0();
12297
12298 if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) {
12299 if (NewFD->getReturnType()->isSizelessVectorType())
12300 Diag(NewFD->getLocation(),
12301 diag::warn_sme_locally_streaming_has_vl_args_returns)
12302 << /*IsArg=*/false;
12303 if (llvm::any_of(NewFD->parameters(), [](ParmVarDecl *P) {
12304 return P->getOriginalType()->isSizelessVectorType();
12305 }))
12306 Diag(NewFD->getLocation(),
12307 diag::warn_sme_locally_streaming_has_vl_args_returns)
12308 << /*IsArg=*/true;
12309 }
12310 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12311 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12312 UsesSM |=
12318 }
12319
12320 if (UsesSM || UsesZA) {
12321 llvm::StringMap<bool> FeatureMap;
12322 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12323 if (!FeatureMap.contains("sme")) {
12324 if (UsesSM)
12325 Diag(NewFD->getLocation(),
12326 diag::err_sme_definition_using_sm_in_non_sme_target);
12327 else
12328 Diag(NewFD->getLocation(),
12329 diag::err_sme_definition_using_za_in_non_sme_target);
12330 }
12331 }
12332 if (UsesZT0) {
12333 llvm::StringMap<bool> FeatureMap;
12334 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12335 if (!FeatureMap.contains("sme2")) {
12336 Diag(NewFD->getLocation(),
12337 diag::err_sme_definition_using_zt0_in_non_sme2_target);
12338 }
12339 }
12340 }
12341
12342 return Redeclaration;
12343}
12344
12346 // [basic.start.main]p3
12347 // The main function shall not be declared with a linkage-specification.
12348 if (FD->isExternCContext() ||
12349 (FD->isExternCXXContext() &&
12351 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification)
12352 << FD->getLanguageLinkage();
12353
12354 // C++11 [basic.start.main]p3:
12355 // A program that [...] declares main to be inline, static or
12356 // constexpr is ill-formed.
12357 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12358 // appear in a declaration of main.
12359 // static main is not an error under C99, but we should warn about it.
12360 // We accept _Noreturn main as an extension.
12361 if (FD->getStorageClass() == SC_Static)
12363 ? diag::err_static_main : diag::warn_static_main)
12365 if (FD->isInlineSpecified())
12366 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12368 if (DS.isNoreturnSpecified()) {
12369 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12370 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12371 Diag(NoreturnLoc, diag::ext_noreturn_main);
12372 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12373 << FixItHint::CreateRemoval(NoreturnRange);
12374 }
12375 if (FD->isConstexpr()) {
12376 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12377 << FD->isConsteval()
12380 }
12381
12382 if (getLangOpts().OpenCL) {
12383 Diag(FD->getLocation(), diag::err_opencl_no_main)
12384 << FD->hasAttr<OpenCLKernelAttr>();
12385 FD->setInvalidDecl();
12386 return;
12387 }
12388
12389 // Functions named main in hlsl are default entries, but don't have specific
12390 // signatures they are required to conform to.
12391 if (getLangOpts().HLSL)
12392 return;
12393
12394 QualType T = FD->getType();
12395 assert(T->isFunctionType() && "function decl is not of function type");
12396 const FunctionType* FT = T->castAs<FunctionType>();
12397
12398 // Set default calling convention for main()
12399 if (FT->getCallConv() != CC_C) {
12401 FD->setType(QualType(FT, 0));
12403 }
12404
12405 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12406 // In C with GNU extensions we allow main() to have non-integer return
12407 // type, but we should warn about the extension, and we disable the
12408 // implicit-return-zero rule.
12409
12410 // GCC in C mode accepts qualified 'int'.
12412 FD->setHasImplicitReturnZero(true);
12413 else {
12414 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12415 SourceRange RTRange = FD->getReturnTypeSourceRange();
12416 if (RTRange.isValid())
12417 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12418 << FixItHint::CreateReplacement(RTRange, "int");
12419 }
12420 } else {
12421 // In C and C++, main magically returns 0 if you fall off the end;
12422 // set the flag which tells us that.
12423 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12424
12425 // All the standards say that main() should return 'int'.
12427 FD->setHasImplicitReturnZero(true);
12428 else {
12429 // Otherwise, this is just a flat-out error.
12430 SourceRange RTRange = FD->getReturnTypeSourceRange();
12431 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12432 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12433 : FixItHint());
12434 FD->setInvalidDecl(true);
12435 }
12436 }
12437
12438 // Treat protoless main() as nullary.
12439 if (isa<FunctionNoProtoType>(FT)) return;
12440
12441 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12442 unsigned nparams = FTP->getNumParams();
12443 assert(FD->getNumParams() == nparams);
12444
12445 bool HasExtraParameters = (nparams > 3);
12446
12447 if (FTP->isVariadic()) {
12448 Diag(FD->getLocation(), diag::ext_variadic_main);
12449 // FIXME: if we had information about the location of the ellipsis, we
12450 // could add a FixIt hint to remove it as a parameter.
12451 }
12452
12453 // Darwin passes an undocumented fourth argument of type char**. If
12454 // other platforms start sprouting these, the logic below will start
12455 // getting shifty.
12456 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12457 HasExtraParameters = false;
12458
12459 if (HasExtraParameters) {
12460 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12461 FD->setInvalidDecl(true);
12462 nparams = 3;
12463 }
12464
12465 // FIXME: a lot of the following diagnostics would be improved
12466 // if we had some location information about types.
12467
12468 QualType CharPP =
12470 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12471
12472 for (unsigned i = 0; i < nparams; ++i) {
12473 QualType AT = FTP->getParamType(i);
12474
12475 bool mismatch = true;
12476
12478 mismatch = false;
12479 else if (Expected[i] == CharPP) {
12480 // As an extension, the following forms are okay:
12481 // char const **
12482 // char const * const *
12483 // char * const *
12484
12486 const PointerType* PT;
12487 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12488 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12490 Context.CharTy)) {
12491 qs.removeConst();
12492 mismatch = !qs.empty();
12493 }
12494 }
12495
12496 if (mismatch) {
12497 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12498 // TODO: suggest replacing given type with expected type
12499 FD->setInvalidDecl(true);
12500 }
12501 }
12502
12503 if (nparams == 1 && !FD->isInvalidDecl()) {
12504 Diag(FD->getLocation(), diag::warn_main_one_arg);
12505 }
12506
12507 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12508 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12509 FD->setInvalidDecl();
12510 }
12511}
12512
12513static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12514
12515 // Default calling convention for main and wmain is __cdecl
12516 if (FD->getName() == "main" || FD->getName() == "wmain")
12517 return false;
12518
12519 // Default calling convention for MinGW is __cdecl
12520 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12521 if (T.isWindowsGNUEnvironment())
12522 return false;
12523
12524 // Default calling convention for WinMain, wWinMain and DllMain
12525 // is __stdcall on 32 bit Windows
12526 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12527 return true;
12528
12529 return false;
12530}
12531
12533 QualType T = FD->getType();
12534 assert(T->isFunctionType() && "function decl is not of function type");
12535 const FunctionType *FT = T->castAs<FunctionType>();
12536
12537 // Set an implicit return of 'zero' if the function can return some integral,
12538 // enumeration, pointer or nullptr type.
12542 // DllMain is exempt because a return value of zero means it failed.
12543 if (FD->getName() != "DllMain")
12544 FD->setHasImplicitReturnZero(true);
12545
12546 // Explicitly specified calling conventions are applied to MSVC entry points
12547 if (!hasExplicitCallingConv(T)) {
12548 if (isDefaultStdCall(FD, *this)) {
12549 if (FT->getCallConv() != CC_X86StdCall) {
12552 FD->setType(QualType(FT, 0));
12553 }
12554 } else if (FT->getCallConv() != CC_C) {
12557 FD->setType(QualType(FT, 0));
12558 }
12559 }
12560
12561 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12562 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12563 FD->setInvalidDecl();
12564 }
12565}
12566
12568 // FIXME: Need strict checking. In C89, we need to check for
12569 // any assignment, increment, decrement, function-calls, or
12570 // commas outside of a sizeof. In C99, it's the same list,
12571 // except that the aforementioned are allowed in unevaluated
12572 // expressions. Everything else falls under the
12573 // "may accept other forms of constant expressions" exception.
12574 //
12575 // Regular C++ code will not end up here (exceptions: language extensions,
12576 // OpenCL C++ etc), so the constant expression rules there don't matter.
12577 if (Init->isValueDependent()) {
12578 assert(Init->containsErrors() &&
12579 "Dependent code should only occur in error-recovery path.");
12580 return true;
12581 }
12582 const Expr *Culprit;
12583 if (Init->isConstantInitializer(Context, false, &Culprit))
12584 return false;
12585 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12586 return true;
12587}
12588
12589namespace {
12590 // Visits an initialization expression to see if OrigDecl is evaluated in
12591 // its own initialization and throws a warning if it does.
12592 class SelfReferenceChecker
12593 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12594 Sema &S;
12595 Decl *OrigDecl;
12596 bool isRecordType;
12597 bool isPODType;
12598 bool isReferenceType;
12599
12600 bool isInitList;
12601 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12602
12603 public:
12605
12606 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12607 S(S), OrigDecl(OrigDecl) {
12608 isPODType = false;
12609 isRecordType = false;
12610 isReferenceType = false;
12611 isInitList = false;
12612 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12613 isPODType = VD->getType().isPODType(S.Context);
12614 isRecordType = VD->getType()->isRecordType();
12615 isReferenceType = VD->getType()->isReferenceType();
12616 }
12617 }
12618
12619 // For most expressions, just call the visitor. For initializer lists,
12620 // track the index of the field being initialized since fields are
12621 // initialized in order allowing use of previously initialized fields.
12622 void CheckExpr(Expr *E) {
12623 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12624 if (!InitList) {
12625 Visit(E);
12626 return;
12627 }
12628
12629 // Track and increment the index here.
12630 isInitList = true;
12631 InitFieldIndex.push_back(0);
12632 for (auto *Child : InitList->children()) {
12633 CheckExpr(cast<Expr>(Child));
12634 ++InitFieldIndex.back();
12635 }
12636 InitFieldIndex.pop_back();
12637 }
12638
12639 // Returns true if MemberExpr is checked and no further checking is needed.
12640 // Returns false if additional checking is required.
12641 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12643 Expr *Base = E;
12644 bool ReferenceField = false;
12645
12646 // Get the field members used.
12647 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12648 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12649 if (!FD)
12650 return false;
12651 Fields.push_back(FD);
12652 if (FD->getType()->isReferenceType())
12653 ReferenceField = true;
12654 Base = ME->getBase()->IgnoreParenImpCasts();
12655 }
12656
12657 // Keep checking only if the base Decl is the same.
12658 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12659 if (!DRE || DRE->getDecl() != OrigDecl)
12660 return false;
12661
12662 // A reference field can be bound to an unininitialized field.
12663 if (CheckReference && !ReferenceField)
12664 return true;
12665
12666 // Convert FieldDecls to their index number.
12667 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12668 for (const FieldDecl *I : llvm::reverse(Fields))
12669 UsedFieldIndex.push_back(I->getFieldIndex());
12670
12671 // See if a warning is needed by checking the first difference in index
12672 // numbers. If field being used has index less than the field being
12673 // initialized, then the use is safe.
12674 for (auto UsedIter = UsedFieldIndex.begin(),
12675 UsedEnd = UsedFieldIndex.end(),
12676 OrigIter = InitFieldIndex.begin(),
12677 OrigEnd = InitFieldIndex.end();
12678 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12679 if (*UsedIter < *OrigIter)
12680 return true;
12681 if (*UsedIter > *OrigIter)
12682 break;
12683 }
12684
12685 // TODO: Add a different warning which will print the field names.
12686 HandleDeclRefExpr(DRE);
12687 return true;
12688 }
12689
12690 // For most expressions, the cast is directly above the DeclRefExpr.
12691 // For conditional operators, the cast can be outside the conditional
12692 // operator if both expressions are DeclRefExpr's.
12693 void HandleValue(Expr *E) {
12694 E = E->IgnoreParens();
12695 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12696 HandleDeclRefExpr(DRE);
12697 return;
12698 }
12699
12700 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12701 Visit(CO->getCond());
12702 HandleValue(CO->getTrueExpr());
12703 HandleValue(CO->getFalseExpr());
12704 return;
12705 }
12706
12707 if (BinaryConditionalOperator *BCO =
12708 dyn_cast<BinaryConditionalOperator>(E)) {
12709 Visit(BCO->getCond());
12710 HandleValue(BCO->getFalseExpr());
12711 return;
12712 }
12713
12714 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12715 if (Expr *SE = OVE->getSourceExpr())
12716 HandleValue(SE);
12717 return;
12718 }
12719
12720 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12721 if (BO->getOpcode() == BO_Comma) {
12722 Visit(BO->getLHS());
12723 HandleValue(BO->getRHS());
12724 return;
12725 }
12726 }
12727
12728 if (isa<MemberExpr>(E)) {
12729 if (isInitList) {
12730 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12731 false /*CheckReference*/))
12732 return;
12733 }
12734
12736 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12737 // Check for static member variables and don't warn on them.
12738 if (!isa<FieldDecl>(ME->getMemberDecl()))
12739 return;
12740 Base = ME->getBase()->IgnoreParenImpCasts();
12741 }
12742 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12743 HandleDeclRefExpr(DRE);
12744 return;
12745 }
12746
12747 Visit(E);
12748 }
12749
12750 // Reference types not handled in HandleValue are handled here since all
12751 // uses of references are bad, not just r-value uses.
12752 void VisitDeclRefExpr(DeclRefExpr *E) {
12753 if (isReferenceType)
12754 HandleDeclRefExpr(E);
12755 }
12756
12757 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12758 if (E->getCastKind() == CK_LValueToRValue) {
12759 HandleValue(E->getSubExpr());
12760 return;
12761 }
12762
12763 Inherited::VisitImplicitCastExpr(E);
12764 }
12765
12766 void VisitMemberExpr(MemberExpr *E) {
12767 if (isInitList) {
12768 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12769 return;
12770 }
12771
12772 // Don't warn on arrays since they can be treated as pointers.
12773 if (E->getType()->canDecayToPointerType()) return;
12774
12775 // Warn when a non-static method call is followed by non-static member
12776 // field accesses, which is followed by a DeclRefExpr.
12777 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12778 bool Warn = (MD && !MD->isStatic());
12779 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12780 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12781 if (!isa<FieldDecl>(ME->getMemberDecl()))
12782 Warn = false;
12783 Base = ME->getBase()->IgnoreParenImpCasts();
12784 }
12785
12786 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12787 if (Warn)
12788 HandleDeclRefExpr(DRE);
12789 return;
12790 }
12791
12792 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12793 // Visit that expression.
12794 Visit(Base);
12795 }
12796
12797 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12798 Expr *Callee = E->getCallee();
12799
12800 if (isa<UnresolvedLookupExpr>(Callee))
12801 return Inherited::VisitCXXOperatorCallExpr(E);
12802
12803 Visit(Callee);
12804 for (auto Arg: E->arguments())
12805 HandleValue(Arg->IgnoreParenImpCasts());
12806 }
12807
12808 void VisitUnaryOperator(UnaryOperator *E) {
12809 // For POD record types, addresses of its own members are well-defined.
12810 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12811 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12812 if (!isPODType)
12813 HandleValue(E->getSubExpr());
12814 return;
12815 }
12816
12817 if (E->isIncrementDecrementOp()) {
12818 HandleValue(E->getSubExpr());
12819 return;
12820 }
12821
12822 Inherited::VisitUnaryOperator(E);
12823 }
12824
12825 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12826
12827 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12828 if (E->getConstructor()->isCopyConstructor()) {
12829 Expr *ArgExpr = E->getArg(0);
12830 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12831 if (ILE->getNumInits() == 1)
12832 ArgExpr = ILE->getInit(0);
12833 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12834 if (ICE->getCastKind() == CK_NoOp)
12835 ArgExpr = ICE->getSubExpr();
12836 HandleValue(ArgExpr);
12837 return;
12838 }
12839 Inherited::VisitCXXConstructExpr(E);
12840 }
12841
12842 void VisitCallExpr(CallExpr *E) {
12843 // Treat std::move as a use.
12844 if (E->isCallToStdMove()) {
12845 HandleValue(E->getArg(0));
12846 return;
12847 }
12848
12849 Inherited::VisitCallExpr(E);
12850 }
12851
12852 void VisitBinaryOperator(BinaryOperator *E) {
12853 if (E->isCompoundAssignmentOp()) {
12854 HandleValue(E->getLHS());
12855 Visit(E->getRHS());
12856 return;
12857 }
12858
12859 Inherited::VisitBinaryOperator(E);
12860 }
12861
12862 // A custom visitor for BinaryConditionalOperator is needed because the
12863 // regular visitor would check the condition and true expression separately
12864 // but both point to the same place giving duplicate diagnostics.
12865 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12866 Visit(E->getCond());
12867 Visit(E->getFalseExpr());
12868 }
12869
12870 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12871 Decl* ReferenceDecl = DRE->getDecl();
12872 if (OrigDecl != ReferenceDecl) return;
12873 unsigned diag;
12874 if (isReferenceType) {
12875 diag = diag::warn_uninit_self_reference_in_reference_init;
12876 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12877 diag = diag::warn_static_self_reference_in_init;
12878 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12879 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12880 DRE->getDecl()->getType()->isRecordType()) {
12881 diag = diag::warn_uninit_self_reference_in_init;
12882 } else {
12883 // Local variables will be handled by the CFG analysis.
12884 return;
12885 }
12886
12887 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12888 S.PDiag(diag)
12889 << DRE->getDecl() << OrigDecl->getLocation()
12890 << DRE->getSourceRange());
12891 }
12892 };
12893
12894 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12895 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12896 bool DirectInit) {
12897 // Parameters arguments are occassionially constructed with itself,
12898 // for instance, in recursive functions. Skip them.
12899 if (isa<ParmVarDecl>(OrigDecl))
12900 return;
12901
12902 E = E->IgnoreParens();
12903
12904 // Skip checking T a = a where T is not a record or reference type.
12905 // Doing so is a way to silence uninitialized warnings.
12906 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12907 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12908 if (ICE->getCastKind() == CK_LValueToRValue)
12909 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12910 if (DRE->getDecl() == OrigDecl)
12911 return;
12912
12913 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12914 }
12915} // end anonymous namespace
12916
12917namespace {
12918 // Simple wrapper to add the name of a variable or (if no variable is
12919 // available) a DeclarationName into a diagnostic.
12920 struct VarDeclOrName {
12921 VarDecl *VDecl;
12922 DeclarationName Name;
12923
12924 friend const Sema::SemaDiagnosticBuilder &
12925 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12926 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12927 }
12928 };
12929} // end anonymous namespace
12930
12933 TypeSourceInfo *TSI,
12935 Expr *Init) {
12936 bool IsInitCapture = !VDecl;
12937 assert((!VDecl || !VDecl->isInitCapture()) &&
12938 "init captures are expected to be deduced prior to initialization");
12939
12940 VarDeclOrName VN{VDecl, Name};
12941
12943 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12944
12945 // Diagnose auto array declarations in C23, unless it's a supported extension.
12946 if (getLangOpts().C23 && Type->isArrayType() &&
12947 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12948 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12949 << (int)Deduced->getContainedAutoType()->getKeyword()
12950 << /*in array decl*/ 23 << Range;
12951 return QualType();
12952 }
12953
12954 // C++11 [dcl.spec.auto]p3
12955 if (!Init) {
12956 assert(VDecl && "no init for init capture deduction?");
12957
12958 // Except for class argument deduction, and then for an initializing
12959 // declaration only, i.e. no static at class scope or extern.
12960 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12961 VDecl->hasExternalStorage() ||
12962 VDecl->isStaticDataMember()) {
12963 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12964 << VDecl->getDeclName() << Type;
12965 return QualType();
12966 }
12967 }
12968
12969 ArrayRef<Expr*> DeduceInits;
12970 if (Init)
12971 DeduceInits = Init;
12972
12973 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12974 if (DirectInit && PL)
12975 DeduceInits = PL->exprs();
12976
12977 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12978 assert(VDecl && "non-auto type for init capture deduction?");
12981 VDecl->getLocation(), DirectInit, Init);
12982 // FIXME: Initialization should not be taking a mutable list of inits.
12983 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
12984 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12985 InitsCopy);
12986 }
12987
12988 if (DirectInit) {
12989 if (auto *IL = dyn_cast<InitListExpr>(Init))
12990 DeduceInits = IL->inits();
12991 }
12992
12993 // Deduction only works if we have exactly one source expression.
12994 if (DeduceInits.empty()) {
12995 // It isn't possible to write this directly, but it is possible to
12996 // end up in this situation with "auto x(some_pack...);"
12997 Diag(Init->getBeginLoc(), IsInitCapture
12998 ? diag::err_init_capture_no_expression
12999 : diag::err_auto_var_init_no_expression)
13000 << VN << Type << Range;
13001 return QualType();
13002 }
13003
13004 if (DeduceInits.size() > 1) {
13005 Diag(DeduceInits[1]->getBeginLoc(),
13006 IsInitCapture ? diag::err_init_capture_multiple_expressions
13007 : diag::err_auto_var_init_multiple_expressions)
13008 << VN << Type << Range;
13009 return QualType();
13010 }
13011
13012 Expr *DeduceInit = DeduceInits[0];
13013 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13014 Diag(Init->getBeginLoc(), IsInitCapture
13015 ? diag::err_init_capture_paren_braces
13016 : diag::err_auto_var_init_paren_braces)
13017 << isa<InitListExpr>(Init) << VN << Type << Range;
13018 return QualType();
13019 }
13020
13021 // Expressions default to 'id' when we're in a debugger.
13022 bool DefaultedAnyToId = false;
13023 if (getLangOpts().DebuggerCastResultToId &&
13024 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13026 if (Result.isInvalid()) {
13027 return QualType();
13028 }
13029 Init = Result.get();
13030 DefaultedAnyToId = true;
13031 }
13032
13033 // C++ [dcl.decomp]p1:
13034 // If the assignment-expression [...] has array type A and no ref-qualifier
13035 // is present, e has type cv A
13036 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13038 DeduceInit->getType()->isConstantArrayType())
13039 return Context.getQualifiedType(DeduceInit->getType(),
13040 Type.getQualifiers());
13041
13043 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13045 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13048 if (!IsInitCapture)
13049 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13050 else if (isa<InitListExpr>(Init))
13052 diag::err_init_capture_deduction_failure_from_init_list)
13053 << VN
13054 << (DeduceInit->getType().isNull() ? TSI->getType()
13055 : DeduceInit->getType())
13056 << DeduceInit->getSourceRange();
13057 else
13058 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13059 << VN << TSI->getType()
13060 << (DeduceInit->getType().isNull() ? TSI->getType()
13061 : DeduceInit->getType())
13062 << DeduceInit->getSourceRange();
13063 }
13064
13065 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13066 // 'id' instead of a specific object type prevents most of our usual
13067 // checks.
13068 // We only want to warn outside of template instantiations, though:
13069 // inside a template, the 'id' could have come from a parameter.
13070 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13071 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13073 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13074 }
13075
13076 return DeducedType;
13077}
13078
13080 Expr *Init) {
13081 assert(!Init || !Init->containsErrors());
13083 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13084 VDecl->getSourceRange(), DirectInit, Init);
13085 if (DeducedType.isNull()) {
13086 VDecl->setInvalidDecl();
13087 return true;
13088 }
13089
13090 VDecl->setType(DeducedType);
13091 assert(VDecl->isLinkageValid());
13092
13093 // In ARC, infer lifetime.
13094 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13095 VDecl->setInvalidDecl();
13096
13097 if (getLangOpts().OpenCL)
13099
13100 // If this is a redeclaration, check that the type we just deduced matches
13101 // the previously declared type.
13102 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13103 // We never need to merge the type, because we cannot form an incomplete
13104 // array of auto, nor deduce such a type.
13105 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13106 }
13107
13108 // Check the deduced type is valid for a variable declaration.
13110 return VDecl->isInvalidDecl();
13111}
13112
13115 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13116 Init = EWC->getSubExpr();
13117
13118 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13119 Init = CE->getSubExpr();
13120
13121 QualType InitType = Init->getType();
13124 "shouldn't be called if type doesn't have a non-trivial C struct");
13125 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13126 for (auto *I : ILE->inits()) {
13127 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13128 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13129 continue;
13130 SourceLocation SL = I->getExprLoc();
13132 }
13133 return;
13134 }
13135
13136 if (isa<ImplicitValueInitExpr>(Init)) {
13139 NTCUK_Init);
13140 } else {
13141 // Assume all other explicit initializers involving copying some existing
13142 // object.
13143 // TODO: ignore any explicit initializers where we can guarantee
13144 // copy-elision.
13147 }
13148}
13149
13150namespace {
13151
13152bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13153 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13154 // in the source code or implicitly by the compiler if it is in a union
13155 // defined in a system header and has non-trivial ObjC ownership
13156 // qualifications. We don't want those fields to participate in determining
13157 // whether the containing union is non-trivial.
13158 return FD->hasAttr<UnavailableAttr>();
13159}
13160
13161struct DiagNonTrivalCUnionDefaultInitializeVisitor
13162 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13163 void> {
13164 using Super =
13165 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13166 void>;
13167
13168 DiagNonTrivalCUnionDefaultInitializeVisitor(
13169 QualType OrigTy, SourceLocation OrigLoc,
13170 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13171 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13172
13173 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13174 const FieldDecl *FD, bool InNonTrivialUnion) {
13175 if (const auto *AT = S.Context.getAsArrayType(QT))
13176 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13177 InNonTrivialUnion);
13178 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13179 }
13180
13181 void visitARCStrong(QualType QT, const FieldDecl *FD,
13182 bool InNonTrivialUnion) {
13183 if (InNonTrivialUnion)
13184 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13185 << 1 << 0 << QT << FD->getName();
13186 }
13187
13188 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13189 if (InNonTrivialUnion)
13190 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13191 << 1 << 0 << QT << FD->getName();
13192 }
13193
13194 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13195 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13196 if (RD->isUnion()) {
13197 if (OrigLoc.isValid()) {
13198 bool IsUnion = false;
13199 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13200 IsUnion = OrigRD->isUnion();
13201 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13202 << 0 << OrigTy << IsUnion << UseContext;
13203 // Reset OrigLoc so that this diagnostic is emitted only once.
13204 OrigLoc = SourceLocation();
13205 }
13206 InNonTrivialUnion = true;
13207 }
13208
13209 if (InNonTrivialUnion)
13210 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13211 << 0 << 0 << QT.getUnqualifiedType() << "";
13212
13213 for (const FieldDecl *FD : RD->fields())
13214 if (!shouldIgnoreForRecordTriviality(FD))
13215 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13216 }
13217
13218 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13219
13220 // The non-trivial C union type or the struct/union type that contains a
13221 // non-trivial C union.
13222 QualType OrigTy;
13223 SourceLocation OrigLoc;
13225 Sema &S;
13226};
13227
13228struct DiagNonTrivalCUnionDestructedTypeVisitor
13229 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13230 using Super =
13232
13233 DiagNonTrivalCUnionDestructedTypeVisitor(
13234 QualType OrigTy, SourceLocation OrigLoc,
13235 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13236 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13237
13238 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13239 const FieldDecl *FD, bool InNonTrivialUnion) {
13240 if (const auto *AT = S.Context.getAsArrayType(QT))
13241 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13242 InNonTrivialUnion);
13243 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13244 }
13245
13246 void visitARCStrong(QualType QT, const FieldDecl *FD,
13247 bool InNonTrivialUnion) {
13248 if (InNonTrivialUnion)
13249 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13250 << 1 << 1 << QT << FD->getName();
13251 }
13252
13253 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13254 if (InNonTrivialUnion)
13255 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13256 << 1 << 1 << QT << FD->getName();
13257 }
13258
13259 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13260 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13261 if (RD->isUnion()) {
13262 if (OrigLoc.isValid()) {
13263 bool IsUnion = false;
13264 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13265 IsUnion = OrigRD->isUnion();
13266 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13267 << 1 << OrigTy << IsUnion << UseContext;
13268 // Reset OrigLoc so that this diagnostic is emitted only once.
13269 OrigLoc = SourceLocation();
13270 }
13271 InNonTrivialUnion = true;
13272 }
13273
13274 if (InNonTrivialUnion)
13275 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13276 << 0 << 1 << QT.getUnqualifiedType() << "";
13277
13278 for (const FieldDecl *FD : RD->fields())
13279 if (!shouldIgnoreForRecordTriviality(FD))
13280 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13281 }
13282
13283 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13284 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13285 bool InNonTrivialUnion) {}
13286
13287 // The non-trivial C union type or the struct/union type that contains a
13288 // non-trivial C union.
13289 QualType OrigTy;
13290 SourceLocation OrigLoc;
13292 Sema &S;
13293};
13294
13295struct DiagNonTrivalCUnionCopyVisitor
13296 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13298
13299 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13301 Sema &S)
13302 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13303
13304 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13305 const FieldDecl *FD, bool InNonTrivialUnion) {
13306 if (const auto *AT = S.Context.getAsArrayType(QT))
13307 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13308 InNonTrivialUnion);
13309 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13310 }
13311
13312 void visitARCStrong(QualType QT, const FieldDecl *FD,
13313 bool InNonTrivialUnion) {
13314 if (InNonTrivialUnion)
13315 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13316 << 1 << 2 << QT << FD->getName();
13317 }
13318
13319 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13320 if (InNonTrivialUnion)
13321 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13322 << 1 << 2 << QT << FD->getName();
13323 }
13324
13325 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13326 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13327 if (RD->isUnion()) {
13328 if (OrigLoc.isValid()) {
13329 bool IsUnion = false;
13330 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13331 IsUnion = OrigRD->isUnion();
13332 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13333 << 2 << OrigTy << IsUnion << UseContext;
13334 // Reset OrigLoc so that this diagnostic is emitted only once.
13335 OrigLoc = SourceLocation();
13336 }
13337 InNonTrivialUnion = true;
13338 }
13339
13340 if (InNonTrivialUnion)
13341 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13342 << 0 << 2 << QT.getUnqualifiedType() << "";
13343
13344 for (const FieldDecl *FD : RD->fields())
13345 if (!shouldIgnoreForRecordTriviality(FD))
13346 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13347 }
13348
13349 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13350 const FieldDecl *FD, bool InNonTrivialUnion) {}
13351 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13352 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13353 bool InNonTrivialUnion) {}
13354
13355 // The non-trivial C union type or the struct/union type that contains a
13356 // non-trivial C union.
13357 QualType OrigTy;
13358 SourceLocation OrigLoc;
13360 Sema &S;
13361};
13362
13363} // namespace
13364
13366 NonTrivialCUnionContext UseContext,
13367 unsigned NonTrivialKind) {
13371 "shouldn't be called if type doesn't have a non-trivial C union");
13372
13373 if ((NonTrivialKind & NTCUK_Init) &&
13375 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13376 .visit(QT, nullptr, false);
13377 if ((NonTrivialKind & NTCUK_Destruct) &&
13379 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13380 .visit(QT, nullptr, false);
13381 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13382 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13383 .visit(QT, nullptr, false);
13384}
13385
13387 // If there is no declaration, there was an error parsing it. Just ignore
13388 // the initializer.
13389 if (!RealDecl) {
13390 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13391 return;
13392 }
13393
13394 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13395 if (!Method->isInvalidDecl()) {
13396 // Pure-specifiers are handled in ActOnPureSpecifier.
13397 Diag(Method->getLocation(), diag::err_member_function_initialization)
13398 << Method->getDeclName() << Init->getSourceRange();
13399 Method->setInvalidDecl();
13400 }
13401 return;
13402 }
13403
13404 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13405 if (!VDecl) {
13406 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13407 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13408 RealDecl->setInvalidDecl();
13409 return;
13410 }
13411
13412 if (VDecl->isInvalidDecl()) {
13414 SmallVector<Expr *> SubExprs;
13415 if (Res.isUsable())
13416 SubExprs.push_back(Res.get());
13417 ExprResult Recovery =
13418 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);
13419 if (Expr *E = Recovery.get())
13420 VDecl->setInit(E);
13421 return;
13422 }
13423
13424 // WebAssembly tables can't be used to initialise a variable.
13425 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13426 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13427 VDecl->setInvalidDecl();
13428 return;
13429 }
13430
13431 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13432 if (VDecl->getType()->isUndeducedType()) {
13433 // Attempt typo correction early so that the type of the init expression can
13434 // be deduced based on the chosen correction if the original init contains a
13435 // TypoExpr.
13437 if (!Res.isUsable()) {
13438 // There are unresolved typos in Init, just drop them.
13439 // FIXME: improve the recovery strategy to preserve the Init.
13440 RealDecl->setInvalidDecl();
13441 return;
13442 }
13443 if (Res.get()->containsErrors()) {
13444 // Invalidate the decl as we don't know the type for recovery-expr yet.
13445 RealDecl->setInvalidDecl();
13446 VDecl->setInit(Res.get());
13447 return;
13448 }
13449 Init = Res.get();
13450
13452 return;
13453 }
13454
13455 // dllimport cannot be used on variable definitions.
13456 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13457 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13458 VDecl->setInvalidDecl();
13459 return;
13460 }
13461
13462 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13463 // the identifier has external or internal linkage, the declaration shall
13464 // have no initializer for the identifier.
13465 // C++14 [dcl.init]p5 is the same restriction for C++.
13466 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13467 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13468 VDecl->setInvalidDecl();
13469 return;
13470 }
13471
13472 if (!VDecl->getType()->isDependentType()) {
13473 // A definition must end up with a complete type, which means it must be
13474 // complete with the restriction that an array type might be completed by
13475 // the initializer; note that later code assumes this restriction.
13476 QualType BaseDeclType = VDecl->getType();
13477 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13478 BaseDeclType = Array->getElementType();
13479 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13480 diag::err_typecheck_decl_incomplete_type)) {
13481 RealDecl->setInvalidDecl();
13482 return;
13483 }
13484
13485 // The variable can not have an abstract class type.
13486 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13487 diag::err_abstract_type_in_decl,
13489 VDecl->setInvalidDecl();
13490 }
13491
13492 // C++ [module.import/6] external definitions are not permitted in header
13493 // units.
13494 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13495 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13496 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13497 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13499 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13500 VDecl->setInvalidDecl();
13501 }
13502
13503 // If adding the initializer will turn this declaration into a definition,
13504 // and we already have a definition for this variable, diagnose or otherwise
13505 // handle the situation.
13506 if (VarDecl *Def = VDecl->getDefinition())
13507 if (Def != VDecl &&
13508 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13510 checkVarDeclRedefinition(Def, VDecl))
13511 return;
13512
13513 if (getLangOpts().CPlusPlus) {
13514 // C++ [class.static.data]p4
13515 // If a static data member is of const integral or const
13516 // enumeration type, its declaration in the class definition can
13517 // specify a constant-initializer which shall be an integral
13518 // constant expression (5.19). In that case, the member can appear
13519 // in integral constant expressions. The member shall still be
13520 // defined in a namespace scope if it is used in the program and the
13521 // namespace scope definition shall not contain an initializer.
13522 //
13523 // We already performed a redefinition check above, but for static
13524 // data members we also need to check whether there was an in-class
13525 // declaration with an initializer.
13526 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13527 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13528 << VDecl->getDeclName();
13529 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13530 diag::note_previous_initializer)
13531 << 0;
13532 return;
13533 }
13534
13535 if (VDecl->hasLocalStorage())
13537
13539 VDecl->setInvalidDecl();
13540 return;
13541 }
13542 }
13543
13544 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13545 // a kernel function cannot be initialized."
13546 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13547 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13548 VDecl->setInvalidDecl();
13549 return;
13550 }
13551
13552 // The LoaderUninitialized attribute acts as a definition (of undef).
13553 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13554 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13555 VDecl->setInvalidDecl();
13556 return;
13557 }
13558
13559 // Get the decls type and save a reference for later, since
13560 // CheckInitializerTypes may change it.
13561 QualType DclT = VDecl->getType(), SavT = DclT;
13562
13563 // Expressions default to 'id' when we're in a debugger
13564 // and we are assigning it to a variable of Objective-C pointer type.
13565 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13566 Init->getType() == Context.UnknownAnyTy) {
13568 if (!Result.isUsable()) {
13569 VDecl->setInvalidDecl();
13570 return;
13571 }
13572 Init = Result.get();
13573 }
13574
13575 // Perform the initialization.
13576 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13577 bool IsParenListInit = false;
13578 if (!VDecl->isInvalidDecl()) {
13581 VDecl->getLocation(), DirectInit, Init);
13582
13583 MultiExprArg Args = Init;
13584 if (CXXDirectInit)
13585 Args = MultiExprArg(CXXDirectInit->getExprs(),
13586 CXXDirectInit->getNumExprs());
13587
13588 // Try to correct any TypoExprs in the initialization arguments.
13589 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13591 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13592 [this, Entity, Kind](Expr *E) {
13593 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13594 return Init.Failed() ? ExprError() : E;
13595 });
13596 if (!Res.isUsable()) {
13597 VDecl->setInvalidDecl();
13598 } else if (Res.get() != Args[Idx]) {
13599 Args[Idx] = Res.get();
13600 }
13601 }
13602 if (VDecl->isInvalidDecl())
13603 return;
13604
13605 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13606 /*TopLevelOfInitList=*/false,
13607 /*TreatUnavailableAsInvalid=*/false);
13608 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13609 if (!Result.isUsable()) {
13610 // If the provided initializer fails to initialize the var decl,
13611 // we attach a recovery expr for better recovery.
13612 auto RecoveryExpr =
13613 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13614 if (RecoveryExpr.get())
13615 VDecl->setInit(RecoveryExpr.get());
13616 // In general, for error recovery purposes, the initializer doesn't play
13617 // part in the valid bit of the declaration. There are a few exceptions:
13618 // 1) if the var decl has a deduced auto type, and the type cannot be
13619 // deduced by an invalid initializer;
13620 // 2) if the var decl is a decomposition decl with a non-deduced type,
13621 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13622 // Case 1) was already handled elsewhere.
13623 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13624 VDecl->setInvalidDecl();
13625 return;
13626 }
13627
13628 Init = Result.getAs<Expr>();
13629 IsParenListInit = !InitSeq.steps().empty() &&
13630 InitSeq.step_begin()->Kind ==
13632 QualType VDeclType = VDecl->getType();
13633 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
13634 !VDeclType->isDependentType() &&
13635 Context.getAsIncompleteArrayType(VDeclType) &&
13637 // Bail out if it is not possible to deduce array size from the
13638 // initializer.
13639 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13640 << VDeclType;
13641 VDecl->setInvalidDecl();
13642 return;
13643 }
13644 }
13645
13646 // Check for self-references within variable initializers.
13647 // Variables declared within a function/method body (except for references)
13648 // are handled by a dataflow analysis.
13649 // This is undefined behavior in C++, but valid in C.
13650 if (getLangOpts().CPlusPlus)
13651 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13652 VDecl->getType()->isReferenceType())
13653 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13654
13655 // If the type changed, it means we had an incomplete type that was
13656 // completed by the initializer. For example:
13657 // int ary[] = { 1, 3, 5 };
13658 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13659 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13660 VDecl->setType(DclT);
13661
13662 if (!VDecl->isInvalidDecl()) {
13663 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13664
13665 if (VDecl->hasAttr<BlocksAttr>())
13666 ObjC().checkRetainCycles(VDecl, Init);
13667
13668 // It is safe to assign a weak reference into a strong variable.
13669 // Although this code can still have problems:
13670 // id x = self.weakProp;
13671 // id y = self.weakProp;
13672 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13673 // paths through the function. This should be revisited if
13674 // -Wrepeated-use-of-weak is made flow-sensitive.
13675 if (FunctionScopeInfo *FSI = getCurFunction())
13676 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13678 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13679 Init->getBeginLoc()))
13680 FSI->markSafeWeakUse(Init);
13681 }
13682
13683 // The initialization is usually a full-expression.
13684 //
13685 // FIXME: If this is a braced initialization of an aggregate, it is not
13686 // an expression, and each individual field initializer is a separate
13687 // full-expression. For instance, in:
13688 //
13689 // struct Temp { ~Temp(); };
13690 // struct S { S(Temp); };
13691 // struct T { S a, b; } t = { Temp(), Temp() }
13692 //
13693 // we should destroy the first Temp before constructing the second.
13696 /*DiscardedValue*/ false, VDecl->isConstexpr());
13697 if (!Result.isUsable()) {
13698 VDecl->setInvalidDecl();
13699 return;
13700 }
13701 Init = Result.get();
13702
13703 // Attach the initializer to the decl.
13704 VDecl->setInit(Init);
13705
13706 if (VDecl->isLocalVarDecl()) {
13707 // Don't check the initializer if the declaration is malformed.
13708 if (VDecl->isInvalidDecl()) {
13709 // do nothing
13710
13711 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13712 // This is true even in C++ for OpenCL.
13713 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13715
13716 // Otherwise, C++ does not restrict the initializer.
13717 } else if (getLangOpts().CPlusPlus) {
13718 // do nothing
13719
13720 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13721 // static storage duration shall be constant expressions or string literals.
13722 } else if (VDecl->getStorageClass() == SC_Static) {
13724
13725 // C89 is stricter than C99 for aggregate initializers.
13726 // C89 6.5.7p3: All the expressions [...] in an initializer list
13727 // for an object that has aggregate or union type shall be
13728 // constant expressions.
13729 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13730 isa<InitListExpr>(Init)) {
13731 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13732 }
13733
13734 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13735 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13736 if (VDecl->hasLocalStorage())
13737 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13738 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13739 VDecl->getLexicalDeclContext()->isRecord()) {
13740 // This is an in-class initialization for a static data member, e.g.,
13741 //
13742 // struct S {
13743 // static const int value = 17;
13744 // };
13745
13746 // C++ [class.mem]p4:
13747 // A member-declarator can contain a constant-initializer only
13748 // if it declares a static member (9.4) of const integral or
13749 // const enumeration type, see 9.4.2.
13750 //
13751 // C++11 [class.static.data]p3:
13752 // If a non-volatile non-inline const static data member is of integral
13753 // or enumeration type, its declaration in the class definition can
13754 // specify a brace-or-equal-initializer in which every initializer-clause
13755 // that is an assignment-expression is a constant expression. A static
13756 // data member of literal type can be declared in the class definition
13757 // with the constexpr specifier; if so, its declaration shall specify a
13758 // brace-or-equal-initializer in which every initializer-clause that is
13759 // an assignment-expression is a constant expression.
13760
13761 // Do nothing on dependent types.
13762 if (DclT->isDependentType()) {
13763
13764 // Allow any 'static constexpr' members, whether or not they are of literal
13765 // type. We separately check that every constexpr variable is of literal
13766 // type.
13767 } else if (VDecl->isConstexpr()) {
13768
13769 // Require constness.
13770 } else if (!DclT.isConstQualified()) {
13771 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13772 << Init->getSourceRange();
13773 VDecl->setInvalidDecl();
13774
13775 // We allow integer constant expressions in all cases.
13776 } else if (DclT->isIntegralOrEnumerationType()) {
13777 // Check whether the expression is a constant expression.
13780 // In C++11, a non-constexpr const static data member with an
13781 // in-class initializer cannot be volatile.
13782 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13783 else if (Init->isValueDependent())
13784 ; // Nothing to check.
13785 else if (Init->isIntegerConstantExpr(Context, &Loc))
13786 ; // Ok, it's an ICE!
13787 else if (Init->getType()->isScopedEnumeralType() &&
13788 Init->isCXX11ConstantExpr(Context))
13789 ; // Ok, it is a scoped-enum constant expression.
13790 else if (Init->isEvaluatable(Context)) {
13791 // If we can constant fold the initializer through heroics, accept it,
13792 // but report this as a use of an extension for -pedantic.
13793 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13794 << Init->getSourceRange();
13795 } else {
13796 // Otherwise, this is some crazy unknown case. Report the issue at the
13797 // location provided by the isIntegerConstantExpr failed check.
13798 Diag(Loc, diag::err_in_class_initializer_non_constant)
13799 << Init->getSourceRange();
13800 VDecl->setInvalidDecl();
13801 }
13802
13803 // We allow foldable floating-point constants as an extension.
13804 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13805 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13806 // it anyway and provide a fixit to add the 'constexpr'.
13807 if (getLangOpts().CPlusPlus11) {
13808 Diag(VDecl->getLocation(),
13809 diag::ext_in_class_initializer_float_type_cxx11)
13810 << DclT << Init->getSourceRange();
13811 Diag(VDecl->getBeginLoc(),
13812 diag::note_in_class_initializer_float_type_cxx11)
13813 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13814 } else {
13815 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13816 << DclT << Init->getSourceRange();
13817
13818 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13819 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13820 << Init->getSourceRange();
13821 VDecl->setInvalidDecl();
13822 }
13823 }
13824
13825 // Suggest adding 'constexpr' in C++11 for literal types.
13826 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13827 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13828 << DclT << Init->getSourceRange()
13829 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13830 VDecl->setConstexpr(true);
13831
13832 } else {
13833 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13834 << DclT << Init->getSourceRange();
13835 VDecl->setInvalidDecl();
13836 }
13837 } else if (VDecl->isFileVarDecl()) {
13838 // In C, extern is typically used to avoid tentative definitions when
13839 // declaring variables in headers, but adding an initializer makes it a
13840 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13841 // In C++, extern is often used to give implicitly static const variables
13842 // external linkage, so don't warn in that case. If selectany is present,
13843 // this might be header code intended for C and C++ inclusion, so apply the
13844 // C++ rules.
13845 if (VDecl->getStorageClass() == SC_Extern &&
13846 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13848 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13850 Diag(VDecl->getLocation(), diag::warn_extern_init);
13851
13852 // In Microsoft C++ mode, a const variable defined in namespace scope has
13853 // external linkage by default if the variable is declared with
13854 // __declspec(dllexport).
13857 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13858 VDecl->setStorageClass(SC_Extern);
13859
13860 // C99 6.7.8p4. All file scoped initializers need to be constant.
13861 // Avoid duplicate diagnostics for constexpr variables.
13862 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13863 !VDecl->isConstexpr())
13865 }
13866
13867 QualType InitType = Init->getType();
13868 if (!InitType.isNull() &&
13872
13873 // We will represent direct-initialization similarly to copy-initialization:
13874 // int x(1); -as-> int x = 1;
13875 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13876 //
13877 // Clients that want to distinguish between the two forms, can check for
13878 // direct initializer using VarDecl::getInitStyle().
13879 // A major benefit is that clients that don't particularly care about which
13880 // exactly form was it (like the CodeGen) can handle both cases without
13881 // special case code.
13882
13883 // C++ 8.5p11:
13884 // The form of initialization (using parentheses or '=') is generally
13885 // insignificant, but does matter when the entity being initialized has a
13886 // class type.
13887 if (CXXDirectInit) {
13888 assert(DirectInit && "Call-style initializer must be direct init.");
13889 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13891 } else if (DirectInit) {
13892 // This must be list-initialization. No other way is direct-initialization.
13894 }
13895
13896 if (LangOpts.OpenMP &&
13897 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13898 VDecl->isFileVarDecl())
13899 DeclsToCheckForDeferredDiags.insert(VDecl);
13901}
13902
13904 // Our main concern here is re-establishing invariants like "a
13905 // variable's type is either dependent or complete".
13906 if (!D || D->isInvalidDecl()) return;
13907
13908 VarDecl *VD = dyn_cast<VarDecl>(D);
13909 if (!VD) return;
13910
13911 // Bindings are not usable if we can't make sense of the initializer.
13912 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13913 for (auto *BD : DD->bindings())
13914 BD->setInvalidDecl();
13915
13916 // Auto types are meaningless if we can't make sense of the initializer.
13917 if (VD->getType()->isUndeducedType()) {
13918 D->setInvalidDecl();
13919 return;
13920 }
13921
13922 QualType Ty = VD->getType();
13923 if (Ty->isDependentType()) return;
13924
13925 // Require a complete type.
13928 diag::err_typecheck_decl_incomplete_type)) {
13929 VD->setInvalidDecl();
13930 return;
13931 }
13932
13933 // Require a non-abstract type.
13934 if (RequireNonAbstractType(VD->getLocation(), Ty,
13935 diag::err_abstract_type_in_decl,
13937 VD->setInvalidDecl();
13938 return;
13939 }
13940
13941 // Don't bother complaining about constructors or destructors,
13942 // though.
13943}
13944
13946 // If there is no declaration, there was an error parsing it. Just ignore it.
13947 if (!RealDecl)
13948 return;
13949
13950 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13951 QualType Type = Var->getType();
13952
13953 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13954 if (isa<DecompositionDecl>(RealDecl)) {
13955 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13956 Var->setInvalidDecl();
13957 return;
13958 }
13959
13960 if (Type->isUndeducedType() &&
13961 DeduceVariableDeclarationType(Var, false, nullptr))
13962 return;
13963
13964 // C++11 [class.static.data]p3: A static data member can be declared with
13965 // the constexpr specifier; if so, its declaration shall specify
13966 // a brace-or-equal-initializer.
13967 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13968 // the definition of a variable [...] or the declaration of a static data
13969 // member.
13970 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13971 !Var->isThisDeclarationADemotedDefinition()) {
13972 if (Var->isStaticDataMember()) {
13973 // C++1z removes the relevant rule; the in-class declaration is always
13974 // a definition there.
13975 if (!getLangOpts().CPlusPlus17 &&
13977 Diag(Var->getLocation(),
13978 diag::err_constexpr_static_mem_var_requires_init)
13979 << Var;
13980 Var->setInvalidDecl();
13981 return;
13982 }
13983 } else {
13984 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13985 Var->setInvalidDecl();
13986 return;
13987 }
13988 }
13989
13990 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13991 // be initialized.
13992 if (!Var->isInvalidDecl() &&
13993 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13994 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13995 bool HasConstExprDefaultConstructor = false;
13996 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13997 for (auto *Ctor : RD->ctors()) {
13998 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13999 Ctor->getMethodQualifiers().getAddressSpace() ==
14001 HasConstExprDefaultConstructor = true;
14002 }
14003 }
14004 }
14005 if (!HasConstExprDefaultConstructor) {
14006 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14007 Var->setInvalidDecl();
14008 return;
14009 }
14010 }
14011
14012 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14013 if (Var->getStorageClass() == SC_Extern) {
14014 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14015 << Var;
14016 Var->setInvalidDecl();
14017 return;
14018 }
14019 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14020 diag::err_typecheck_decl_incomplete_type)) {
14021 Var->setInvalidDecl();
14022 return;
14023 }
14024 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14025 if (!RD->hasTrivialDefaultConstructor()) {
14026 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14027 Var->setInvalidDecl();
14028 return;
14029 }
14030 }
14031 // The declaration is uninitialized, no need for further checks.
14032 return;
14033 }
14034
14035 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14036 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14037 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14038 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14040
14041
14042 switch (DefKind) {
14044 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14045 break;
14046
14047 // We have an out-of-line definition of a static data member
14048 // that has an in-class initializer, so we type-check this like
14049 // a declaration.
14050 //
14051 [[fallthrough]];
14052
14054 // It's only a declaration.
14055
14056 // Block scope. C99 6.7p7: If an identifier for an object is
14057 // declared with no linkage (C99 6.2.2p6), the type for the
14058 // object shall be complete.
14059 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14060 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14061 RequireCompleteType(Var->getLocation(), Type,
14062 diag::err_typecheck_decl_incomplete_type))
14063 Var->setInvalidDecl();
14064
14065 // Make sure that the type is not abstract.
14066 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14067 RequireNonAbstractType(Var->getLocation(), Type,
14068 diag::err_abstract_type_in_decl,
14070 Var->setInvalidDecl();
14071 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14072 Var->getStorageClass() == SC_PrivateExtern) {
14073 Diag(Var->getLocation(), diag::warn_private_extern);
14074 Diag(Var->getLocation(), diag::note_private_extern);
14075 }
14076
14078 !Var->isInvalidDecl())
14079 ExternalDeclarations.push_back(Var);
14080
14081 return;
14082
14084 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14085 // object that has file scope without an initializer, and without a
14086 // storage-class specifier or with the storage-class specifier "static",
14087 // constitutes a tentative definition. Note: A tentative definition with
14088 // external linkage is valid (C99 6.2.2p5).
14089 if (!Var->isInvalidDecl()) {
14090 if (const IncompleteArrayType *ArrayT
14093 Var->getLocation(), ArrayT->getElementType(),
14094 diag::err_array_incomplete_or_sizeless_type))
14095 Var->setInvalidDecl();
14096 } else if (Var->getStorageClass() == SC_Static) {
14097 // C99 6.9.2p3: If the declaration of an identifier for an object is
14098 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14099 // declared type shall not be an incomplete type.
14100 // NOTE: code such as the following
14101 // static struct s;
14102 // struct s { int a; };
14103 // is accepted by gcc. Hence here we issue a warning instead of
14104 // an error and we do not invalidate the static declaration.
14105 // NOTE: to avoid multiple warnings, only check the first declaration.
14106 if (Var->isFirstDecl())
14107 RequireCompleteType(Var->getLocation(), Type,
14108 diag::ext_typecheck_decl_incomplete_type);
14109 }
14110 }
14111
14112 // Record the tentative definition; we're done.
14113 if (!Var->isInvalidDecl())
14115 return;
14116 }
14117
14118 // Provide a specific diagnostic for uninitialized variable
14119 // definitions with incomplete array type.
14120 if (Type->isIncompleteArrayType()) {
14121 if (Var->isConstexpr())
14122 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14123 << Var;
14124 else
14125 Diag(Var->getLocation(),
14126 diag::err_typecheck_incomplete_array_needs_initializer);
14127 Var->setInvalidDecl();
14128 return;
14129 }
14130
14131 // Provide a specific diagnostic for uninitialized variable
14132 // definitions with reference type.
14133 if (Type->isReferenceType()) {
14134 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14135 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14136 return;
14137 }
14138
14139 // Do not attempt to type-check the default initializer for a
14140 // variable with dependent type.
14141 if (Type->isDependentType())
14142 return;
14143
14144 if (Var->isInvalidDecl())
14145 return;
14146
14147 if (!Var->hasAttr<AliasAttr>()) {
14148 if (RequireCompleteType(Var->getLocation(),
14150 diag::err_typecheck_decl_incomplete_type)) {
14151 Var->setInvalidDecl();
14152 return;
14153 }
14154 } else {
14155 return;
14156 }
14157
14158 // The variable can not have an abstract class type.
14159 if (RequireNonAbstractType(Var->getLocation(), Type,
14160 diag::err_abstract_type_in_decl,
14162 Var->setInvalidDecl();
14163 return;
14164 }
14165
14166 // Check for jumps past the implicit initializer. C++0x
14167 // clarifies that this applies to a "variable with automatic
14168 // storage duration", not a "local variable".
14169 // C++11 [stmt.dcl]p3
14170 // A program that jumps from a point where a variable with automatic
14171 // storage duration is not in scope to a point where it is in scope is
14172 // ill-formed unless the variable has scalar type, class type with a
14173 // trivial default constructor and a trivial destructor, a cv-qualified
14174 // version of one of these types, or an array of one of the preceding
14175 // types and is declared without an initializer.
14176 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14177 if (const RecordType *Record
14179 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14180 // Mark the function (if we're in one) for further checking even if the
14181 // looser rules of C++11 do not require such checks, so that we can
14182 // diagnose incompatibilities with C++98.
14183 if (!CXXRecord->isPOD())
14185 }
14186 }
14187 // In OpenCL, we can't initialize objects in the __local address space,
14188 // even implicitly, so don't synthesize an implicit initializer.
14189 if (getLangOpts().OpenCL &&
14190 Var->getType().getAddressSpace() == LangAS::opencl_local)
14191 return;
14192 // C++03 [dcl.init]p9:
14193 // If no initializer is specified for an object, and the
14194 // object is of (possibly cv-qualified) non-POD class type (or
14195 // array thereof), the object shall be default-initialized; if
14196 // the object is of const-qualified type, the underlying class
14197 // type shall have a user-declared default
14198 // constructor. Otherwise, if no initializer is specified for
14199 // a non- static object, the object and its subobjects, if
14200 // any, have an indeterminate initial value); if the object
14201 // or any of its subobjects are of const-qualified type, the
14202 // program is ill-formed.
14203 // C++0x [dcl.init]p11:
14204 // If no initializer is specified for an object, the object is
14205 // default-initialized; [...].
14208 = InitializationKind::CreateDefault(Var->getLocation());
14209
14210 InitializationSequence InitSeq(*this, Entity, Kind, {});
14211 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14212
14213 if (Init.get()) {
14214 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14215 // This is important for template substitution.
14216 Var->setInitStyle(VarDecl::CallInit);
14217 } else if (Init.isInvalid()) {
14218 // If default-init fails, attach a recovery-expr initializer to track
14219 // that initialization was attempted and failed.
14220 auto RecoveryExpr =
14221 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14222 if (RecoveryExpr.get())
14223 Var->setInit(RecoveryExpr.get());
14224 }
14225
14227 }
14228}
14229
14231 // If there is no declaration, there was an error parsing it. Ignore it.
14232 if (!D)
14233 return;
14234
14235 VarDecl *VD = dyn_cast<VarDecl>(D);
14236 if (!VD) {
14237 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14238 D->setInvalidDecl();
14239 return;
14240 }
14241
14242 VD->setCXXForRangeDecl(true);
14243
14244 // for-range-declaration cannot be given a storage class specifier.
14245 int Error = -1;
14246 switch (VD->getStorageClass()) {
14247 case SC_None:
14248 break;
14249 case SC_Extern:
14250 Error = 0;
14251 break;
14252 case SC_Static:
14253 Error = 1;
14254 break;
14255 case SC_PrivateExtern:
14256 Error = 2;
14257 break;
14258 case SC_Auto:
14259 Error = 3;
14260 break;
14261 case SC_Register:
14262 Error = 4;
14263 break;
14264 }
14265
14266 // for-range-declaration cannot be given a storage class specifier con't.
14267 switch (VD->getTSCSpec()) {
14268 case TSCS_thread_local:
14269 Error = 6;
14270 break;
14271 case TSCS___thread:
14272 case TSCS__Thread_local:
14273 case TSCS_unspecified:
14274 break;
14275 }
14276
14277 if (Error != -1) {
14278 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14279 << VD << Error;
14280 D->setInvalidDecl();
14281 }
14282}
14283
14285 IdentifierInfo *Ident,
14286 ParsedAttributes &Attrs) {
14287 // C++1y [stmt.iter]p1:
14288 // A range-based for statement of the form
14289 // for ( for-range-identifier : for-range-initializer ) statement
14290 // is equivalent to
14291 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14292 DeclSpec DS(Attrs.getPool().getFactory());
14293
14294 const char *PrevSpec;
14295 unsigned DiagID;
14296 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14298
14300 D.SetIdentifier(Ident, IdentLoc);
14301 D.takeAttributes(Attrs);
14302
14303 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14304 IdentLoc);
14305 Decl *Var = ActOnDeclarator(S, D);
14306 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14308 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14309 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14310 : IdentLoc);
14311}
14312
14314 if (var->isInvalidDecl()) return;
14315
14317
14318 if (getLangOpts().OpenCL) {
14319 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14320 // initialiser
14321 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14322 !var->hasInit()) {
14323 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14324 << 1 /*Init*/;
14325 var->setInvalidDecl();
14326 return;
14327 }
14328 }
14329
14330 // In Objective-C, don't allow jumps past the implicit initialization of a
14331 // local retaining variable.
14332 if (getLangOpts().ObjC &&
14333 var->hasLocalStorage()) {
14334 switch (var->getType().getObjCLifetime()) {
14338 break;
14339
14343 break;
14344 }
14345 }
14346
14347 if (var->hasLocalStorage() &&
14348 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14350
14351 // Warn about externally-visible variables being defined without a
14352 // prior declaration. We only want to do this for global
14353 // declarations, but we also specifically need to avoid doing it for
14354 // class members because the linkage of an anonymous class can
14355 // change if it's later given a typedef name.
14356 if (var->isThisDeclarationADefinition() &&
14357 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14358 var->isExternallyVisible() && var->hasLinkage() &&
14359 !var->isInline() && !var->getDescribedVarTemplate() &&
14360 var->getStorageClass() != SC_Register &&
14361 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14362 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14363 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14364 var->getLocation())) {
14365 // Find a previous declaration that's not a definition.
14366 VarDecl *prev = var->getPreviousDecl();
14367 while (prev && prev->isThisDeclarationADefinition())
14368 prev = prev->getPreviousDecl();
14369
14370 if (!prev) {
14371 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14372 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14373 << /* variable */ 0;
14374 }
14375 }
14376
14377 // Cache the result of checking for constant initialization.
14378 std::optional<bool> CacheHasConstInit;
14379 const Expr *CacheCulprit = nullptr;
14380 auto checkConstInit = [&]() mutable {
14381 if (!CacheHasConstInit)
14382 CacheHasConstInit = var->getInit()->isConstantInitializer(
14383 Context, var->getType()->isReferenceType(), &CacheCulprit);
14384 return *CacheHasConstInit;
14385 };
14386
14387 if (var->getTLSKind() == VarDecl::TLS_Static) {
14388 if (var->getType().isDestructedType()) {
14389 // GNU C++98 edits for __thread, [basic.start.term]p3:
14390 // The type of an object with thread storage duration shall not
14391 // have a non-trivial destructor.
14392 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14394 Diag(var->getLocation(), diag::note_use_thread_local);
14395 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14396 if (!checkConstInit()) {
14397 // GNU C++98 edits for __thread, [basic.start.init]p4:
14398 // An object of thread storage duration shall not require dynamic
14399 // initialization.
14400 // FIXME: Need strict checking here.
14401 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14402 << CacheCulprit->getSourceRange();
14404 Diag(var->getLocation(), diag::note_use_thread_local);
14405 }
14406 }
14407 }
14408
14409
14410 if (!var->getType()->isStructureType() && var->hasInit() &&
14411 isa<InitListExpr>(var->getInit())) {
14412 const auto *ILE = cast<InitListExpr>(var->getInit());
14413 unsigned NumInits = ILE->getNumInits();
14414 if (NumInits > 2)
14415 for (unsigned I = 0; I < NumInits; ++I) {
14416 const auto *Init = ILE->getInit(I);
14417 if (!Init)
14418 break;
14419 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14420 if (!SL)
14421 break;
14422
14423 unsigned NumConcat = SL->getNumConcatenated();
14424 // Diagnose missing comma in string array initialization.
14425 // Do not warn when all the elements in the initializer are concatenated
14426 // together. Do not warn for macros too.
14427 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14428 bool OnlyOneMissingComma = true;
14429 for (unsigned J = I + 1; J < NumInits; ++J) {
14430 const auto *Init = ILE->getInit(J);
14431 if (!Init)
14432 break;
14433 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14434 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14435 OnlyOneMissingComma = false;
14436 break;
14437 }
14438 }
14439
14440 if (OnlyOneMissingComma) {
14442 for (unsigned i = 0; i < NumConcat - 1; ++i)
14443 Hints.push_back(FixItHint::CreateInsertion(
14444 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14445
14446 Diag(SL->getStrTokenLoc(1),
14447 diag::warn_concatenated_literal_array_init)
14448 << Hints;
14449 Diag(SL->getBeginLoc(),
14450 diag::note_concatenated_string_literal_silence);
14451 }
14452 // In any case, stop now.
14453 break;
14454 }
14455 }
14456 }
14457
14458
14459 QualType type = var->getType();
14460
14461 if (var->hasAttr<BlocksAttr>())
14463
14464 Expr *Init = var->getInit();
14465 bool GlobalStorage = var->hasGlobalStorage();
14466 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14468 bool HasConstInit = true;
14469
14470 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14471 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14472 << var;
14473
14474 // Check whether the initializer is sufficiently constant.
14475 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14476 !type->isDependentType() && Init && !Init->isValueDependent() &&
14477 (GlobalStorage || var->isConstexpr() ||
14478 var->mightBeUsableInConstantExpressions(Context))) {
14479 // If this variable might have a constant initializer or might be usable in
14480 // constant expressions, check whether or not it actually is now. We can't
14481 // do this lazily, because the result might depend on things that change
14482 // later, such as which constexpr functions happen to be defined.
14484 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14485 // Prior to C++11, in contexts where a constant initializer is required,
14486 // the set of valid constant initializers is described by syntactic rules
14487 // in [expr.const]p2-6.
14488 // FIXME: Stricter checking for these rules would be useful for constinit /
14489 // -Wglobal-constructors.
14490 HasConstInit = checkConstInit();
14491
14492 // Compute and cache the constant value, and remember that we have a
14493 // constant initializer.
14494 if (HasConstInit) {
14495 (void)var->checkForConstantInitialization(Notes);
14496 Notes.clear();
14497 } else if (CacheCulprit) {
14498 Notes.emplace_back(CacheCulprit->getExprLoc(),
14499 PDiag(diag::note_invalid_subexpr_in_const_expr));
14500 Notes.back().second << CacheCulprit->getSourceRange();
14501 }
14502 } else {
14503 // Evaluate the initializer to see if it's a constant initializer.
14504 HasConstInit = var->checkForConstantInitialization(Notes);
14505 }
14506
14507 if (HasConstInit) {
14508 // FIXME: Consider replacing the initializer with a ConstantExpr.
14509 } else if (var->isConstexpr()) {
14510 SourceLocation DiagLoc = var->getLocation();
14511 // If the note doesn't add any useful information other than a source
14512 // location, fold it into the primary diagnostic.
14513 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14514 diag::note_invalid_subexpr_in_const_expr) {
14515 DiagLoc = Notes[0].first;
14516 Notes.clear();
14517 }
14518 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14519 << var << Init->getSourceRange();
14520 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14521 Diag(Notes[I].first, Notes[I].second);
14522 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14523 auto *Attr = var->getAttr<ConstInitAttr>();
14524 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14525 << Init->getSourceRange();
14526 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14527 << Attr->getRange() << Attr->isConstinit();
14528 for (auto &it : Notes)
14529 Diag(it.first, it.second);
14530 } else if (IsGlobal &&
14531 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14532 var->getLocation())) {
14533 // Warn about globals which don't have a constant initializer. Don't
14534 // warn about globals with a non-trivial destructor because we already
14535 // warned about them.
14536 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14537 if (!(RD && !RD->hasTrivialDestructor())) {
14538 // checkConstInit() here permits trivial default initialization even in
14539 // C++11 onwards, where such an initializer is not a constant initializer
14540 // but nonetheless doesn't require a global constructor.
14541 if (!checkConstInit())
14542 Diag(var->getLocation(), diag::warn_global_constructor)
14543 << Init->getSourceRange();
14544 }
14545 }
14546 }
14547
14548 // Apply section attributes and pragmas to global variables.
14549 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14551 PragmaStack<StringLiteral *> *Stack = nullptr;
14552 int SectionFlags = ASTContext::PSF_Read;
14553 bool MSVCEnv =
14554 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14555 std::optional<QualType::NonConstantStorageReason> Reason;
14556 if (HasConstInit &&
14557 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14558 Stack = &ConstSegStack;
14559 } else {
14560 SectionFlags |= ASTContext::PSF_Write;
14561 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14562 }
14563 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14564 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14565 SectionFlags |= ASTContext::PSF_Implicit;
14566 UnifySection(SA->getName(), SectionFlags, var);
14567 } else if (Stack->CurrentValue) {
14568 if (Stack != &ConstSegStack && MSVCEnv &&
14569 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14570 var->getType().isConstQualified()) {
14571 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14572 NonConstNonReferenceType) &&
14573 "This case should've already been handled elsewhere");
14574 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14575 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14577 : *Reason);
14578 }
14579 SectionFlags |= ASTContext::PSF_Implicit;
14580 auto SectionName = Stack->CurrentValue->getString();
14581 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14582 Stack->CurrentPragmaLocation,
14583 SectionAttr::Declspec_allocate));
14584 if (UnifySection(SectionName, SectionFlags, var))
14585 var->dropAttr<SectionAttr>();
14586 }
14587
14588 // Apply the init_seg attribute if this has an initializer. If the
14589 // initializer turns out to not be dynamic, we'll end up ignoring this
14590 // attribute.
14591 if (CurInitSeg && var->getInit())
14592 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14593 CurInitSegLoc));
14594 }
14595
14596 // All the following checks are C++ only.
14597 if (!getLangOpts().CPlusPlus) {
14598 // If this variable must be emitted, add it as an initializer for the
14599 // current module.
14600 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14601 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14602 return;
14603 }
14604
14605 // Require the destructor.
14606 if (!type->isDependentType())
14607 if (const RecordType *recordType = baseType->getAs<RecordType>())
14609
14610 // If this variable must be emitted, add it as an initializer for the current
14611 // module.
14612 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14613 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14614
14615 // Build the bindings if this is a structured binding declaration.
14616 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14618}
14619
14621 assert(VD->isStaticLocal());
14622
14623 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14624
14625 // Find outermost function when VD is in lambda function.
14626 while (FD && !getDLLAttr(FD) &&
14627 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14628 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14629 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14630 }
14631
14632 if (!FD)
14633 return;
14634
14635 // Static locals inherit dll attributes from their function.
14636 if (Attr *A = getDLLAttr(FD)) {
14637 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14638 NewAttr->setInherited(true);
14639 VD->addAttr(NewAttr);
14640 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14641 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14642 NewAttr->setInherited(true);
14643 VD->addAttr(NewAttr);
14644
14645 // Export this function to enforce exporting this static variable even
14646 // if it is not used in this compilation unit.
14647 if (!FD->hasAttr<DLLExportAttr>())
14648 FD->addAttr(NewAttr);
14649
14650 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14651 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14652 NewAttr->setInherited(true);
14653 VD->addAttr(NewAttr);
14654 }
14655}
14656
14658 assert(VD->getTLSKind());
14659
14660 // Perform TLS alignment check here after attributes attached to the variable
14661 // which may affect the alignment have been processed. Only perform the check
14662 // if the target has a maximum TLS alignment (zero means no constraints).
14663 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14664 // Protect the check so that it's not performed on dependent types and
14665 // dependent alignments (we can't determine the alignment in that case).
14666 if (!VD->hasDependentAlignment()) {
14667 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14668 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14669 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14671 << (unsigned)MaxAlignChars.getQuantity();
14672 }
14673 }
14674 }
14675}
14676
14678 // Note that we are no longer parsing the initializer for this declaration.
14679 ParsingInitForAutoVars.erase(ThisDecl);
14680
14681 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14682 if (!VD)
14683 return;
14684
14685 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14687 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14689 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14693 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14697 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14701 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14704 }
14705
14706 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14707 for (auto *BD : DD->bindings()) {
14709 }
14710 }
14711
14712 CheckInvalidBuiltinCountedByRef(VD->getInit(), InitializerKind);
14713
14714 checkAttributesAfterMerging(*this, *VD);
14715
14716 if (VD->isStaticLocal())
14718
14719 if (VD->getTLSKind())
14721
14722 // Perform check for initializers of device-side global variables.
14723 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14724 // 7.5). We must also apply the same checks to all __shared__
14725 // variables whether they are local or not. CUDA also allows
14726 // constant initializers for __constant__ and __device__ variables.
14727 if (getLangOpts().CUDA)
14729
14730 // Grab the dllimport or dllexport attribute off of the VarDecl.
14731 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14732
14733 // Imported static data members cannot be defined out-of-line.
14734 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14735 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14737 // We allow definitions of dllimport class template static data members
14738 // with a warning.
14740 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14741 bool IsClassTemplateMember =
14742 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14743 Context->getDescribedClassTemplate();
14744
14745 Diag(VD->getLocation(),
14746 IsClassTemplateMember
14747 ? diag::warn_attribute_dllimport_static_field_definition
14748 : diag::err_attribute_dllimport_static_field_definition);
14749 Diag(IA->getLocation(), diag::note_attribute);
14750 if (!IsClassTemplateMember)
14751 VD->setInvalidDecl();
14752 }
14753 }
14754
14755 // dllimport/dllexport variables cannot be thread local, their TLS index
14756 // isn't exported with the variable.
14757 if (DLLAttr && VD->getTLSKind()) {
14758 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14759 if (F && getDLLAttr(F)) {
14760 assert(VD->isStaticLocal());
14761 // But if this is a static local in a dlimport/dllexport function, the
14762 // function will never be inlined, which means the var would never be
14763 // imported, so having it marked import/export is safe.
14764 } else {
14765 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14766 << DLLAttr;
14767 VD->setInvalidDecl();
14768 }
14769 }
14770
14771 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14772 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14773 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14774 << Attr;
14775 VD->dropAttr<UsedAttr>();
14776 }
14777 }
14778 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14779 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14780 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14781 << Attr;
14782 VD->dropAttr<RetainAttr>();
14783 }
14784 }
14785
14786 const DeclContext *DC = VD->getDeclContext();
14787 // If there's a #pragma GCC visibility in scope, and this isn't a class
14788 // member, set the visibility of this variable.
14791
14792 // FIXME: Warn on unused var template partial specializations.
14793 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14795
14796 // Now we have parsed the initializer and can update the table of magic
14797 // tag values.
14798 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14800 return;
14801
14802 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14803 const Expr *MagicValueExpr = VD->getInit();
14804 if (!MagicValueExpr) {
14805 continue;
14806 }
14807 std::optional<llvm::APSInt> MagicValueInt;
14808 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14809 Diag(I->getRange().getBegin(),
14810 diag::err_type_tag_for_datatype_not_ice)
14811 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14812 continue;
14813 }
14814 if (MagicValueInt->getActiveBits() > 64) {
14815 Diag(I->getRange().getBegin(),
14816 diag::err_type_tag_for_datatype_too_large)
14817 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14818 continue;
14819 }
14820 uint64_t MagicValue = MagicValueInt->getZExtValue();
14821 RegisterTypeTagForDatatype(I->getArgumentKind(),
14822 MagicValue,
14823 I->getMatchingCType(),
14824 I->getLayoutCompatible(),
14825 I->getMustBeNull());
14826 }
14827}
14828
14830 auto *VD = dyn_cast<VarDecl>(DD);
14831 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14832}
14833
14835 ArrayRef<Decl *> Group) {
14837
14838 if (DS.isTypeSpecOwned())
14839 Decls.push_back(DS.getRepAsDecl());
14840
14841 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14842 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14843 bool DiagnosedMultipleDecomps = false;
14844 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14845 bool DiagnosedNonDeducedAuto = false;
14846
14847 for (Decl *D : Group) {
14848 if (!D)
14849 continue;
14850 // Check if the Decl has been declared in '#pragma omp declare target'
14851 // directive and has static storage duration.
14852 if (auto *VD = dyn_cast<VarDecl>(D);
14853 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14854 VD->hasGlobalStorage())
14856 // For declarators, there are some additional syntactic-ish checks we need
14857 // to perform.
14858 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14859 if (!FirstDeclaratorInGroup)
14860 FirstDeclaratorInGroup = DD;
14861 if (!FirstDecompDeclaratorInGroup)
14862 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14863 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14864 !hasDeducedAuto(DD))
14865 FirstNonDeducedAutoInGroup = DD;
14866
14867 if (FirstDeclaratorInGroup != DD) {
14868 // A decomposition declaration cannot be combined with any other
14869 // declaration in the same group.
14870 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14871 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14872 diag::err_decomp_decl_not_alone)
14873 << FirstDeclaratorInGroup->getSourceRange()
14874 << DD->getSourceRange();
14875 DiagnosedMultipleDecomps = true;
14876 }
14877
14878 // A declarator that uses 'auto' in any way other than to declare a
14879 // variable with a deduced type cannot be combined with any other
14880 // declarator in the same group.
14881 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14882 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14883 diag::err_auto_non_deduced_not_alone)
14884 << FirstNonDeducedAutoInGroup->getType()
14886 << FirstDeclaratorInGroup->getSourceRange()
14887 << DD->getSourceRange();
14888 DiagnosedNonDeducedAuto = true;
14889 }
14890 }
14891 }
14892
14893 Decls.push_back(D);
14894 }
14895
14897 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14898 handleTagNumbering(Tag, S);
14899 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14901 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14902 }
14903 }
14904
14905 return BuildDeclaratorGroup(Decls);
14906}
14907
14910 // C++14 [dcl.spec.auto]p7: (DR1347)
14911 // If the type that replaces the placeholder type is not the same in each
14912 // deduction, the program is ill-formed.
14913 if (Group.size() > 1) {
14914 QualType Deduced;
14915 VarDecl *DeducedDecl = nullptr;
14916 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14917 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14918 if (!D || D->isInvalidDecl())
14919 break;
14920 DeducedType *DT = D->getType()->getContainedDeducedType();
14921 if (!DT || DT->getDeducedType().isNull())
14922 continue;
14923 if (Deduced.isNull()) {
14924 Deduced = DT->getDeducedType();
14925 DeducedDecl = D;
14926 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14927 auto *AT = dyn_cast<AutoType>(DT);
14928 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14929 diag::err_auto_different_deductions)
14930 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14931 << DeducedDecl->getDeclName() << DT->getDeducedType()
14932 << D->getDeclName();
14933 if (DeducedDecl->hasInit())
14934 Dia << DeducedDecl->getInit()->getSourceRange();
14935 if (D->getInit())
14936 Dia << D->getInit()->getSourceRange();
14937 D->setInvalidDecl();
14938 break;
14939 }
14940 }
14941 }
14942
14944
14945 return DeclGroupPtrTy::make(
14946 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14947}
14948
14951}
14952
14954 // Don't parse the comment if Doxygen diagnostics are ignored.
14955 if (Group.empty() || !Group[0])
14956 return;
14957
14958 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14959 Group[0]->getLocation()) &&
14960 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14961 Group[0]->getLocation()))
14962 return;
14963
14964 if (Group.size() >= 2) {
14965 // This is a decl group. Normally it will contain only declarations
14966 // produced from declarator list. But in case we have any definitions or
14967 // additional declaration references:
14968 // 'typedef struct S {} S;'
14969 // 'typedef struct S *S;'
14970 // 'struct S *pS;'
14971 // FinalizeDeclaratorGroup adds these as separate declarations.
14972 Decl *MaybeTagDecl = Group[0];
14973 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14974 Group = Group.slice(1);
14975 }
14976 }
14977
14978 // FIMXE: We assume every Decl in the group is in the same file.
14979 // This is false when preprocessor constructs the group from decls in
14980 // different files (e. g. macros or #include).
14982}
14983
14985 // Check that there are no default arguments inside the type of this
14986 // parameter.
14987 if (getLangOpts().CPlusPlus)
14989
14990 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14991 if (D.getCXXScopeSpec().isSet()) {
14992 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14993 << D.getCXXScopeSpec().getRange();
14994 }
14995
14996 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14997 // simple identifier except [...irrelevant cases...].
14998 switch (D.getName().getKind()) {
15000 break;
15001
15009 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15011 break;
15012
15015 // GetNameForDeclarator would not produce a useful name in this case.
15016 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15017 break;
15018 }
15019}
15020
15022 SourceLocation ExplicitThisLoc) {
15023 if (!ExplicitThisLoc.isValid())
15024 return;
15025 assert(S.getLangOpts().CPlusPlus &&
15026 "explicit parameter in non-cplusplus mode");
15027 if (!S.getLangOpts().CPlusPlus23)
15028 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15029 << P->getSourceRange();
15030
15031 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15032 // parameter pack.
15033 if (P->isParameterPack()) {
15034 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15035 << P->getSourceRange();
15036 return;
15037 }
15038 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15039 if (LambdaScopeInfo *LSI = S.getCurLambda())
15040 LSI->ExplicitObjectParameter = P;
15041}
15042
15044 SourceLocation ExplicitThisLoc) {
15045 const DeclSpec &DS = D.getDeclSpec();
15046
15047 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15048 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15049 // except for the special case of a single unnamed parameter of type void
15050 // with no storage class specifier, no type qualifier, and no following
15051 // ellipsis terminator.
15052 // Clang applies the C2y rules for 'register void' in all C language modes,
15053 // same as GCC, because it's questionable what that could possibly mean.
15054
15055 // C++03 [dcl.stc]p2 also permits 'auto'.
15056 StorageClass SC = SC_None;
15058 SC = SC_Register;
15059 // In C++11, the 'register' storage class specifier is deprecated.
15060 // In C++17, it is not allowed, but we tolerate it as an extension.
15061 if (getLangOpts().CPlusPlus11) {
15063 ? diag::ext_register_storage_class
15064 : diag::warn_deprecated_register)
15066 } else if (!getLangOpts().CPlusPlus &&
15068 D.getNumTypeObjects() == 0) {
15070 diag::err_invalid_storage_class_in_func_decl)
15072 D.getMutableDeclSpec().ClearStorageClassSpecs();
15073 }
15074 } else if (getLangOpts().CPlusPlus &&
15076 SC = SC_Auto;
15079 diag::err_invalid_storage_class_in_func_decl);
15080 D.getMutableDeclSpec().ClearStorageClassSpecs();
15081 }
15082
15084 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15086 if (DS.isInlineSpecified())
15087 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15088 << getLangOpts().CPlusPlus17;
15089 if (DS.hasConstexprSpecifier())
15090 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15091 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15092
15094
15096
15098 QualType parmDeclType = TInfo->getType();
15099
15100 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15101 const IdentifierInfo *II = D.getIdentifier();
15102 if (II) {
15103 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
15104 RedeclarationKind::ForVisibleRedeclaration);
15105 LookupName(R, S);
15106 if (!R.empty()) {
15107 NamedDecl *PrevDecl = *R.begin();
15108 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15109 // Maybe we will complain about the shadowed template parameter.
15110 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15111 // Just pretend that we didn't see the previous declaration.
15112 PrevDecl = nullptr;
15113 }
15114 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15115 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15116 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15117 // Recover by removing the name
15118 II = nullptr;
15119 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15120 D.setInvalidType(true);
15121 }
15122 }
15123 }
15124
15125 // Temporarily put parameter variables in the translation unit, not
15126 // the enclosing context. This prevents them from accidentally
15127 // looking like class members in C++.
15128 ParmVarDecl *New =
15130 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15131
15132 if (D.isInvalidType())
15133 New->setInvalidDecl();
15134
15135 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15136
15137 assert(S->isFunctionPrototypeScope());
15138 assert(S->getFunctionPrototypeDepth() >= 1);
15139 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15140 S->getNextFunctionPrototypeIndex());
15141
15142 // Add the parameter declaration into this scope.
15143 S->AddDecl(New);
15144 if (II)
15145 IdResolver.AddDecl(New);
15146
15147 ProcessDeclAttributes(S, New, D);
15148
15149 if (D.getDeclSpec().isModulePrivateSpecified())
15150 Diag(New->getLocation(), diag::err_module_private_local)
15151 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15152 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
15153
15154 if (New->hasAttr<BlocksAttr>()) {
15155 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15156 }
15157
15158 if (getLangOpts().OpenCL)
15160
15161 return New;
15162}
15163
15166 QualType T) {
15167 /* FIXME: setting StartLoc == Loc.
15168 Would it be worth to modify callers so as to provide proper source
15169 location for the unnamed parameters, embedding the parameter's type? */
15170 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15172 SC_None, nullptr);
15173 Param->setImplicit();
15174 return Param;
15175}
15176
15178 // Don't diagnose unused-parameter errors in template instantiations; we
15179 // will already have done so in the template itself.
15181 return;
15182
15183 for (const ParmVarDecl *Parameter : Parameters) {
15184 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15185 !Parameter->hasAttr<UnusedAttr>() &&
15186 !Parameter->getIdentifier()->isPlaceholder()) {
15187 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15188 << Parameter->getDeclName();
15189 }
15190 }
15191}
15192
15194 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15195 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15196 return;
15197
15198 // Warn if the return value is pass-by-value and larger than the specified
15199 // threshold.
15200 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15201 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15202 if (Size > LangOpts.NumLargeByValueCopy)
15203 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15204 }
15205
15206 // Warn if any parameter is pass-by-value and larger than the specified
15207 // threshold.
15208 for (const ParmVarDecl *Parameter : Parameters) {
15209 QualType T = Parameter->getType();
15210 if (T->isDependentType() || !T.isPODType(Context))
15211 continue;
15212 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15213 if (Size > LangOpts.NumLargeByValueCopy)
15214 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15215 << Parameter << Size;
15216 }
15217}
15218
15220 SourceLocation NameLoc,
15221 const IdentifierInfo *Name, QualType T,
15222 TypeSourceInfo *TSInfo, StorageClass SC) {
15223 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15224 if (getLangOpts().ObjCAutoRefCount &&
15225 T.getObjCLifetime() == Qualifiers::OCL_None &&
15226 T->isObjCLifetimeType()) {
15227
15228 Qualifiers::ObjCLifetime lifetime;
15229
15230 // Special cases for arrays:
15231 // - if it's const, use __unsafe_unretained
15232 // - otherwise, it's an error
15233 if (T->isArrayType()) {
15234 if (!T.isConstQualified()) {
15238 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15239 else
15240 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15241 << TSInfo->getTypeLoc().getSourceRange();
15242 }
15244 } else {
15245 lifetime = T->getObjCARCImplicitLifetime();
15246 }
15247 T = Context.getLifetimeQualifiedType(T, lifetime);
15248 }
15249
15250 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15252 TSInfo, SC, nullptr);
15253
15254 // Make a note if we created a new pack in the scope of a lambda, so that
15255 // we know that references to that pack must also be expanded within the
15256 // lambda scope.
15257 if (New->isParameterPack())
15258 if (auto *CSI = getEnclosingLambdaOrBlock())
15259 CSI->LocalPacks.push_back(New);
15260
15265
15266 // Parameter declarators cannot be interface types. All ObjC objects are
15267 // passed by reference.
15268 if (T->isObjCObjectType()) {
15269 SourceLocation TypeEndLoc =
15271 Diag(NameLoc,
15272 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15273 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15275 New->setType(T);
15276 }
15277
15278 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15279 // duration shall not be qualified by an address-space qualifier."
15280 // Since all parameters have automatic store duration, they can not have
15281 // an address space.
15282 if (T.getAddressSpace() != LangAS::Default &&
15283 // OpenCL allows function arguments declared to be an array of a type
15284 // to be qualified with an address space.
15285 !(getLangOpts().OpenCL &&
15286 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15287 // WebAssembly allows reference types as parameters. Funcref in particular
15288 // lives in a different address space.
15289 !(T->isFunctionPointerType() &&
15290 T.getAddressSpace() == LangAS::wasm_funcref)) {
15291 Diag(NameLoc, diag::err_arg_with_address_space);
15292 New->setInvalidDecl();
15293 }
15294
15295 // PPC MMA non-pointer types are not allowed as function argument types.
15296 if (Context.getTargetInfo().getTriple().isPPC64() &&
15297 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15298 New->setInvalidDecl();
15299 }
15300
15301 return New;
15302}
15303
15305 SourceLocation LocAfterDecls) {
15306 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15307
15308 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15309 // in the declaration list shall have at least one declarator, those
15310 // declarators shall only declare identifiers from the identifier list, and
15311 // every identifier in the identifier list shall be declared.
15312 //
15313 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15314 // identifiers it names shall be declared in the declaration list."
15315 //
15316 // This is why we only diagnose in C99 and later. Note, the other conditions
15317 // listed are checked elsewhere.
15318 if (!FTI.hasPrototype) {
15319 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15320 --i;
15321 if (FTI.Params[i].Param == nullptr) {
15322 if (getLangOpts().C99) {
15323 SmallString<256> Code;
15324 llvm::raw_svector_ostream(Code)
15325 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15326 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15327 << FTI.Params[i].Ident
15328 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15329 }
15330
15331 // Implicitly declare the argument as type 'int' for lack of a better
15332 // type.
15333 AttributeFactory attrs;
15334 DeclSpec DS(attrs);
15335 const char* PrevSpec; // unused
15336 unsigned DiagID; // unused
15337 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15338 DiagID, Context.getPrintingPolicy());
15339 // Use the identifier location for the type source range.
15340 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15341 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15344 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15345 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15346 }
15347 }
15348 }
15349}
15350
15351Decl *
15353 MultiTemplateParamsArg TemplateParameterLists,
15354 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15355 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15356 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15357 Scope *ParentScope = FnBodyScope->getParent();
15358
15359 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15360 // we define a non-templated function definition, we will create a declaration
15361 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15362 // The base function declaration will have the equivalent of an `omp declare
15363 // variant` annotation which specifies the mangled definition as a
15364 // specialization function under the OpenMP context defined as part of the
15365 // `omp begin declare variant`.
15367 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15369 ParentScope, D, TemplateParameterLists, Bases);
15370
15371 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15372 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15373 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15374
15375 if (!Bases.empty())
15377 Bases);
15378
15379 return Dcl;
15380}
15381
15384}
15385
15387 const FunctionDecl *&PossiblePrototype) {
15388 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15389 Prev = Prev->getPreviousDecl()) {
15390 // Ignore any declarations that occur in function or method
15391 // scope, because they aren't visible from the header.
15392 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15393 continue;
15394
15395 PossiblePrototype = Prev;
15396 return Prev->getType()->isFunctionProtoType();
15397 }
15398 return false;
15399}
15400
15401static bool
15403 const FunctionDecl *&PossiblePrototype) {
15404 // Don't warn about invalid declarations.
15405 if (FD->isInvalidDecl())
15406 return false;
15407
15408 // Or declarations that aren't global.
15409 if (!FD->isGlobal())
15410 return false;
15411
15412 // Don't warn about C++ member functions.
15413 if (isa<CXXMethodDecl>(FD))
15414 return false;
15415
15416 // Don't warn about 'main'.
15417 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15418 if (IdentifierInfo *II = FD->getIdentifier())
15419 if (II->isStr("main") || II->isStr("efi_main"))
15420 return false;
15421
15422 if (FD->isMSVCRTEntryPoint())
15423 return false;
15424
15425 // Don't warn about inline functions.
15426 if (FD->isInlined())
15427 return false;
15428
15429 // Don't warn about function templates.
15431 return false;
15432
15433 // Don't warn about function template specializations.
15435 return false;
15436
15437 // Don't warn for OpenCL kernels.
15438 if (FD->hasAttr<OpenCLKernelAttr>())
15439 return false;
15440
15441 // Don't warn on explicitly deleted functions.
15442 if (FD->isDeleted())
15443 return false;
15444
15445 // Don't warn on implicitly local functions (such as having local-typed
15446 // parameters).
15447 if (!FD->isExternallyVisible())
15448 return false;
15449
15450 // If we were able to find a potential prototype, don't warn.
15451 if (FindPossiblePrototype(FD, PossiblePrototype))
15452 return false;
15453
15454 return true;
15455}
15456
15457void
15459 const FunctionDecl *EffectiveDefinition,
15460 SkipBodyInfo *SkipBody) {
15461 const FunctionDecl *Definition = EffectiveDefinition;
15462 if (!Definition &&
15463 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15464 return;
15465
15466 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15467 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15468 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15469 // A merged copy of the same function, instantiated as a member of
15470 // the same class, is OK.
15471 if (declaresSameEntity(OrigFD, OrigDef) &&
15472 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15473 cast<Decl>(FD->getLexicalDeclContext())))
15474 return;
15475 }
15476 }
15477 }
15478
15480 return;
15481
15482 // Don't emit an error when this is redefinition of a typo-corrected
15483 // definition.
15485 return;
15486
15487 // If we don't have a visible definition of the function, and it's inline or
15488 // a template, skip the new definition.
15489 if (SkipBody && !hasVisibleDefinition(Definition) &&
15490 (Definition->getFormalLinkage() == Linkage::Internal ||
15491 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15492 Definition->getNumTemplateParameterLists())) {
15493 SkipBody->ShouldSkip = true;
15494 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15495 if (auto *TD = Definition->getDescribedFunctionTemplate())
15498 return;
15499 }
15500
15501 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15502 Definition->getStorageClass() == SC_Extern)
15503 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15504 << FD << getLangOpts().CPlusPlus;
15505 else
15506 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15507
15508 Diag(Definition->getLocation(), diag::note_previous_definition);
15509 FD->setInvalidDecl();
15510}
15511
15513 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15514
15516 LSI->CallOperator = CallOperator;
15517 LSI->Lambda = LambdaClass;
15518 LSI->ReturnType = CallOperator->getReturnType();
15519 // When this function is called in situation where the context of the call
15520 // operator is not entered, we set AfterParameterList to false, so that
15521 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15522 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
15523 // where we would set the CurContext to the lambda operator before
15524 // substituting into it. In this case the flag needs to be true such that
15525 // tryCaptureVariable can correctly handle potential captures thereof.
15526 LSI->AfterParameterList = CurContext == CallOperator;
15527
15528 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
15529 // used at the point of dealing with potential captures.
15530 //
15531 // We don't use LambdaClass->isGenericLambda() because this value doesn't
15532 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
15533 // associated. (Technically, we could recover that list from their
15534 // instantiation patterns, but for now, the GLTemplateParameterList seems
15535 // unnecessary in these cases.)
15536 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
15537 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
15538 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15539
15540 if (LCD == LCD_None)
15542 else if (LCD == LCD_ByCopy)
15544 else if (LCD == LCD_ByRef)
15546 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15547
15549 LSI->Mutable = !CallOperator->isConst();
15550 if (CallOperator->isExplicitObjectMemberFunction())
15551 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15552
15553 // Add the captures to the LSI so they can be noted as already
15554 // captured within tryCaptureVar.
15555 auto I = LambdaClass->field_begin();
15556 for (const auto &C : LambdaClass->captures()) {
15557 if (C.capturesVariable()) {
15558 ValueDecl *VD = C.getCapturedVar();
15559 if (VD->isInitCapture())
15561 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15562 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15563 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15564 /*EllipsisLoc*/C.isPackExpansion()
15565 ? C.getEllipsisLoc() : SourceLocation(),
15566 I->getType(), /*Invalid*/false);
15567
15568 } else if (C.capturesThis()) {
15569 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15570 C.getCaptureKind() == LCK_StarThis);
15571 } else {
15572 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15573 I->getType());
15574 }
15575 ++I;
15576 }
15577 return LSI;
15578}
15579
15581 SkipBodyInfo *SkipBody,
15582 FnBodyKind BodyKind) {
15583 if (!D) {
15584 // Parsing the function declaration failed in some way. Push on a fake scope
15585 // anyway so we can try to parse the function body.
15588 return D;
15589 }
15590
15591 FunctionDecl *FD = nullptr;
15592
15593 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15594 FD = FunTmpl->getTemplatedDecl();
15595 else
15596 FD = cast<FunctionDecl>(D);
15597
15598 // Do not push if it is a lambda because one is already pushed when building
15599 // the lambda in ActOnStartOfLambdaDefinition().
15600 if (!isLambdaCallOperator(FD))
15601 // [expr.const]/p14.1
15602 // An expression or conversion is in an immediate function context if it is
15603 // potentially evaluated and either: its innermost enclosing non-block scope
15604 // is a function parameter scope of an immediate function.
15607 : ExprEvalContexts.back().Context);
15608
15609 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15610 // context is nested in an immediate function context, so smaller contexts
15611 // that appear inside immediate functions (like variable initializers) are
15612 // considered to be inside an immediate function context even though by
15613 // themselves they are not immediate function contexts. But when a new
15614 // function is entered, we need to reset this tracking, since the entered
15615 // function might be not an immediate function.
15616 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15617 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15618 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15619
15620 // Check for defining attributes before the check for redefinition.
15621 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15622 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15623 FD->dropAttr<AliasAttr>();
15624 FD->setInvalidDecl();
15625 }
15626 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15627 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15628 FD->dropAttr<IFuncAttr>();
15629 FD->setInvalidDecl();
15630 }
15631 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15632 if (Context.getTargetInfo().getTriple().isAArch64() &&
15633 !Context.getTargetInfo().hasFeature("fmv") &&
15634 !Attr->isDefaultVersion()) {
15635 // If function multi versioning disabled skip parsing function body
15636 // defined with non-default target_version attribute
15637 if (SkipBody)
15638 SkipBody->ShouldSkip = true;
15639 return nullptr;
15640 }
15641 }
15642
15643 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15644 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15645 Ctor->isDefaultConstructor() &&
15647 // If this is an MS ABI dllexport default constructor, instantiate any
15648 // default arguments.
15650 }
15651 }
15652
15653 // See if this is a redefinition. If 'will have body' (or similar) is already
15654 // set, then these checks were already performed when it was set.
15655 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15657 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15658
15659 // If we're skipping the body, we're done. Don't enter the scope.
15660 if (SkipBody && SkipBody->ShouldSkip)
15661 return D;
15662 }
15663
15664 // Mark this function as "will have a body eventually". This lets users to
15665 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15666 // this function.
15667 FD->setWillHaveBody();
15668
15669 // If we are instantiating a generic lambda call operator, push
15670 // a LambdaScopeInfo onto the function stack. But use the information
15671 // that's already been calculated (ActOnLambdaExpr) to prime the current
15672 // LambdaScopeInfo.
15673 // When the template operator is being specialized, the LambdaScopeInfo,
15674 // has to be properly restored so that tryCaptureVariable doesn't try
15675 // and capture any new variables. In addition when calculating potential
15676 // captures during transformation of nested lambdas, it is necessary to
15677 // have the LSI properly restored.
15679 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15680 // instantiated, explicitly specialized.
15683 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15684 FD->setInvalidDecl();
15686 } else {
15687 assert(inTemplateInstantiation() &&
15688 "There should be an active template instantiation on the stack "
15689 "when instantiating a generic lambda!");
15690 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15691 }
15692 } else {
15693 // Enter a new function scope
15695 }
15696
15697 // Builtin functions cannot be defined.
15698 if (unsigned BuiltinID = FD->getBuiltinID()) {
15701 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15702 FD->setInvalidDecl();
15703 }
15704 }
15705
15706 // The return type of a function definition must be complete (C99 6.9.1p3).
15707 // C++23 [dcl.fct.def.general]/p2
15708 // The type of [...] the return for a function definition
15709 // shall not be a (possibly cv-qualified) class type that is incomplete
15710 // or abstract within the function body unless the function is deleted.
15711 QualType ResultType = FD->getReturnType();
15712 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15713 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15714 (RequireCompleteType(FD->getLocation(), ResultType,
15715 diag::err_func_def_incomplete_result) ||
15717 diag::err_abstract_type_in_decl,
15719 FD->setInvalidDecl();
15720
15721 if (FnBodyScope)
15722 PushDeclContext(FnBodyScope, FD);
15723
15724 // Check the validity of our function parameters
15725 if (BodyKind != FnBodyKind::Delete)
15727 /*CheckParameterNames=*/true);
15728
15729 // Add non-parameter declarations already in the function to the current
15730 // scope.
15731 if (FnBodyScope) {
15732 for (Decl *NPD : FD->decls()) {
15733 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15734 if (!NonParmDecl)
15735 continue;
15736 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15737 "parameters should not be in newly created FD yet");
15738
15739 // If the decl has a name, make it accessible in the current scope.
15740 if (NonParmDecl->getDeclName())
15741 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15742
15743 // Similarly, dive into enums and fish their constants out, making them
15744 // accessible in this scope.
15745 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15746 for (auto *EI : ED->enumerators())
15747 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15748 }
15749 }
15750 }
15751
15752 // Introduce our parameters into the function scope
15753 for (auto *Param : FD->parameters()) {
15754 Param->setOwningFunction(FD);
15755
15756 // If this has an identifier, add it to the scope stack.
15757 if (Param->getIdentifier() && FnBodyScope) {
15758 CheckShadow(FnBodyScope, Param);
15759
15760 PushOnScopeChains(Param, FnBodyScope);
15761 }
15762 }
15763
15764 // C++ [module.import/6] external definitions are not permitted in header
15765 // units. Deleted and Defaulted functions are implicitly inline (but the
15766 // inline state is not set at this point, so check the BodyKind explicitly).
15767 // FIXME: Consider an alternate location for the test where the inlined()
15768 // state is complete.
15769 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15770 !FD->isInvalidDecl() && !FD->isInlined() &&
15771 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15772 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15773 !FD->isTemplateInstantiation()) {
15774 assert(FD->isThisDeclarationADefinition());
15775 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15776 FD->setInvalidDecl();
15777 }
15778
15779 // Ensure that the function's exception specification is instantiated.
15780 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15782
15783 // dllimport cannot be applied to non-inline function definitions.
15784 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15785 !FD->isTemplateInstantiation()) {
15786 assert(!FD->hasAttr<DLLExportAttr>());
15787 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15788 FD->setInvalidDecl();
15789 return D;
15790 }
15791
15792 // Some function attributes (like OptimizeNoneAttr) need actions before
15793 // parsing body started.
15795
15796 // We want to attach documentation to original Decl (which might be
15797 // a function template).
15799 if (getCurLexicalContext()->isObjCContainer() &&
15800 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15801 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15802 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15803
15805
15806 return D;
15807}
15808
15810 if (!FD || FD->isInvalidDecl())
15811 return;
15812 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
15813 FD = TD->getTemplatedDecl();
15814 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15818 FpPragmaStack.CurrentValue =
15820 }
15821}
15822
15824 ReturnStmt **Returns = Scope->Returns.data();
15825
15826 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15827 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15828 if (!NRVOCandidate->isNRVOVariable())
15829 Returns[I]->setNRVOCandidate(nullptr);
15830 }
15831 }
15832}
15833
15835 // We can't delay parsing the body of a constexpr function template (yet).
15836 if (D.getDeclSpec().hasConstexprSpecifier())
15837 return false;
15838
15839 // We can't delay parsing the body of a function template with a deduced
15840 // return type (yet).
15841 if (D.getDeclSpec().hasAutoTypeSpec()) {
15842 // If the placeholder introduces a non-deduced trailing return type,
15843 // we can still delay parsing it.
15844 if (D.getNumTypeObjects()) {
15845 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15846 if (Outer.Kind == DeclaratorChunk::Function &&
15847 Outer.Fun.hasTrailingReturnType()) {
15848 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15849 return Ty.isNull() || !Ty->isUndeducedType();
15850 }
15851 }
15852 return false;
15853 }
15854
15855 return true;
15856}
15857
15859 // We cannot skip the body of a function (or function template) which is
15860 // constexpr, since we may need to evaluate its body in order to parse the
15861 // rest of the file.
15862 // We cannot skip the body of a function with an undeduced return type,
15863 // because any callers of that function need to know the type.
15864 if (const FunctionDecl *FD = D->getAsFunction()) {
15865 if (FD->isConstexpr())
15866 return false;
15867 // We can't simply call Type::isUndeducedType here, because inside template
15868 // auto can be deduced to a dependent type, which is not considered
15869 // "undeduced".
15870 if (FD->getReturnType()->getContainedDeducedType())
15871 return false;
15872 }
15874}
15875
15877 if (!Decl)
15878 return nullptr;
15879 if (FunctionDecl *FD = Decl->getAsFunction())
15880 FD->setHasSkippedBody();
15881 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15882 MD->setHasSkippedBody();
15883 return Decl;
15884}
15885
15887 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15888}
15889
15890/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15891/// body.
15893public:
15894 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15896 if (!IsLambda)
15898 }
15899
15900private:
15901 Sema &S;
15902 bool IsLambda = false;
15903};
15904
15906 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15907
15908 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15909 if (EscapeInfo.count(BD))
15910 return EscapeInfo[BD];
15911
15912 bool R = false;
15913 const BlockDecl *CurBD = BD;
15914
15915 do {
15916 R = !CurBD->doesNotEscape();
15917 if (R)
15918 break;
15919 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15920 } while (CurBD);
15921
15922 return EscapeInfo[BD] = R;
15923 };
15924
15925 // If the location where 'self' is implicitly retained is inside a escaping
15926 // block, emit a diagnostic.
15927 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15929 if (IsOrNestedInEscapingBlock(P.second))
15930 S.Diag(P.first, diag::warn_implicitly_retains_self)
15931 << FixItHint::CreateInsertion(P.first, "self->");
15932}
15933
15934static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
15935 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
15936 FD->getDeclName().isIdentifier() && FD->getName() == Name;
15937}
15938
15940 return methodHasName(FD, "get_return_object");
15941}
15942
15944 return FD->isStatic() &&
15945 methodHasName(FD, "get_return_object_on_allocation_failure");
15946}
15947
15950 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15951 return;
15952 // Allow some_promise_type::get_return_object().
15954 return;
15955 if (!FD->hasAttr<CoroWrapperAttr>())
15956 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15957}
15958
15960 bool IsInstantiation) {
15962 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15963
15964 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15965 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15966
15968 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15969
15970 // If we skip function body, we can't tell if a function is a coroutine.
15971 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15972 if (FSI->isCoroutine())
15974 else
15976 }
15977
15978 {
15979 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15980 // one is already popped when finishing the lambda in BuildLambdaExpr().
15981 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15982 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15983 if (FD) {
15984 // If this is called by Parser::ParseFunctionDefinition() after marking
15985 // the declaration as deleted, and if the deleted-function-body contains
15986 // a message (C++26), then a DefaultedOrDeletedInfo will have already been
15987 // added to store that message; do not overwrite it in that case.
15988 //
15989 // Since this would always set the body to 'nullptr' in that case anyway,
15990 // which is already done when the function decl is initially created,
15991 // always skipping this irrespective of whether there is a delete message
15992 // should not be a problem.
15993 if (!FD->isDeletedAsWritten())
15994 FD->setBody(Body);
15995 FD->setWillHaveBody(false);
15997
15998 if (getLangOpts().CPlusPlus14) {
15999 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16000 FD->getReturnType()->isUndeducedType()) {
16001 // For a function with a deduced result type to return void,
16002 // the result type as written must be 'auto' or 'decltype(auto)',
16003 // possibly cv-qualified or constrained, but not ref-qualified.
16004 if (!FD->getReturnType()->getAs<AutoType>()) {
16005 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16006 << FD->getReturnType();
16007 FD->setInvalidDecl();
16008 } else {
16009 // Falling off the end of the function is the same as 'return;'.
16010 Expr *Dummy = nullptr;
16012 FD, dcl->getLocation(), Dummy,
16013 FD->getReturnType()->getAs<AutoType>()))
16014 FD->setInvalidDecl();
16015 }
16016 }
16017 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16018 // In C++11, we don't use 'auto' deduction rules for lambda call
16019 // operators because we don't support return type deduction.
16020 auto *LSI = getCurLambda();
16021 if (LSI->HasImplicitReturnType) {
16023
16024 // C++11 [expr.prim.lambda]p4:
16025 // [...] if there are no return statements in the compound-statement
16026 // [the deduced type is] the type void
16027 QualType RetType =
16028 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16029
16030 // Update the return type to the deduced type.
16031 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16032 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16033 Proto->getExtProtoInfo()));
16034 }
16035 }
16036
16037 // If the function implicitly returns zero (like 'main') or is naked,
16038 // don't complain about missing return statements.
16039 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
16041
16042 // MSVC permits the use of pure specifier (=0) on function definition,
16043 // defined at class scope, warn about this non-standard construct.
16044 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16045 !FD->isOutOfLine())
16046 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16047
16048 if (!FD->isInvalidDecl()) {
16049 // Don't diagnose unused parameters of defaulted, deleted or naked
16050 // functions.
16051 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16052 !FD->hasAttr<NakedAttr>())
16055 FD->getReturnType(), FD);
16056
16057 // If this is a structor, we need a vtable.
16058 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16059 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16060 else if (CXXDestructorDecl *Destructor =
16061 dyn_cast<CXXDestructorDecl>(FD))
16062 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16063
16064 // Try to apply the named return value optimization. We have to check
16065 // if we can do this here because lambdas keep return statements around
16066 // to deduce an implicit return type.
16067 if (FD->getReturnType()->isRecordType() &&
16069 computeNRVO(Body, FSI);
16070 }
16071
16072 // GNU warning -Wmissing-prototypes:
16073 // Warn if a global function is defined without a previous
16074 // prototype declaration. This warning is issued even if the
16075 // definition itself provides a prototype. The aim is to detect
16076 // global functions that fail to be declared in header files.
16077 const FunctionDecl *PossiblePrototype = nullptr;
16078 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16079 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16080
16081 if (PossiblePrototype) {
16082 // We found a declaration that is not a prototype,
16083 // but that could be a zero-parameter prototype
16084 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16085 TypeLoc TL = TI->getTypeLoc();
16087 Diag(PossiblePrototype->getLocation(),
16088 diag::note_declaration_not_a_prototype)
16089 << (FD->getNumParams() != 0)
16091 FTL.getRParenLoc(), "void")
16092 : FixItHint{});
16093 }
16094 } else {
16095 // Returns true if the token beginning at this Loc is `const`.
16096 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16097 const LangOptions &LangOpts) {
16098 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
16099 if (LocInfo.first.isInvalid())
16100 return false;
16101
16102 bool Invalid = false;
16103 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16104 if (Invalid)
16105 return false;
16106
16107 if (LocInfo.second > Buffer.size())
16108 return false;
16109
16110 const char *LexStart = Buffer.data() + LocInfo.second;
16111 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16112
16113 return StartTok.consume_front("const") &&
16114 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16115 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16116 };
16117
16118 auto findBeginLoc = [&]() {
16119 // If the return type has `const` qualifier, we want to insert
16120 // `static` before `const` (and not before the typename).
16121 if ((FD->getReturnType()->isAnyPointerType() &&
16124 // But only do this if we can determine where the `const` is.
16125
16126 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16127 getLangOpts()))
16128
16129 return FD->getBeginLoc();
16130 }
16131 return FD->getTypeSpecStartLoc();
16132 };
16134 diag::note_static_for_internal_linkage)
16135 << /* function */ 1
16136 << (FD->getStorageClass() == SC_None
16137 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16138 : FixItHint{});
16139 }
16140 }
16141
16142 // We might not have found a prototype because we didn't wish to warn on
16143 // the lack of a missing prototype. Try again without the checks for
16144 // whether we want to warn on the missing prototype.
16145 if (!PossiblePrototype)
16146 (void)FindPossiblePrototype(FD, PossiblePrototype);
16147
16148 // If the function being defined does not have a prototype, then we may
16149 // need to diagnose it as changing behavior in C23 because we now know
16150 // whether the function accepts arguments or not. This only handles the
16151 // case where the definition has no prototype but does have parameters
16152 // and either there is no previous potential prototype, or the previous
16153 // potential prototype also has no actual prototype. This handles cases
16154 // like:
16155 // void f(); void f(a) int a; {}
16156 // void g(a) int a; {}
16157 // See MergeFunctionDecl() for other cases of the behavior change
16158 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16159 // type without a prototype.
16160 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16161 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16162 !PossiblePrototype->isImplicit()))) {
16163 // The function definition has parameters, so this will change behavior
16164 // in C23. If there is a possible prototype, it comes before the
16165 // function definition.
16166 // FIXME: The declaration may have already been diagnosed as being
16167 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16168 // there's no way to test for the "changes behavior" condition in
16169 // SemaType.cpp when forming the declaration's function type. So, we do
16170 // this awkward dance instead.
16171 //
16172 // If we have a possible prototype and it declares a function with a
16173 // prototype, we don't want to diagnose it; if we have a possible
16174 // prototype and it has no prototype, it may have already been
16175 // diagnosed in SemaType.cpp as deprecated depending on whether
16176 // -Wstrict-prototypes is enabled. If we already warned about it being
16177 // deprecated, add a note that it also changes behavior. If we didn't
16178 // warn about it being deprecated (because the diagnostic is not
16179 // enabled), warn now that it is deprecated and changes behavior.
16180
16181 // This K&R C function definition definitely changes behavior in C23,
16182 // so diagnose it.
16183 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16184 << /*definition*/ 1 << /* not supported in C23 */ 0;
16185
16186 // If we have a possible prototype for the function which is a user-
16187 // visible declaration, we already tested that it has no prototype.
16188 // This will change behavior in C23. This gets a warning rather than a
16189 // note because it's the same behavior-changing problem as with the
16190 // definition.
16191 if (PossiblePrototype)
16192 Diag(PossiblePrototype->getLocation(),
16193 diag::warn_non_prototype_changes_behavior)
16194 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16195 << /*definition*/ 1;
16196 }
16197
16198 // Warn on CPUDispatch with an actual body.
16199 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16200 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16201 if (!CmpndBody->body_empty())
16202 Diag(CmpndBody->body_front()->getBeginLoc(),
16203 diag::warn_dispatch_body_ignored);
16204
16205 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16206 const CXXMethodDecl *KeyFunction;
16207 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16208 MD->isVirtual() &&
16209 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16210 MD == KeyFunction->getCanonicalDecl()) {
16211 // Update the key-function state if necessary for this ABI.
16212 if (FD->isInlined() &&
16215
16216 // If the newly-chosen key function is already defined, then we
16217 // need to mark the vtable as used retroactively.
16218 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16219 const FunctionDecl *Definition;
16220 if (KeyFunction && KeyFunction->isDefined(Definition))
16221 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16222 } else {
16223 // We just defined they key function; mark the vtable as used.
16224 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16225 }
16226 }
16227 }
16228
16229 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16230 "Function parsing confused");
16231 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16232 assert(MD == getCurMethodDecl() && "Method parsing confused");
16233 MD->setBody(Body);
16234 if (!MD->isInvalidDecl()) {
16236 MD->getReturnType(), MD);
16237
16238 if (Body)
16239 computeNRVO(Body, FSI);
16240 }
16241 if (FSI->ObjCShouldCallSuper) {
16242 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16243 << MD->getSelector().getAsString();
16244 FSI->ObjCShouldCallSuper = false;
16245 }
16247 const ObjCMethodDecl *InitMethod = nullptr;
16248 bool isDesignated =
16249 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16250 assert(isDesignated && InitMethod);
16251 (void)isDesignated;
16252
16253 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16254 auto IFace = MD->getClassInterface();
16255 if (!IFace)
16256 return false;
16257 auto SuperD = IFace->getSuperClass();
16258 if (!SuperD)
16259 return false;
16260 return SuperD->getIdentifier() ==
16261 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16262 };
16263 // Don't issue this warning for unavailable inits or direct subclasses
16264 // of NSObject.
16265 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16266 Diag(MD->getLocation(),
16267 diag::warn_objc_designated_init_missing_super_call);
16268 Diag(InitMethod->getLocation(),
16269 diag::note_objc_designated_init_marked_here);
16270 }
16272 }
16273 if (FSI->ObjCWarnForNoInitDelegation) {
16274 // Don't issue this warning for unavailable inits.
16275 if (!MD->isUnavailable())
16276 Diag(MD->getLocation(),
16277 diag::warn_objc_secondary_init_missing_init_call);
16278 FSI->ObjCWarnForNoInitDelegation = false;
16279 }
16280
16282 } else {
16283 // Parsing the function declaration failed in some way. Pop the fake scope
16284 // we pushed on.
16285 PopFunctionScopeInfo(ActivePolicy, dcl);
16286 return nullptr;
16287 }
16288
16289 if (Body && FSI->HasPotentialAvailabilityViolations)
16291
16292 assert(!FSI->ObjCShouldCallSuper &&
16293 "This should only be set for ObjC methods, which should have been "
16294 "handled in the block above.");
16295
16296 // Verify and clean out per-function state.
16297 if (Body && (!FD || !FD->isDefaulted())) {
16298 // C++ constructors that have function-try-blocks can't have return
16299 // statements in the handlers of that block. (C++ [except.handle]p14)
16300 // Verify this.
16301 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16302 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16303
16304 // Verify that gotos and switch cases don't jump into scopes illegally.
16307
16308 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16309 if (!Destructor->getParent()->isDependentType())
16311
16313 Destructor->getParent());
16314 }
16315
16316 // If any errors have occurred, clear out any temporaries that may have
16317 // been leftover. This ensures that these temporaries won't be picked up
16318 // for deletion in some later function.
16321 getDiagnostics().getSuppressAllDiagnostics()) {
16323 }
16324 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16325 // Since the body is valid, issue any analysis-based warnings that are
16326 // enabled.
16327 ActivePolicy = &WP;
16328 }
16329
16330 if (!IsInstantiation && FD &&
16331 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16332 !FD->isInvalidDecl() &&
16334 FD->setInvalidDecl();
16335
16336 if (FD && FD->hasAttr<NakedAttr>()) {
16337 for (const Stmt *S : Body->children()) {
16338 // Allow local register variables without initializer as they don't
16339 // require prologue.
16340 bool RegisterVariables = false;
16341 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16342 for (const auto *Decl : DS->decls()) {
16343 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16344 RegisterVariables =
16345 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16346 if (!RegisterVariables)
16347 break;
16348 }
16349 }
16350 }
16351 if (RegisterVariables)
16352 continue;
16353 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16354 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16355 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16356 FD->setInvalidDecl();
16357 break;
16358 }
16359 }
16360 }
16361
16362 assert(ExprCleanupObjects.size() ==
16363 ExprEvalContexts.back().NumCleanupObjects &&
16364 "Leftover temporaries in function");
16365 assert(!Cleanup.exprNeedsCleanups() &&
16366 "Unaccounted cleanups in function");
16367 assert(MaybeODRUseExprs.empty() &&
16368 "Leftover expressions for odr-use checking");
16369 }
16370 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16371 // the declaration context below. Otherwise, we're unable to transform
16372 // 'this' expressions when transforming immediate context functions.
16373
16374 if (!IsInstantiation)
16376
16377 PopFunctionScopeInfo(ActivePolicy, dcl);
16378 // If any errors have occurred, clear out any temporaries that may have
16379 // been leftover. This ensures that these temporaries won't be picked up for
16380 // deletion in some later function.
16383 }
16384
16385 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16386 !LangOpts.OMPTargetTriples.empty())) ||
16387 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16388 auto ES = getEmissionStatus(FD);
16391 DeclsToCheckForDeferredDiags.insert(FD);
16392 }
16393
16394 if (FD && !FD->isDeleted())
16395 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16396
16397 return dcl;
16398}
16399
16400/// When we finish delayed parsing of an attribute, we must attach it to the
16401/// relevant Decl.
16403 ParsedAttributes &Attrs) {
16404 // Always attach attributes to the underlying decl.
16405 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16406 D = TD->getTemplatedDecl();
16407 ProcessDeclAttributeList(S, D, Attrs);
16409
16410 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16411 if (Method->isStatic())
16413}
16414
16416 IdentifierInfo &II, Scope *S) {
16417 // It is not valid to implicitly define a function in C23.
16419 "Implicit function declarations aren't allowed in this language mode");
16420
16421 // Find the scope in which the identifier is injected and the corresponding
16422 // DeclContext.
16423 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16424 // In that case, we inject the declaration into the translation unit scope
16425 // instead.
16426 Scope *BlockScope = S;
16427 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16428 BlockScope = BlockScope->getParent();
16429
16430 // Loop until we find a DeclContext that is either a function/method or the
16431 // translation unit, which are the only two valid places to implicitly define
16432 // a function. This avoids accidentally defining the function within a tag
16433 // declaration, for example.
16434 Scope *ContextScope = BlockScope;
16435 while (!ContextScope->getEntity() ||
16436 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16437 !ContextScope->getEntity()->isTranslationUnit()))
16438 ContextScope = ContextScope->getParent();
16439 ContextRAII SavedContext(*this, ContextScope->getEntity());
16440
16441 // Before we produce a declaration for an implicitly defined
16442 // function, see whether there was a locally-scoped declaration of
16443 // this name as a function or variable. If so, use that
16444 // (non-visible) declaration, and complain about it.
16445 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16446 if (ExternCPrev) {
16447 // We still need to inject the function into the enclosing block scope so
16448 // that later (non-call) uses can see it.
16449 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16450
16451 // C89 footnote 38:
16452 // If in fact it is not defined as having type "function returning int",
16453 // the behavior is undefined.
16454 if (!isa<FunctionDecl>(ExternCPrev) ||
16456 cast<FunctionDecl>(ExternCPrev)->getType(),
16458 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16459 << ExternCPrev << !getLangOpts().C99;
16460 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16461 return ExternCPrev;
16462 }
16463 }
16464
16465 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16466 unsigned diag_id;
16467 if (II.getName().starts_with("__builtin_"))
16468 diag_id = diag::warn_builtin_unknown;
16469 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16470 else if (getLangOpts().C99)
16471 diag_id = diag::ext_implicit_function_decl_c99;
16472 else
16473 diag_id = diag::warn_implicit_function_decl;
16474
16475 TypoCorrection Corrected;
16476 // Because typo correction is expensive, only do it if the implicit
16477 // function declaration is going to be treated as an error.
16478 //
16479 // Perform the correction before issuing the main diagnostic, as some
16480 // consumers use typo-correction callbacks to enhance the main diagnostic.
16481 if (S && !ExternCPrev &&
16485 S, nullptr, CCC, CTK_NonError);
16486 }
16487
16488 Diag(Loc, diag_id) << &II;
16489 if (Corrected) {
16490 // If the correction is going to suggest an implicitly defined function,
16491 // skip the correction as not being a particularly good idea.
16492 bool Diagnose = true;
16493 if (const auto *D = Corrected.getCorrectionDecl())
16494 Diagnose = !D->isImplicit();
16495 if (Diagnose)
16496 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16497 /*ErrorRecovery*/ false);
16498 }
16499
16500 // If we found a prior declaration of this function, don't bother building
16501 // another one. We've already pushed that one into scope, so there's nothing
16502 // more to do.
16503 if (ExternCPrev)
16504 return ExternCPrev;
16505
16506 // Set a Declarator for the implicit definition: int foo();
16507 const char *Dummy;
16508 AttributeFactory attrFactory;
16509 DeclSpec DS(attrFactory);
16510 unsigned DiagID;
16511 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16513 (void)Error; // Silence warning.
16514 assert(!Error && "Error setting up implicit decl!");
16515 SourceLocation NoLoc;
16517 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16518 /*IsAmbiguous=*/false,
16519 /*LParenLoc=*/NoLoc,
16520 /*Params=*/nullptr,
16521 /*NumParams=*/0,
16522 /*EllipsisLoc=*/NoLoc,
16523 /*RParenLoc=*/NoLoc,
16524 /*RefQualifierIsLvalueRef=*/true,
16525 /*RefQualifierLoc=*/NoLoc,
16526 /*MutableLoc=*/NoLoc, EST_None,
16527 /*ESpecRange=*/SourceRange(),
16528 /*Exceptions=*/nullptr,
16529 /*ExceptionRanges=*/nullptr,
16530 /*NumExceptions=*/0,
16531 /*NoexceptExpr=*/nullptr,
16532 /*ExceptionSpecTokens=*/nullptr,
16533 /*DeclsInPrototype=*/{}, Loc, Loc,
16534 D),
16535 std::move(DS.getAttributes()), SourceLocation());
16536 D.SetIdentifier(&II, Loc);
16537
16538 // Insert this function into the enclosing block scope.
16539 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16540 FD->setImplicit();
16541
16543
16544 return FD;
16545}
16546
16548 FunctionDecl *FD) {
16549 if (FD->isInvalidDecl())
16550 return;
16551
16552 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16553 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16554 return;
16555
16556 std::optional<unsigned> AlignmentParam;
16557 bool IsNothrow = false;
16558 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16559 return;
16560
16561 // C++2a [basic.stc.dynamic.allocation]p4:
16562 // An allocation function that has a non-throwing exception specification
16563 // indicates failure by returning a null pointer value. Any other allocation
16564 // function never returns a null pointer value and indicates failure only by
16565 // throwing an exception [...]
16566 //
16567 // However, -fcheck-new invalidates this possible assumption, so don't add
16568 // NonNull when that is enabled.
16569 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16570 !getLangOpts().CheckNew)
16571 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16572
16573 // C++2a [basic.stc.dynamic.allocation]p2:
16574 // An allocation function attempts to allocate the requested amount of
16575 // storage. [...] If the request succeeds, the value returned by a
16576 // replaceable allocation function is a [...] pointer value p0 different
16577 // from any previously returned value p1 [...]
16578 //
16579 // However, this particular information is being added in codegen,
16580 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16581
16582 // C++2a [basic.stc.dynamic.allocation]p2:
16583 // An allocation function attempts to allocate the requested amount of
16584 // storage. If it is successful, it returns the address of the start of a
16585 // block of storage whose length in bytes is at least as large as the
16586 // requested size.
16587 if (!FD->hasAttr<AllocSizeAttr>()) {
16588 FD->addAttr(AllocSizeAttr::CreateImplicit(
16589 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16590 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16591 }
16592
16593 // C++2a [basic.stc.dynamic.allocation]p3:
16594 // For an allocation function [...], the pointer returned on a successful
16595 // call shall represent the address of storage that is aligned as follows:
16596 // (3.1) If the allocation function takes an argument of type
16597 // std​::​align_­val_­t, the storage will have the alignment
16598 // specified by the value of this argument.
16599 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16600 FD->addAttr(AllocAlignAttr::CreateImplicit(
16601 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16602 }
16603
16604 // FIXME:
16605 // C++2a [basic.stc.dynamic.allocation]p3:
16606 // For an allocation function [...], the pointer returned on a successful
16607 // call shall represent the address of storage that is aligned as follows:
16608 // (3.2) Otherwise, if the allocation function is named operator new[],
16609 // the storage is aligned for any object that does not have
16610 // new-extended alignment ([basic.align]) and is no larger than the
16611 // requested size.
16612 // (3.3) Otherwise, the storage is aligned for any object that does not
16613 // have new-extended alignment and is of the requested size.
16614}
16615
16617 if (FD->isInvalidDecl())
16618 return;
16619
16620 // If this is a built-in function, map its builtin attributes to
16621 // actual attributes.
16622 if (unsigned BuiltinID = FD->getBuiltinID()) {
16623 // Handle printf-formatting attributes.
16624 unsigned FormatIdx;
16625 bool HasVAListArg;
16626 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16627 if (!FD->hasAttr<FormatAttr>()) {
16628 const char *fmt = "printf";
16629 unsigned int NumParams = FD->getNumParams();
16630 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16631 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16632 fmt = "NSString";
16633 FD->addAttr(FormatAttr::CreateImplicit(Context,
16634 &Context.Idents.get(fmt),
16635 FormatIdx+1,
16636 HasVAListArg ? 0 : FormatIdx+2,
16637 FD->getLocation()));
16638 }
16639 }
16640 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16641 HasVAListArg)) {
16642 if (!FD->hasAttr<FormatAttr>())
16643 FD->addAttr(FormatAttr::CreateImplicit(Context,
16644 &Context.Idents.get("scanf"),
16645 FormatIdx+1,
16646 HasVAListArg ? 0 : FormatIdx+2,
16647 FD->getLocation()));
16648 }
16649
16650 // Handle automatically recognized callbacks.
16651 SmallVector<int, 4> Encoding;
16652 if (!FD->hasAttr<CallbackAttr>() &&
16653 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16654 FD->addAttr(CallbackAttr::CreateImplicit(
16655 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16656
16657 // Mark const if we don't care about errno and/or floating point exceptions
16658 // that are the only thing preventing the function from being const. This
16659 // allows IRgen to use LLVM intrinsics for such functions.
16660 bool NoExceptions =
16662 bool ConstWithoutErrnoAndExceptions =
16664 bool ConstWithoutExceptions =
16666 if (!FD->hasAttr<ConstAttr>() &&
16667 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16668 (!ConstWithoutErrnoAndExceptions ||
16669 (!getLangOpts().MathErrno && NoExceptions)) &&
16670 (!ConstWithoutExceptions || NoExceptions))
16671 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16672
16673 // We make "fma" on GNU or Windows const because we know it does not set
16674 // errno in those environments even though it could set errno based on the
16675 // C standard.
16676 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16677 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16678 !FD->hasAttr<ConstAttr>()) {
16679 switch (BuiltinID) {
16680 case Builtin::BI__builtin_fma:
16681 case Builtin::BI__builtin_fmaf:
16682 case Builtin::BI__builtin_fmal:
16683 case Builtin::BIfma:
16684 case Builtin::BIfmaf:
16685 case Builtin::BIfmal:
16686 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16687 break;
16688 default:
16689 break;
16690 }
16691 }
16692
16693 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16694 !FD->hasAttr<ReturnsTwiceAttr>())
16695 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16696 FD->getLocation()));
16697 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16698 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16699 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16700 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16701 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16702 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16703 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16704 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16705 // Add the appropriate attribute, depending on the CUDA compilation mode
16706 // and which target the builtin belongs to. For example, during host
16707 // compilation, aux builtins are __device__, while the rest are __host__.
16708 if (getLangOpts().CUDAIsDevice !=
16710 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16711 else
16712 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16713 }
16714
16715 // Add known guaranteed alignment for allocation functions.
16716 switch (BuiltinID) {
16717 case Builtin::BImemalign:
16718 case Builtin::BIaligned_alloc:
16719 if (!FD->hasAttr<AllocAlignAttr>())
16720 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16721 FD->getLocation()));
16722 break;
16723 default:
16724 break;
16725 }
16726
16727 // Add allocsize attribute for allocation functions.
16728 switch (BuiltinID) {
16729 case Builtin::BIcalloc:
16730 FD->addAttr(AllocSizeAttr::CreateImplicit(
16731 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16732 break;
16733 case Builtin::BImemalign:
16734 case Builtin::BIaligned_alloc:
16735 case Builtin::BIrealloc:
16736 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16737 ParamIdx(), FD->getLocation()));
16738 break;
16739 case Builtin::BImalloc:
16740 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16741 ParamIdx(), FD->getLocation()));
16742 break;
16743 default:
16744 break;
16745 }
16746 }
16747
16752
16753 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16754 // throw, add an implicit nothrow attribute to any extern "C" function we come
16755 // across.
16756 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16757 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16758 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16759 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16760 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16761 }
16762
16763 IdentifierInfo *Name = FD->getIdentifier();
16764 if (!Name)
16765 return;
16767 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16768 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16770 // Okay: this could be a libc/libm/Objective-C function we know
16771 // about.
16772 } else
16773 return;
16774
16775 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16776 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16777 // target-specific builtins, perhaps?
16778 if (!FD->hasAttr<FormatAttr>())
16779 FD->addAttr(FormatAttr::CreateImplicit(Context,
16780 &Context.Idents.get("printf"), 2,
16781 Name->isStr("vasprintf") ? 0 : 3,
16782 FD->getLocation()));
16783 }
16784
16785 if (Name->isStr("__CFStringMakeConstantString")) {
16786 // We already have a __builtin___CFStringMakeConstantString,
16787 // but builds that use -fno-constant-cfstrings don't go through that.
16788 if (!FD->hasAttr<FormatArgAttr>())
16789 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16790 FD->getLocation()));
16791 }
16792}
16793
16795 TypeSourceInfo *TInfo) {
16796 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16797 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16798
16799 if (!TInfo) {
16800 assert(D.isInvalidType() && "no declarator info for valid type");
16802 }
16803
16804 // Scope manipulation handled by caller.
16805 TypedefDecl *NewTD =
16807 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16808
16809 // Bail out immediately if we have an invalid declaration.
16810 if (D.isInvalidType()) {
16811 NewTD->setInvalidDecl();
16812 return NewTD;
16813 }
16814
16815 if (D.getDeclSpec().isModulePrivateSpecified()) {
16817 Diag(NewTD->getLocation(), diag::err_module_private_local)
16818 << 2 << NewTD
16819 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16821 D.getDeclSpec().getModulePrivateSpecLoc());
16822 else
16823 NewTD->setModulePrivate();
16824 }
16825
16826 // C++ [dcl.typedef]p8:
16827 // If the typedef declaration defines an unnamed class (or
16828 // enum), the first typedef-name declared by the declaration
16829 // to be that class type (or enum type) is used to denote the
16830 // class type (or enum type) for linkage purposes only.
16831 // We need to check whether the type was declared in the declaration.
16832 switch (D.getDeclSpec().getTypeSpecType()) {
16833 case TST_enum:
16834 case TST_struct:
16835 case TST_interface:
16836 case TST_union:
16837 case TST_class: {
16838 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16839 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16840 break;
16841 }
16842
16843 default:
16844 break;
16845 }
16846
16847 return NewTD;
16848}
16849
16851 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16852 QualType T = TI->getType();
16853
16854 if (T->isDependentType())
16855 return false;
16856
16857 // This doesn't use 'isIntegralType' despite the error message mentioning
16858 // integral type because isIntegralType would also allow enum types in C.
16859 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16860 if (BT->isInteger())
16861 return false;
16862
16863 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16864 << T << T->isBitIntType();
16865}
16866
16868 QualType EnumUnderlyingTy, bool IsFixed,
16869 const EnumDecl *Prev) {
16870 if (IsScoped != Prev->isScoped()) {
16871 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16872 << Prev->isScoped();
16873 Diag(Prev->getLocation(), diag::note_previous_declaration);
16874 return true;
16875 }
16876
16877 if (IsFixed && Prev->isFixed()) {
16878 if (!EnumUnderlyingTy->isDependentType() &&
16879 !Prev->getIntegerType()->isDependentType() &&
16880 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16881 Prev->getIntegerType())) {
16882 // TODO: Highlight the underlying type of the redeclaration.
16883 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16884 << EnumUnderlyingTy << Prev->getIntegerType();
16885 Diag(Prev->getLocation(), diag::note_previous_declaration)
16886 << Prev->getIntegerTypeRange();
16887 return true;
16888 }
16889 } else if (IsFixed != Prev->isFixed()) {
16890 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16891 << Prev->isFixed();
16892 Diag(Prev->getLocation(), diag::note_previous_declaration);
16893 return true;
16894 }
16895
16896 return false;
16897}
16898
16899/// Get diagnostic %select index for tag kind for
16900/// redeclaration diagnostic message.
16901/// WARNING: Indexes apply to particular diagnostics only!
16902///
16903/// \returns diagnostic %select index.
16905 switch (Tag) {
16907 return 0;
16909 return 1;
16910 case TagTypeKind::Class:
16911 return 2;
16912 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16913 }
16914}
16915
16916/// Determine if tag kind is a class-key compatible with
16917/// class for redeclaration (class, struct, or __interface).
16918///
16919/// \returns true iff the tag kind is compatible.
16921{
16922 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16924}
16925
16927 TagTypeKind TTK) {
16928 if (isa<TypedefDecl>(PrevDecl))
16929 return NTK_Typedef;
16930 else if (isa<TypeAliasDecl>(PrevDecl))
16931 return NTK_TypeAlias;
16932 else if (isa<ClassTemplateDecl>(PrevDecl))
16933 return NTK_Template;
16934 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16935 return NTK_TypeAliasTemplate;
16936 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16938 switch (TTK) {
16941 case TagTypeKind::Class:
16942 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16943 case TagTypeKind::Union:
16944 return NTK_NonUnion;
16945 case TagTypeKind::Enum:
16946 return NTK_NonEnum;
16947 }
16948 llvm_unreachable("invalid TTK");
16949}
16950
16952 TagTypeKind NewTag, bool isDefinition,
16953 SourceLocation NewTagLoc,
16954 const IdentifierInfo *Name) {
16955 // C++ [dcl.type.elab]p3:
16956 // The class-key or enum keyword present in the
16957 // elaborated-type-specifier shall agree in kind with the
16958 // declaration to which the name in the elaborated-type-specifier
16959 // refers. This rule also applies to the form of
16960 // elaborated-type-specifier that declares a class-name or
16961 // friend class since it can be construed as referring to the
16962 // definition of the class. Thus, in any
16963 // elaborated-type-specifier, the enum keyword shall be used to
16964 // refer to an enumeration (7.2), the union class-key shall be
16965 // used to refer to a union (clause 9), and either the class or
16966 // struct class-key shall be used to refer to a class (clause 9)
16967 // declared using the class or struct class-key.
16968 TagTypeKind OldTag = Previous->getTagKind();
16969 if (OldTag != NewTag &&
16971 return false;
16972
16973 // Tags are compatible, but we might still want to warn on mismatched tags.
16974 // Non-class tags can't be mismatched at this point.
16976 return true;
16977
16978 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16979 // by our warning analysis. We don't want to warn about mismatches with (eg)
16980 // declarations in system headers that are designed to be specialized, but if
16981 // a user asks us to warn, we should warn if their code contains mismatched
16982 // declarations.
16983 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16984 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16985 Loc);
16986 };
16987 if (IsIgnoredLoc(NewTagLoc))
16988 return true;
16989
16990 auto IsIgnored = [&](const TagDecl *Tag) {
16991 return IsIgnoredLoc(Tag->getLocation());
16992 };
16993 while (IsIgnored(Previous)) {
16994 Previous = Previous->getPreviousDecl();
16995 if (!Previous)
16996 return true;
16997 OldTag = Previous->getTagKind();
16998 }
16999
17000 bool isTemplate = false;
17001 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17002 isTemplate = Record->getDescribedClassTemplate();
17003
17005 if (OldTag != NewTag) {
17006 // In a template instantiation, do not offer fix-its for tag mismatches
17007 // since they usually mess up the template instead of fixing the problem.
17008 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17010 << getRedeclDiagFromTagKind(OldTag);
17011 // FIXME: Note previous location?
17012 }
17013 return true;
17014 }
17015
17016 if (isDefinition) {
17017 // On definitions, check all previous tags and issue a fix-it for each
17018 // one that doesn't match the current tag.
17019 if (Previous->getDefinition()) {
17020 // Don't suggest fix-its for redefinitions.
17021 return true;
17022 }
17023
17024 bool previousMismatch = false;
17025 for (const TagDecl *I : Previous->redecls()) {
17026 if (I->getTagKind() != NewTag) {
17027 // Ignore previous declarations for which the warning was disabled.
17028 if (IsIgnored(I))
17029 continue;
17030
17031 if (!previousMismatch) {
17032 previousMismatch = true;
17033 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17035 << getRedeclDiagFromTagKind(I->getTagKind());
17036 }
17037 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17039 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17041 }
17042 }
17043 return true;
17044 }
17045
17046 // Identify the prevailing tag kind: this is the kind of the definition (if
17047 // there is a non-ignored definition), or otherwise the kind of the prior
17048 // (non-ignored) declaration.
17049 const TagDecl *PrevDef = Previous->getDefinition();
17050 if (PrevDef && IsIgnored(PrevDef))
17051 PrevDef = nullptr;
17052 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17053 if (Redecl->getTagKind() != NewTag) {
17054 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17056 << getRedeclDiagFromTagKind(OldTag);
17057 Diag(Redecl->getLocation(), diag::note_previous_use);
17058
17059 // If there is a previous definition, suggest a fix-it.
17060 if (PrevDef) {
17061 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17065 }
17066 }
17067
17068 return true;
17069}
17070
17071/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17072/// from an outer enclosing namespace or file scope inside a friend declaration.
17073/// This should provide the commented out code in the following snippet:
17074/// namespace N {
17075/// struct X;
17076/// namespace M {
17077/// struct Y { friend struct /*N::*/ X; };
17078/// }
17079/// }
17081 SourceLocation NameLoc) {
17082 // While the decl is in a namespace, do repeated lookup of that name and see
17083 // if we get the same namespace back. If we do not, continue until
17084 // translation unit scope, at which point we have a fully qualified NNS.
17087 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17088 // This tag should be declared in a namespace, which can only be enclosed by
17089 // other namespaces. Bail if there's an anonymous namespace in the chain.
17090 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17091 if (!Namespace || Namespace->isAnonymousNamespace())
17092 return FixItHint();
17093 IdentifierInfo *II = Namespace->getIdentifier();
17094 Namespaces.push_back(II);
17095 NamedDecl *Lookup = SemaRef.LookupSingleName(
17096 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17097 if (Lookup == Namespace)
17098 break;
17099 }
17100
17101 // Once we have all the namespaces, reverse them to go outermost first, and
17102 // build an NNS.
17103 SmallString<64> Insertion;
17104 llvm::raw_svector_ostream OS(Insertion);
17105 if (DC->isTranslationUnit())
17106 OS << "::";
17107 std::reverse(Namespaces.begin(), Namespaces.end());
17108 for (auto *II : Namespaces)
17109 OS << II->getName() << "::";
17110 return FixItHint::CreateInsertion(NameLoc, Insertion);
17111}
17112
17113/// Determine whether a tag originally declared in context \p OldDC can
17114/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17115/// found a declaration in \p OldDC as a previous decl, perhaps through a
17116/// using-declaration).
17118 DeclContext *NewDC) {
17119 OldDC = OldDC->getRedeclContext();
17120 NewDC = NewDC->getRedeclContext();
17121
17122 if (OldDC->Equals(NewDC))
17123 return true;
17124
17125 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17126 // encloses the other).
17127 if (S.getLangOpts().MSVCCompat &&
17128 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17129 return true;
17130
17131 return false;
17132}
17133
17135Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17136 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17137 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17138 SourceLocation ModulePrivateLoc,
17139 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17140 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17141 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17142 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17143 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17144 // If this is not a definition, it must have a name.
17145 IdentifierInfo *OrigName = Name;
17146 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17147 "Nameless record must be a definition!");
17148 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17149
17150 OwnedDecl = false;
17152 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17153
17154 // FIXME: Check member specializations more carefully.
17155 bool isMemberSpecialization = false;
17156 bool Invalid = false;
17157
17158 // We only need to do this matching if we have template parameters
17159 // or a scope specifier, which also conveniently avoids this work
17160 // for non-C++ cases.
17161 if (TemplateParameterLists.size() > 0 ||
17162 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17163 TemplateParameterList *TemplateParams =
17165 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17166 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17167
17168 // C++23 [dcl.type.elab] p2:
17169 // If an elaborated-type-specifier is the sole constituent of a
17170 // declaration, the declaration is ill-formed unless it is an explicit
17171 // specialization, an explicit instantiation or it has one of the
17172 // following forms: [...]
17173 // C++23 [dcl.enum] p1:
17174 // If the enum-head-name of an opaque-enum-declaration contains a
17175 // nested-name-specifier, the declaration shall be an explicit
17176 // specialization.
17177 //
17178 // FIXME: Class template partial specializations can be forward declared
17179 // per CWG2213, but the resolution failed to allow qualified forward
17180 // declarations. This is almost certainly unintentional, so we allow them.
17181 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17182 !isMemberSpecialization)
17183 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17185
17186 if (TemplateParams) {
17187 if (Kind == TagTypeKind::Enum) {
17188 Diag(KWLoc, diag::err_enum_template);
17189 return true;
17190 }
17191
17192 if (TemplateParams->size() > 0) {
17193 // This is a declaration or definition of a class template (which may
17194 // be a member of another template).
17195
17196 if (Invalid)
17197 return true;
17198
17199 OwnedDecl = false;
17201 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17202 AS, ModulePrivateLoc,
17203 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17204 TemplateParameterLists.data(), SkipBody);
17205 return Result.get();
17206 } else {
17207 // The "template<>" header is extraneous.
17208 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17209 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17210 isMemberSpecialization = true;
17211 }
17212 }
17213
17214 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17215 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17216 return true;
17217 }
17218
17219 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17220 // C++23 [dcl.type.elab]p4:
17221 // If an elaborated-type-specifier appears with the friend specifier as
17222 // an entire member-declaration, the member-declaration shall have one
17223 // of the following forms:
17224 // friend class-key nested-name-specifier(opt) identifier ;
17225 // friend class-key simple-template-id ;
17226 // friend class-key nested-name-specifier template(opt)
17227 // simple-template-id ;
17228 //
17229 // Since enum is not a class-key, so declarations like "friend enum E;"
17230 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17231 // invalid, most implementations accept so we issue a pedantic warning.
17232 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17233 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17234 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17235 Diag(KWLoc, diag::note_enum_friend)
17236 << (ScopedEnum + ScopedEnumUsesClassTag);
17237 }
17238
17239 // Figure out the underlying type if this a enum declaration. We need to do
17240 // this early, because it's needed to detect if this is an incompatible
17241 // redeclaration.
17242 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17243 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17244
17245 if (Kind == TagTypeKind::Enum) {
17246 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17247 // No underlying type explicitly specified, or we failed to parse the
17248 // type, default to int.
17249 EnumUnderlying = Context.IntTy.getTypePtr();
17250 } else if (UnderlyingType.get()) {
17251 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17252 // integral type; any cv-qualification is ignored.
17253 TypeSourceInfo *TI = nullptr;
17254 GetTypeFromParser(UnderlyingType.get(), &TI);
17255 EnumUnderlying = TI;
17256
17258 // Recover by falling back to int.
17259 EnumUnderlying = Context.IntTy.getTypePtr();
17260
17263 EnumUnderlying = Context.IntTy.getTypePtr();
17264
17265 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17266 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17267 // of 'int'. However, if this is an unfixed forward declaration, don't set
17268 // the underlying type unless the user enables -fms-compatibility. This
17269 // makes unfixed forward declared enums incomplete and is more conforming.
17270 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17271 EnumUnderlying = Context.IntTy.getTypePtr();
17272 }
17273 }
17274
17275 DeclContext *SearchDC = CurContext;
17276 DeclContext *DC = CurContext;
17277 bool isStdBadAlloc = false;
17278 bool isStdAlignValT = false;
17279
17281 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17282 Redecl = RedeclarationKind::NotForRedeclaration;
17283
17284 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17285 /// implemented asks for structural equivalence checking, the returned decl
17286 /// here is passed back to the parser, allowing the tag body to be parsed.
17287 auto createTagFromNewDecl = [&]() -> TagDecl * {
17288 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17289 // If there is an identifier, use the location of the identifier as the
17290 // location of the decl, otherwise use the location of the struct/union
17291 // keyword.
17292 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17293 TagDecl *New = nullptr;
17294
17295 if (Kind == TagTypeKind::Enum) {
17296 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17297 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17298 // If this is an undefined enum, bail.
17299 if (TUK != TagUseKind::Definition && !Invalid)
17300 return nullptr;
17301 if (EnumUnderlying) {
17302 EnumDecl *ED = cast<EnumDecl>(New);
17303 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17305 else
17306 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17307 QualType EnumTy = ED->getIntegerType();
17310 : EnumTy);
17311 }
17312 } else { // struct/union
17313 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17314 nullptr);
17315 }
17316
17317 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17318 // Add alignment attributes if necessary; these attributes are checked
17319 // when the ASTContext lays out the structure.
17320 //
17321 // It is important for implementing the correct semantics that this
17322 // happen here (in ActOnTag). The #pragma pack stack is
17323 // maintained as a result of parser callbacks which can occur at
17324 // many points during the parsing of a struct declaration (because
17325 // the #pragma tokens are effectively skipped over during the
17326 // parsing of the struct).
17327 if (TUK == TagUseKind::Definition &&
17328 (!SkipBody || !SkipBody->ShouldSkip)) {
17331 }
17332 }
17334 return New;
17335 };
17336
17337 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17338 if (Name && SS.isNotEmpty()) {
17339 // We have a nested-name tag ('struct foo::bar').
17340
17341 // Check for invalid 'foo::'.
17342 if (SS.isInvalid()) {
17343 Name = nullptr;
17344 goto CreateNewDecl;
17345 }
17346
17347 // If this is a friend or a reference to a class in a dependent
17348 // context, don't try to make a decl for it.
17349 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17350 DC = computeDeclContext(SS, false);
17351 if (!DC) {
17352 IsDependent = true;
17353 return true;
17354 }
17355 } else {
17356 DC = computeDeclContext(SS, true);
17357 if (!DC) {
17358 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17359 << SS.getRange();
17360 return true;
17361 }
17362 }
17363
17364 if (RequireCompleteDeclContext(SS, DC))
17365 return true;
17366
17367 SearchDC = DC;
17368 // Look-up name inside 'foo::'.
17370
17371 if (Previous.isAmbiguous())
17372 return true;
17373
17374 if (Previous.empty()) {
17375 // Name lookup did not find anything. However, if the
17376 // nested-name-specifier refers to the current instantiation,
17377 // and that current instantiation has any dependent base
17378 // classes, we might find something at instantiation time: treat
17379 // this as a dependent elaborated-type-specifier.
17380 // But this only makes any sense for reference-like lookups.
17381 if (Previous.wasNotFoundInCurrentInstantiation() &&
17382 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17383 IsDependent = true;
17384 return true;
17385 }
17386
17387 // A tag 'foo::bar' must already exist.
17388 Diag(NameLoc, diag::err_not_tag_in_scope)
17389 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17390 Name = nullptr;
17391 Invalid = true;
17392 goto CreateNewDecl;
17393 }
17394 } else if (Name) {
17395 // C++14 [class.mem]p14:
17396 // If T is the name of a class, then each of the following shall have a
17397 // name different from T:
17398 // -- every member of class T that is itself a type
17399 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17400 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17401 return true;
17402
17403 // If this is a named struct, check to see if there was a previous forward
17404 // declaration or definition.
17405 // FIXME: We're looking into outer scopes here, even when we
17406 // shouldn't be. Doing so can result in ambiguities that we
17407 // shouldn't be diagnosing.
17408 LookupName(Previous, S);
17409
17410 // When declaring or defining a tag, ignore ambiguities introduced
17411 // by types using'ed into this scope.
17412 if (Previous.isAmbiguous() &&
17414 LookupResult::Filter F = Previous.makeFilter();
17415 while (F.hasNext()) {
17416 NamedDecl *ND = F.next();
17417 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17418 SearchDC->getRedeclContext()))
17419 F.erase();
17420 }
17421 F.done();
17422 }
17423
17424 // C++11 [namespace.memdef]p3:
17425 // If the name in a friend declaration is neither qualified nor
17426 // a template-id and the declaration is a function or an
17427 // elaborated-type-specifier, the lookup to determine whether
17428 // the entity has been previously declared shall not consider
17429 // any scopes outside the innermost enclosing namespace.
17430 //
17431 // MSVC doesn't implement the above rule for types, so a friend tag
17432 // declaration may be a redeclaration of a type declared in an enclosing
17433 // scope. They do implement this rule for friend functions.
17434 //
17435 // Does it matter that this should be by scope instead of by
17436 // semantic context?
17437 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17438 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17439 LookupResult::Filter F = Previous.makeFilter();
17440 bool FriendSawTagOutsideEnclosingNamespace = false;
17441 while (F.hasNext()) {
17442 NamedDecl *ND = F.next();
17444 if (DC->isFileContext() &&
17445 !EnclosingNS->Encloses(ND->getDeclContext())) {
17446 if (getLangOpts().MSVCCompat)
17447 FriendSawTagOutsideEnclosingNamespace = true;
17448 else
17449 F.erase();
17450 }
17451 }
17452 F.done();
17453
17454 // Diagnose this MSVC extension in the easy case where lookup would have
17455 // unambiguously found something outside the enclosing namespace.
17456 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17457 NamedDecl *ND = Previous.getFoundDecl();
17458 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17459 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17460 }
17461 }
17462
17463 // Note: there used to be some attempt at recovery here.
17464 if (Previous.isAmbiguous())
17465 return true;
17466
17467 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17468 // FIXME: This makes sure that we ignore the contexts associated
17469 // with C structs, unions, and enums when looking for a matching
17470 // tag declaration or definition. See the similar lookup tweak
17471 // in Sema::LookupName; is there a better way to deal with this?
17472 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17473 SearchDC = SearchDC->getParent();
17474 } else if (getLangOpts().CPlusPlus) {
17475 // Inside ObjCContainer want to keep it as a lexical decl context but go
17476 // past it (most often to TranslationUnit) to find the semantic decl
17477 // context.
17478 while (isa<ObjCContainerDecl>(SearchDC))
17479 SearchDC = SearchDC->getParent();
17480 }
17481 } else if (getLangOpts().CPlusPlus) {
17482 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17483 // TagDecl the same way as we skip it for named TagDecl.
17484 while (isa<ObjCContainerDecl>(SearchDC))
17485 SearchDC = SearchDC->getParent();
17486 }
17487
17488 if (Previous.isSingleResult() &&
17489 Previous.getFoundDecl()->isTemplateParameter()) {
17490 // Maybe we will complain about the shadowed template parameter.
17491 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17492 // Just pretend that we didn't see the previous declaration.
17493 Previous.clear();
17494 }
17495
17496 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17497 DC->Equals(getStdNamespace())) {
17498 if (Name->isStr("bad_alloc")) {
17499 // This is a declaration of or a reference to "std::bad_alloc".
17500 isStdBadAlloc = true;
17501
17502 // If std::bad_alloc has been implicitly declared (but made invisible to
17503 // name lookup), fill in this implicit declaration as the previous
17504 // declaration, so that the declarations get chained appropriately.
17505 if (Previous.empty() && StdBadAlloc)
17506 Previous.addDecl(getStdBadAlloc());
17507 } else if (Name->isStr("align_val_t")) {
17508 isStdAlignValT = true;
17509 if (Previous.empty() && StdAlignValT)
17510 Previous.addDecl(getStdAlignValT());
17511 }
17512 }
17513
17514 // If we didn't find a previous declaration, and this is a reference
17515 // (or friend reference), move to the correct scope. In C++, we
17516 // also need to do a redeclaration lookup there, just in case
17517 // there's a shadow friend decl.
17518 if (Name && Previous.empty() &&
17519 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17520 IsTemplateParamOrArg)) {
17521 if (Invalid) goto CreateNewDecl;
17522 assert(SS.isEmpty());
17523
17524 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17525 // C++ [basic.scope.pdecl]p5:
17526 // -- for an elaborated-type-specifier of the form
17527 //
17528 // class-key identifier
17529 //
17530 // if the elaborated-type-specifier is used in the
17531 // decl-specifier-seq or parameter-declaration-clause of a
17532 // function defined in namespace scope, the identifier is
17533 // declared as a class-name in the namespace that contains
17534 // the declaration; otherwise, except as a friend
17535 // declaration, the identifier is declared in the smallest
17536 // non-class, non-function-prototype scope that contains the
17537 // declaration.
17538 //
17539 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17540 // C structs and unions.
17541 //
17542 // It is an error in C++ to declare (rather than define) an enum
17543 // type, including via an elaborated type specifier. We'll
17544 // diagnose that later; for now, declare the enum in the same
17545 // scope as we would have picked for any other tag type.
17546 //
17547 // GNU C also supports this behavior as part of its incomplete
17548 // enum types extension, while GNU C++ does not.
17549 //
17550 // Find the context where we'll be declaring the tag.
17551 // FIXME: We would like to maintain the current DeclContext as the
17552 // lexical context,
17553 SearchDC = getTagInjectionContext(SearchDC);
17554
17555 // Find the scope where we'll be declaring the tag.
17557 } else {
17558 assert(TUK == TagUseKind::Friend);
17559 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17560
17561 // C++ [namespace.memdef]p3:
17562 // If a friend declaration in a non-local class first declares a
17563 // class or function, the friend class or function is a member of
17564 // the innermost enclosing namespace.
17565 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17566 : SearchDC->getEnclosingNamespaceContext();
17567 }
17568
17569 // In C++, we need to do a redeclaration lookup to properly
17570 // diagnose some problems.
17571 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17572 // hidden declaration so that we don't get ambiguity errors when using a
17573 // type declared by an elaborated-type-specifier. In C that is not correct
17574 // and we should instead merge compatible types found by lookup.
17575 if (getLangOpts().CPlusPlus) {
17576 // FIXME: This can perform qualified lookups into function contexts,
17577 // which are meaningless.
17578 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17579 LookupQualifiedName(Previous, SearchDC);
17580 } else {
17581 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17582 LookupName(Previous, S);
17583 }
17584 }
17585
17586 // If we have a known previous declaration to use, then use it.
17587 if (Previous.empty() && SkipBody && SkipBody->Previous)
17588 Previous.addDecl(SkipBody->Previous);
17589
17590 if (!Previous.empty()) {
17591 NamedDecl *PrevDecl = Previous.getFoundDecl();
17592 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17593
17594 // It's okay to have a tag decl in the same scope as a typedef
17595 // which hides a tag decl in the same scope. Finding this
17596 // with a redeclaration lookup can only actually happen in C++.
17597 //
17598 // This is also okay for elaborated-type-specifiers, which is
17599 // technically forbidden by the current standard but which is
17600 // okay according to the likely resolution of an open issue;
17601 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17602 if (getLangOpts().CPlusPlus) {
17603 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17604 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17605 TagDecl *Tag = TT->getDecl();
17606 if (Tag->getDeclName() == Name &&
17607 Tag->getDeclContext()->getRedeclContext()
17608 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17609 PrevDecl = Tag;
17610 Previous.clear();
17611 Previous.addDecl(Tag);
17612 Previous.resolveKind();
17613 }
17614 }
17615 }
17616 }
17617
17618 // If this is a redeclaration of a using shadow declaration, it must
17619 // declare a tag in the same context. In MSVC mode, we allow a
17620 // redefinition if either context is within the other.
17621 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17622 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17623 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17624 TUK != TagUseKind::Friend &&
17625 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17626 !(OldTag && isAcceptableTagRedeclContext(
17627 *this, OldTag->getDeclContext(), SearchDC))) {
17628 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17629 Diag(Shadow->getTargetDecl()->getLocation(),
17630 diag::note_using_decl_target);
17631 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17632 << 0;
17633 // Recover by ignoring the old declaration.
17634 Previous.clear();
17635 goto CreateNewDecl;
17636 }
17637 }
17638
17639 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17640 // If this is a use of a previous tag, or if the tag is already declared
17641 // in the same scope (so that the definition/declaration completes or
17642 // rementions the tag), reuse the decl.
17643 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17644 isDeclInScope(DirectPrevDecl, SearchDC, S,
17645 SS.isNotEmpty() || isMemberSpecialization)) {
17646 // Make sure that this wasn't declared as an enum and now used as a
17647 // struct or something similar.
17648 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17649 TUK == TagUseKind::Definition, KWLoc,
17650 Name)) {
17651 bool SafeToContinue =
17652 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17653 Kind != TagTypeKind::Enum);
17654 if (SafeToContinue)
17655 Diag(KWLoc, diag::err_use_with_wrong_tag)
17656 << Name
17658 PrevTagDecl->getKindName());
17659 else
17660 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17661 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17662
17663 if (SafeToContinue)
17664 Kind = PrevTagDecl->getTagKind();
17665 else {
17666 // Recover by making this an anonymous redefinition.
17667 Name = nullptr;
17668 Previous.clear();
17669 Invalid = true;
17670 }
17671 }
17672
17673 if (Kind == TagTypeKind::Enum &&
17674 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17675 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17676 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
17677 return PrevTagDecl;
17678
17679 QualType EnumUnderlyingTy;
17680 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17681 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17682 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17683 EnumUnderlyingTy = QualType(T, 0);
17684
17685 // All conflicts with previous declarations are recovered by
17686 // returning the previous declaration, unless this is a definition,
17687 // in which case we want the caller to bail out.
17688 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17689 ScopedEnum, EnumUnderlyingTy,
17690 IsFixed, PrevEnum))
17691 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
17692 }
17693
17694 // C++11 [class.mem]p1:
17695 // A member shall not be declared twice in the member-specification,
17696 // except that a nested class or member class template can be declared
17697 // and then later defined.
17698 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
17699 S->isDeclScope(PrevDecl)) {
17700 Diag(NameLoc, diag::ext_member_redeclared);
17701 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17702 }
17703
17704 if (!Invalid) {
17705 // If this is a use, just return the declaration we found, unless
17706 // we have attributes.
17707 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17708 if (!Attrs.empty()) {
17709 // FIXME: Diagnose these attributes. For now, we create a new
17710 // declaration to hold them.
17711 } else if (TUK == TagUseKind::Reference &&
17712 (PrevTagDecl->getFriendObjectKind() ==
17714 PrevDecl->getOwningModule() != getCurrentModule()) &&
17715 SS.isEmpty()) {
17716 // This declaration is a reference to an existing entity, but
17717 // has different visibility from that entity: it either makes
17718 // a friend visible or it makes a type visible in a new module.
17719 // In either case, create a new declaration. We only do this if
17720 // the declaration would have meant the same thing if no prior
17721 // declaration were found, that is, if it was found in the same
17722 // scope where we would have injected a declaration.
17723 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17724 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17725 return PrevTagDecl;
17726 // This is in the injected scope, create a new declaration in
17727 // that scope.
17729 } else {
17730 return PrevTagDecl;
17731 }
17732 }
17733
17734 // Diagnose attempts to redefine a tag.
17735 if (TUK == TagUseKind::Definition) {
17736 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17737 // If we're defining a specialization and the previous definition
17738 // is from an implicit instantiation, don't emit an error
17739 // here; we'll catch this in the general case below.
17740 bool IsExplicitSpecializationAfterInstantiation = false;
17741 if (isMemberSpecialization) {
17742 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17743 IsExplicitSpecializationAfterInstantiation =
17744 RD->getTemplateSpecializationKind() !=
17746 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17747 IsExplicitSpecializationAfterInstantiation =
17748 ED->getTemplateSpecializationKind() !=
17750 }
17751
17752 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17753 // not keep more that one definition around (merge them). However,
17754 // ensure the decl passes the structural compatibility check in
17755 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17756 NamedDecl *Hidden = nullptr;
17757 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17758 // There is a definition of this tag, but it is not visible. We
17759 // explicitly make use of C++'s one definition rule here, and
17760 // assume that this definition is identical to the hidden one
17761 // we already have. Make the existing definition visible and
17762 // use it in place of this one.
17763 if (!getLangOpts().CPlusPlus) {
17764 // Postpone making the old definition visible until after we
17765 // complete parsing the new one and do the structural
17766 // comparison.
17767 SkipBody->CheckSameAsPrevious = true;
17768 SkipBody->New = createTagFromNewDecl();
17769 SkipBody->Previous = Def;
17770 return Def;
17771 } else {
17772 SkipBody->ShouldSkip = true;
17773 SkipBody->Previous = Def;
17775 // Carry on and handle it like a normal definition. We'll
17776 // skip starting the definition later.
17777 }
17778 } else if (!IsExplicitSpecializationAfterInstantiation) {
17779 // A redeclaration in function prototype scope in C isn't
17780 // visible elsewhere, so merely issue a warning.
17781 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17782 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17783 else
17784 Diag(NameLoc, diag::err_redefinition) << Name;
17786 NameLoc.isValid() ? NameLoc : KWLoc);
17787 // If this is a redefinition, recover by making this
17788 // struct be anonymous, which will make any later
17789 // references get the previous definition.
17790 Name = nullptr;
17791 Previous.clear();
17792 Invalid = true;
17793 }
17794 } else {
17795 // If the type is currently being defined, complain
17796 // about a nested redefinition.
17797 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17798 if (TD->isBeingDefined()) {
17799 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17800 Diag(PrevTagDecl->getLocation(),
17801 diag::note_previous_definition);
17802 Name = nullptr;
17803 Previous.clear();
17804 Invalid = true;
17805 }
17806 }
17807
17808 // Okay, this is definition of a previously declared or referenced
17809 // tag. We're going to create a new Decl for it.
17810 }
17811
17812 // Okay, we're going to make a redeclaration. If this is some kind
17813 // of reference, make sure we build the redeclaration in the same DC
17814 // as the original, and ignore the current access specifier.
17815 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17816 SearchDC = PrevTagDecl->getDeclContext();
17817 AS = AS_none;
17818 }
17819 }
17820 // If we get here we have (another) forward declaration or we
17821 // have a definition. Just create a new decl.
17822
17823 } else {
17824 // If we get here, this is a definition of a new tag type in a nested
17825 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17826 // new decl/type. We set PrevDecl to NULL so that the entities
17827 // have distinct types.
17828 Previous.clear();
17829 }
17830 // If we get here, we're going to create a new Decl. If PrevDecl
17831 // is non-NULL, it's a definition of the tag declared by
17832 // PrevDecl. If it's NULL, we have a new definition.
17833
17834 // Otherwise, PrevDecl is not a tag, but was found with tag
17835 // lookup. This is only actually possible in C++, where a few
17836 // things like templates still live in the tag namespace.
17837 } else {
17838 // Use a better diagnostic if an elaborated-type-specifier
17839 // found the wrong kind of type on the first
17840 // (non-redeclaration) lookup.
17841 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
17842 !Previous.isForRedeclaration()) {
17843 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17844 Diag(NameLoc, diag::err_tag_reference_non_tag)
17845 << PrevDecl << NTK << llvm::to_underlying(Kind);
17846 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17847 Invalid = true;
17848
17849 // Otherwise, only diagnose if the declaration is in scope.
17850 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17851 SS.isNotEmpty() || isMemberSpecialization)) {
17852 // do nothing
17853
17854 // Diagnose implicit declarations introduced by elaborated types.
17855 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17856 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17857 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17858 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17859 Invalid = true;
17860
17861 // Otherwise it's a declaration. Call out a particularly common
17862 // case here.
17863 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17864 unsigned Kind = 0;
17865 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17866 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17867 << Name << Kind << TND->getUnderlyingType();
17868 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17869 Invalid = true;
17870
17871 // Otherwise, diagnose.
17872 } else {
17873 // The tag name clashes with something else in the target scope,
17874 // issue an error and recover by making this tag be anonymous.
17875 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17876 notePreviousDefinition(PrevDecl, NameLoc);
17877 Name = nullptr;
17878 Invalid = true;
17879 }
17880
17881 // The existing declaration isn't relevant to us; we're in a
17882 // new scope, so clear out the previous declaration.
17883 Previous.clear();
17884 }
17885 }
17886
17887CreateNewDecl:
17888
17889 TagDecl *PrevDecl = nullptr;
17890 if (Previous.isSingleResult())
17891 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17892
17893 // If there is an identifier, use the location of the identifier as the
17894 // location of the decl, otherwise use the location of the struct/union
17895 // keyword.
17896 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17897
17898 // Otherwise, create a new declaration. If there is a previous
17899 // declaration of the same entity, the two will be linked via
17900 // PrevDecl.
17901 TagDecl *New;
17902
17903 if (Kind == TagTypeKind::Enum) {
17904 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17905 // enum X { A, B, C } D; D should chain to X.
17906 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17907 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17908 ScopedEnumUsesClassTag, IsFixed);
17909
17910 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17911 StdAlignValT = cast<EnumDecl>(New);
17912
17913 // If this is an undefined enum, warn.
17914 if (TUK != TagUseKind::Definition && !Invalid) {
17915 TagDecl *Def;
17916 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17917 // C++0x: 7.2p2: opaque-enum-declaration.
17918 // Conflicts are diagnosed above. Do nothing.
17919 }
17920 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17921 Diag(Loc, diag::ext_forward_ref_enum_def)
17922 << New;
17923 Diag(Def->getLocation(), diag::note_previous_definition);
17924 } else {
17925 unsigned DiagID = diag::ext_forward_ref_enum;
17926 if (getLangOpts().MSVCCompat)
17927 DiagID = diag::ext_ms_forward_ref_enum;
17928 else if (getLangOpts().CPlusPlus)
17929 DiagID = diag::err_forward_ref_enum;
17930 Diag(Loc, DiagID);
17931 }
17932 }
17933
17934 if (EnumUnderlying) {
17935 EnumDecl *ED = cast<EnumDecl>(New);
17936 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17938 else
17939 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
17940 QualType EnumTy = ED->getIntegerType();
17943 : EnumTy);
17944 assert(ED->isComplete() && "enum with type should be complete");
17945 }
17946 } else {
17947 // struct/union/class
17948
17949 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17950 // struct X { int A; } D; D should chain to X.
17951 if (getLangOpts().CPlusPlus) {
17952 // FIXME: Look for a way to use RecordDecl for simple structs.
17953 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17954 cast_or_null<CXXRecordDecl>(PrevDecl));
17955
17956 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17957 StdBadAlloc = cast<CXXRecordDecl>(New);
17958 } else
17959 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17960 cast_or_null<RecordDecl>(PrevDecl));
17961 }
17962
17963 // Only C23 and later allow defining new types in 'offsetof()'.
17964 if (OOK != OOK_Outside && TUK == TagUseKind::Definition &&
17966 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17967 << (OOK == OOK_Macro) << New->getSourceRange();
17968
17969 // C++11 [dcl.type]p3:
17970 // A type-specifier-seq shall not define a class or enumeration [...].
17971 if (!Invalid && getLangOpts().CPlusPlus &&
17972 (IsTypeSpecifier || IsTemplateParamOrArg) &&
17973 TUK == TagUseKind::Definition) {
17974 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17975 << Context.getTagDeclType(New);
17976 Invalid = true;
17977 }
17978
17980 DC->getDeclKind() == Decl::Enum) {
17981 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17982 << Context.getTagDeclType(New);
17983 Invalid = true;
17984 }
17985
17986 // Maybe add qualifier info.
17987 if (SS.isNotEmpty()) {
17988 if (SS.isSet()) {
17989 // If this is either a declaration or a definition, check the
17990 // nested-name-specifier against the current context.
17991 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
17992 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17993 /*TemplateId=*/nullptr,
17994 isMemberSpecialization))
17995 Invalid = true;
17996
17998 if (TemplateParameterLists.size() > 0) {
17999 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18000 }
18001 }
18002 else
18003 Invalid = true;
18004 }
18005
18006 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18007 // Add alignment attributes if necessary; these attributes are checked when
18008 // the ASTContext lays out the structure.
18009 //
18010 // It is important for implementing the correct semantics that this
18011 // happen here (in ActOnTag). The #pragma pack stack is
18012 // maintained as a result of parser callbacks which can occur at
18013 // many points during the parsing of a struct declaration (because
18014 // the #pragma tokens are effectively skipped over during the
18015 // parsing of the struct).
18016 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18019 }
18020 }
18021
18022 if (ModulePrivateLoc.isValid()) {
18023 if (isMemberSpecialization)
18024 Diag(New->getLocation(), diag::err_module_private_specialization)
18025 << 2
18026 << FixItHint::CreateRemoval(ModulePrivateLoc);
18027 // __module_private__ does not apply to local classes. However, we only
18028 // diagnose this as an error when the declaration specifiers are
18029 // freestanding. Here, we just ignore the __module_private__.
18030 else if (!SearchDC->isFunctionOrMethod())
18031 New->setModulePrivate();
18032 }
18033
18034 // If this is a specialization of a member class (of a class template),
18035 // check the specialization.
18036 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18037 Invalid = true;
18038
18039 // If we're declaring or defining a tag in function prototype scope in C,
18040 // note that this type can only be used within the function and add it to
18041 // the list of decls to inject into the function definition scope.
18042 if ((Name || Kind == TagTypeKind::Enum) &&
18043 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18044 if (getLangOpts().CPlusPlus) {
18045 // C++ [dcl.fct]p6:
18046 // Types shall not be defined in return or parameter types.
18047 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18048 Diag(Loc, diag::err_type_defined_in_param_type)
18049 << Name;
18050 Invalid = true;
18051 }
18052 if (TUK == TagUseKind::Declaration)
18053 Invalid = true;
18054 } else if (!PrevDecl) {
18055 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
18056 }
18057 }
18058
18059 if (Invalid)
18060 New->setInvalidDecl();
18061
18062 // Set the lexical context. If the tag has a C++ scope specifier, the
18063 // lexical context will be different from the semantic context.
18065
18066 // Mark this as a friend decl if applicable.
18067 // In Microsoft mode, a friend declaration also acts as a forward
18068 // declaration so we always pass true to setObjectOfFriendDecl to make
18069 // the tag name visible.
18070 if (TUK == TagUseKind::Friend)
18071 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18072
18073 // Set the access specifier.
18074 if (!Invalid && SearchDC->isRecord())
18075 SetMemberAccessSpecifier(New, PrevDecl, AS);
18076
18077 if (PrevDecl)
18078 CheckRedeclarationInModule(New, PrevDecl);
18079
18080 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
18081 New->startDefinition();
18082
18083 ProcessDeclAttributeList(S, New, Attrs);
18084 AddPragmaAttributes(S, New);
18085
18086 // If this has an identifier, add it to the scope stack.
18087 if (TUK == TagUseKind::Friend) {
18088 // We might be replacing an existing declaration in the lookup tables;
18089 // if so, borrow its access specifier.
18090 if (PrevDecl)
18091 New->setAccess(PrevDecl->getAccess());
18092
18094 DC->makeDeclVisibleInContext(New);
18095 if (Name) // can be null along some error paths
18096 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18097 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18098 } else if (Name) {
18099 S = getNonFieldDeclScope(S);
18100 PushOnScopeChains(New, S, true);
18101 } else {
18102 CurContext->addDecl(New);
18103 }
18104
18105 // If this is the C FILE type, notify the AST context.
18106 if (IdentifierInfo *II = New->getIdentifier())
18107 if (!New->isInvalidDecl() &&
18109 II->isStr("FILE"))
18110 Context.setFILEDecl(New);
18111
18112 if (PrevDecl)
18113 mergeDeclAttributes(New, PrevDecl);
18114
18115 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18118 }
18119
18120 // If there's a #pragma GCC visibility in scope, set the visibility of this
18121 // record.
18123
18124 if (isMemberSpecialization && !New->isInvalidDecl())
18126
18127 OwnedDecl = true;
18128 // In C++, don't return an invalid declaration. We can't recover well from
18129 // the cases where we make the type anonymous.
18130 if (Invalid && getLangOpts().CPlusPlus) {
18131 if (New->isBeingDefined())
18132 if (auto RD = dyn_cast<RecordDecl>(New))
18133 RD->completeDefinition();
18134 return true;
18135 } else if (SkipBody && SkipBody->ShouldSkip) {
18136 return SkipBody->Previous;
18137 } else {
18138 return New;
18139 }
18140}
18141
18144 TagDecl *Tag = cast<TagDecl>(TagD);
18145
18146 // Enter the tag context.
18147 PushDeclContext(S, Tag);
18148
18150
18151 // If there's a #pragma GCC visibility in scope, set the visibility of this
18152 // record.
18154}
18155
18157 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18158 return false;
18159
18160 // Make the previous decl visible.
18162 return true;
18163}
18164
18166 SourceLocation FinalLoc,
18167 bool IsFinalSpelledSealed,
18168 bool IsAbstract,
18169 SourceLocation LBraceLoc) {
18171 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
18172
18173 FieldCollector->StartClass();
18174
18175 if (!Record->getIdentifier())
18176 return;
18177
18178 if (IsAbstract)
18179 Record->markAbstract();
18180
18181 if (FinalLoc.isValid()) {
18182 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18183 IsFinalSpelledSealed
18184 ? FinalAttr::Keyword_sealed
18185 : FinalAttr::Keyword_final));
18186 }
18187 // C++ [class]p2:
18188 // [...] The class-name is also inserted into the scope of the
18189 // class itself; this is known as the injected-class-name. For
18190 // purposes of access checking, the injected-class-name is treated
18191 // as if it were a public member name.
18192 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18193 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18194 Record->getLocation(), Record->getIdentifier(),
18195 /*PrevDecl=*/nullptr,
18196 /*DelayTypeCreation=*/true);
18197 Context.getTypeDeclType(InjectedClassName, Record);
18198 InjectedClassName->setImplicit();
18199 InjectedClassName->setAccess(AS_public);
18200 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18201 InjectedClassName->setDescribedClassTemplate(Template);
18202 PushOnScopeChains(InjectedClassName, S);
18203 assert(InjectedClassName->isInjectedClassName() &&
18204 "Broken injected-class-name");
18205}
18206
18208 SourceRange BraceRange) {
18210 TagDecl *Tag = cast<TagDecl>(TagD);
18211 Tag->setBraceRange(BraceRange);
18212
18213 // Make sure we "complete" the definition even it is invalid.
18214 if (Tag->isBeingDefined()) {
18215 assert(Tag->isInvalidDecl() && "We should already have completed it");
18216 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18217 RD->completeDefinition();
18218 }
18219
18220 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18221 FieldCollector->FinishClass();
18222 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18223 auto *Def = RD->getDefinition();
18224 assert(Def && "The record is expected to have a completed definition");
18225 unsigned NumInitMethods = 0;
18226 for (auto *Method : Def->methods()) {
18227 if (!Method->getIdentifier())
18228 continue;
18229 if (Method->getName() == "__init")
18230 NumInitMethods++;
18231 }
18232 if (NumInitMethods > 1 || !Def->hasInitMethod())
18233 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18234 }
18235
18236 // If we're defining a dynamic class in a module interface unit, we always
18237 // need to produce the vtable for it, even if the vtable is not used in the
18238 // current TU.
18239 //
18240 // The case where the current class is not dynamic is handled in
18241 // MarkVTableUsed.
18242 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
18243 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
18244 }
18245
18246 // Exit this scope of this tag's definition.
18248
18249 if (getCurLexicalContext()->isObjCContainer() &&
18250 Tag->getDeclContext()->isFileContext())
18251 Tag->setTopLevelDeclInObjCContainer();
18252
18253 // Notify the consumer that we've defined a tag.
18254 if (!Tag->isInvalidDecl())
18256
18257 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18258 // from XLs and instead matches the XL #pragma pack(1) behavior.
18259 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18260 AlignPackStack.hasValue()) {
18261 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18262 // Only diagnose #pragma align(packed).
18263 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18264 return;
18265 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18266 if (!RD)
18267 return;
18268 // Only warn if there is at least 1 bitfield member.
18269 if (llvm::any_of(RD->fields(),
18270 [](const FieldDecl *FD) { return FD->isBitField(); }))
18271 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18272 }
18273}
18274
18277 TagDecl *Tag = cast<TagDecl>(TagD);
18278 Tag->setInvalidDecl();
18279
18280 // Make sure we "complete" the definition even it is invalid.
18281 if (Tag->isBeingDefined()) {
18282 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18283 RD->completeDefinition();
18284 }
18285
18286 // We're undoing ActOnTagStartDefinition here, not
18287 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18288 // the FieldCollector.
18289
18291}
18292
18293// Note that FieldName may be null for anonymous bitfields.
18295 const IdentifierInfo *FieldName,
18296 QualType FieldTy, bool IsMsStruct,
18297 Expr *BitWidth) {
18298 assert(BitWidth);
18299 if (BitWidth->containsErrors())
18300 return ExprError();
18301
18302 // C99 6.7.2.1p4 - verify the field type.
18303 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18304 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18305 // Handle incomplete and sizeless types with a specific error.
18306 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18307 diag::err_field_incomplete_or_sizeless))
18308 return ExprError();
18309 if (FieldName)
18310 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18311 << FieldName << FieldTy << BitWidth->getSourceRange();
18312 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18313 << FieldTy << BitWidth->getSourceRange();
18314 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18316 return ExprError();
18317
18318 // If the bit-width is type- or value-dependent, don't try to check
18319 // it now.
18320 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18321 return BitWidth;
18322
18323 llvm::APSInt Value;
18325 if (ICE.isInvalid())
18326 return ICE;
18327 BitWidth = ICE.get();
18328
18329 // Zero-width bitfield is ok for anonymous field.
18330 if (Value == 0 && FieldName)
18331 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18332 << FieldName << BitWidth->getSourceRange();
18333
18334 if (Value.isSigned() && Value.isNegative()) {
18335 if (FieldName)
18336 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18337 << FieldName << toString(Value, 10);
18338 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18339 << toString(Value, 10);
18340 }
18341
18342 // The size of the bit-field must not exceed our maximum permitted object
18343 // size.
18344 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18345 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18346 << !FieldName << FieldName << toString(Value, 10);
18347 }
18348
18349 if (!FieldTy->isDependentType()) {
18350 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18351 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18352 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18353
18354 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18355 // ABI.
18356 bool CStdConstraintViolation =
18357 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18358 bool MSBitfieldViolation =
18359 Value.ugt(TypeStorageSize) &&
18360 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18361 if (CStdConstraintViolation || MSBitfieldViolation) {
18362 unsigned DiagWidth =
18363 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18364 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18365 << (bool)FieldName << FieldName << toString(Value, 10)
18366 << !CStdConstraintViolation << DiagWidth;
18367 }
18368
18369 // Warn on types where the user might conceivably expect to get all
18370 // specified bits as value bits: that's all integral types other than
18371 // 'bool'.
18372 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18373 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18374 << FieldName << toString(Value, 10)
18375 << (unsigned)TypeWidth;
18376 }
18377 }
18378
18379 return BitWidth;
18380}
18381
18383 Declarator &D, Expr *BitfieldWidth) {
18384 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18385 D, BitfieldWidth,
18386 /*InitStyle=*/ICIS_NoInit, AS_public);
18387 return Res;
18388}
18389
18391 SourceLocation DeclStart,
18392 Declarator &D, Expr *BitWidth,
18393 InClassInitStyle InitStyle,
18394 AccessSpecifier AS) {
18395 if (D.isDecompositionDeclarator()) {
18396 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18397 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18398 << Decomp.getSourceRange();
18399 return nullptr;
18400 }
18401
18402 const IdentifierInfo *II = D.getIdentifier();
18403 SourceLocation Loc = DeclStart;
18404 if (II) Loc = D.getIdentifierLoc();
18405
18407 QualType T = TInfo->getType();
18408 if (getLangOpts().CPlusPlus) {
18410
18411 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18413 D.setInvalidType();
18414 T = Context.IntTy;
18416 }
18417 }
18418
18419 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18420
18421 if (D.getDeclSpec().isInlineSpecified())
18422 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18423 << getLangOpts().CPlusPlus17;
18424 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18425 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18426 diag::err_invalid_thread)
18428
18429 // Check to see if this name was declared as a member previously
18430 NamedDecl *PrevDecl = nullptr;
18432 RedeclarationKind::ForVisibleRedeclaration);
18433 LookupName(Previous, S);
18434 switch (Previous.getResultKind()) {
18437 PrevDecl = Previous.getAsSingle<NamedDecl>();
18438 break;
18439
18441 PrevDecl = Previous.getRepresentativeDecl();
18442 break;
18443
18447 break;
18448 }
18449 Previous.suppressDiagnostics();
18450
18451 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18452 // Maybe we will complain about the shadowed template parameter.
18453 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18454 // Just pretend that we didn't see the previous declaration.
18455 PrevDecl = nullptr;
18456 }
18457
18458 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18459 PrevDecl = nullptr;
18460
18461 bool Mutable
18462 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18463 SourceLocation TSSL = D.getBeginLoc();
18464 FieldDecl *NewFD
18465 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18466 TSSL, AS, PrevDecl, &D);
18467
18468 if (NewFD->isInvalidDecl())
18469 Record->setInvalidDecl();
18470
18471 if (D.getDeclSpec().isModulePrivateSpecified())
18472 NewFD->setModulePrivate();
18473
18474 if (NewFD->isInvalidDecl() && PrevDecl) {
18475 // Don't introduce NewFD into scope; there's already something
18476 // with the same name in the same scope.
18477 } else if (II) {
18478 PushOnScopeChains(NewFD, S);
18479 } else
18480 Record->addDecl(NewFD);
18481
18482 return NewFD;
18483}
18484
18486 TypeSourceInfo *TInfo,
18488 bool Mutable, Expr *BitWidth,
18489 InClassInitStyle InitStyle,
18490 SourceLocation TSSL,
18491 AccessSpecifier AS, NamedDecl *PrevDecl,
18492 Declarator *D) {
18493 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18494 bool InvalidDecl = false;
18495 if (D) InvalidDecl = D->isInvalidType();
18496
18497 // If we receive a broken type, recover by assuming 'int' and
18498 // marking this declaration as invalid.
18499 if (T.isNull() || T->containsErrors()) {
18500 InvalidDecl = true;
18501 T = Context.IntTy;
18502 }
18503
18505 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18506 bool isIncomplete =
18507 LangOpts.HLSL // HLSL allows sizeless builtin types
18508 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
18510 diag::err_field_incomplete_or_sizeless);
18511 if (isIncomplete) {
18512 // Fields of incomplete type force their record to be invalid.
18513 Record->setInvalidDecl();
18514 InvalidDecl = true;
18515 } else {
18516 NamedDecl *Def;
18517 EltTy->isIncompleteType(&Def);
18518 if (Def && Def->isInvalidDecl()) {
18519 Record->setInvalidDecl();
18520 InvalidDecl = true;
18521 }
18522 }
18523 }
18524
18525 // TR 18037 does not allow fields to be declared with address space
18526 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18528 Diag(Loc, diag::err_field_with_address_space);
18529 Record->setInvalidDecl();
18530 InvalidDecl = true;
18531 }
18532
18533 if (LangOpts.OpenCL) {
18534 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18535 // used as structure or union field: image, sampler, event or block types.
18536 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18537 T->isBlockPointerType()) {
18538 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18539 Record->setInvalidDecl();
18540 InvalidDecl = true;
18541 }
18542 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18543 // is enabled.
18544 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18545 "__cl_clang_bitfields", LangOpts)) {
18546 Diag(Loc, diag::err_opencl_bitfields);
18547 InvalidDecl = true;
18548 }
18549 }
18550
18551 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18552 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18553 T.hasQualifiers()) {
18554 InvalidDecl = true;
18555 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18556 }
18557
18558 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18559 // than a variably modified type.
18560 if (!InvalidDecl && T->isVariablyModifiedType()) {
18562 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18563 InvalidDecl = true;
18564 }
18565
18566 // Fields can not have abstract class types
18567 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18568 diag::err_abstract_type_in_decl,
18570 InvalidDecl = true;
18571
18572 if (InvalidDecl)
18573 BitWidth = nullptr;
18574 // If this is declared as a bit-field, check the bit-field.
18575 if (BitWidth) {
18576 BitWidth =
18577 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18578 if (!BitWidth) {
18579 InvalidDecl = true;
18580 BitWidth = nullptr;
18581 }
18582 }
18583
18584 // Check that 'mutable' is consistent with the type of the declaration.
18585 if (!InvalidDecl && Mutable) {
18586 unsigned DiagID = 0;
18587 if (T->isReferenceType())
18588 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18589 : diag::err_mutable_reference;
18590 else if (T.isConstQualified())
18591 DiagID = diag::err_mutable_const;
18592
18593 if (DiagID) {
18594 SourceLocation ErrLoc = Loc;
18595 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18596 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18597 Diag(ErrLoc, DiagID);
18598 if (DiagID != diag::ext_mutable_reference) {
18599 Mutable = false;
18600 InvalidDecl = true;
18601 }
18602 }
18603 }
18604
18605 // C++11 [class.union]p8 (DR1460):
18606 // At most one variant member of a union may have a
18607 // brace-or-equal-initializer.
18608 if (InitStyle != ICIS_NoInit)
18609 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18610
18611 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18612 BitWidth, Mutable, InitStyle);
18613 if (InvalidDecl)
18614 NewFD->setInvalidDecl();
18615
18616 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18617 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18618 Diag(Loc, diag::err_duplicate_member) << II;
18619 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18620 NewFD->setInvalidDecl();
18621 }
18622
18623 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18624 if (Record->isUnion()) {
18625 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18626 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18627 if (RDecl->getDefinition()) {
18628 // C++ [class.union]p1: An object of a class with a non-trivial
18629 // constructor, a non-trivial copy constructor, a non-trivial
18630 // destructor, or a non-trivial copy assignment operator
18631 // cannot be a member of a union, nor can an array of such
18632 // objects.
18633 if (CheckNontrivialField(NewFD))
18634 NewFD->setInvalidDecl();
18635 }
18636 }
18637
18638 // C++ [class.union]p1: If a union contains a member of reference type,
18639 // the program is ill-formed, except when compiling with MSVC extensions
18640 // enabled.
18641 if (EltTy->isReferenceType()) {
18642 const bool HaveMSExt =
18643 getLangOpts().MicrosoftExt &&
18645
18646 Diag(NewFD->getLocation(),
18647 HaveMSExt ? diag::ext_union_member_of_reference_type
18648 : diag::err_union_member_of_reference_type)
18649 << NewFD->getDeclName() << EltTy;
18650 if (!HaveMSExt)
18651 NewFD->setInvalidDecl();
18652 }
18653 }
18654 }
18655
18656 // FIXME: We need to pass in the attributes given an AST
18657 // representation, not a parser representation.
18658 if (D) {
18659 // FIXME: The current scope is almost... but not entirely... correct here.
18661
18662 if (NewFD->hasAttrs())
18664 }
18665
18666 // In auto-retain/release, infer strong retension for fields of
18667 // retainable type.
18668 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
18669 NewFD->setInvalidDecl();
18670
18671 if (T.isObjCGCWeak())
18672 Diag(Loc, diag::warn_attribute_weak_on_field);
18673
18674 // PPC MMA non-pointer types are not allowed as field types.
18675 if (Context.getTargetInfo().getTriple().isPPC64() &&
18676 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
18677 NewFD->setInvalidDecl();
18678
18679 NewFD->setAccess(AS);
18680 return NewFD;
18681}
18682
18684 assert(FD);
18685 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18686
18687 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18688 return false;
18689
18691 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18692 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18693 if (RDecl->getDefinition()) {
18694 // We check for copy constructors before constructors
18695 // because otherwise we'll never get complaints about
18696 // copy constructors.
18697
18699 // We're required to check for any non-trivial constructors. Since the
18700 // implicit default constructor is suppressed if there are any
18701 // user-declared constructors, we just need to check that there is a
18702 // trivial default constructor and a trivial copy constructor. (We don't
18703 // worry about move constructors here, since this is a C++98 check.)
18704 if (RDecl->hasNonTrivialCopyConstructor())
18706 else if (!RDecl->hasTrivialDefaultConstructor())
18708 else if (RDecl->hasNonTrivialCopyAssignment())
18710 else if (RDecl->hasNonTrivialDestructor())
18712
18713 if (member != CXXSpecialMemberKind::Invalid) {
18714 if (!getLangOpts().CPlusPlus11 &&
18715 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18716 // Objective-C++ ARC: it is an error to have a non-trivial field of
18717 // a union. However, system headers in Objective-C programs
18718 // occasionally have Objective-C lifetime objects within unions,
18719 // and rather than cause the program to fail, we make those
18720 // members unavailable.
18722 if (getSourceManager().isInSystemHeader(Loc)) {
18723 if (!FD->hasAttr<UnavailableAttr>())
18724 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18725 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18726 return false;
18727 }
18728 }
18729
18730 Diag(
18731 FD->getLocation(),
18733 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18734 : diag::err_illegal_union_or_anon_struct_member)
18735 << FD->getParent()->isUnion() << FD->getDeclName()
18736 << llvm::to_underlying(member);
18737 DiagnoseNontrivial(RDecl, member);
18738 return !getLangOpts().CPlusPlus11;
18739 }
18740 }
18741 }
18742
18743 return false;
18744}
18745
18747 SmallVectorImpl<Decl *> &AllIvarDecls) {
18748 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18749 return;
18750
18751 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18752 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18753
18754 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18755 return;
18756 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18757 if (!ID) {
18758 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18759 if (!CD->IsClassExtension())
18760 return;
18761 }
18762 // No need to add this to end of @implementation.
18763 else
18764 return;
18765 }
18766 // All conditions are met. Add a new bitfield to the tail end of ivars.
18767 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18768 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18769
18770 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18771 DeclLoc, DeclLoc, nullptr,
18774 DeclLoc),
18776 true);
18777 AllIvarDecls.push_back(Ivar);
18778}
18779
18780/// [class.dtor]p4:
18781/// At the end of the definition of a class, overload resolution is
18782/// performed among the prospective destructors declared in that class with
18783/// an empty argument list to select the destructor for the class, also
18784/// known as the selected destructor.
18785///
18786/// We do the overload resolution here, then mark the selected constructor in the AST.
18787/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18789 if (!Record->hasUserDeclaredDestructor()) {
18790 return;
18791 }
18792
18793 SourceLocation Loc = Record->getLocation();
18795
18796 for (auto *Decl : Record->decls()) {
18797 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18798 if (DD->isInvalidDecl())
18799 continue;
18800 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18801 OCS);
18802 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18803 }
18804 }
18805
18806 if (OCS.empty()) {
18807 return;
18808 }
18810 unsigned Msg = 0;
18811 OverloadCandidateDisplayKind DisplayKind;
18812
18813 switch (OCS.BestViableFunction(S, Loc, Best)) {
18814 case OR_Success:
18815 case OR_Deleted:
18816 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18817 break;
18818
18819 case OR_Ambiguous:
18820 Msg = diag::err_ambiguous_destructor;
18821 DisplayKind = OCD_AmbiguousCandidates;
18822 break;
18823
18825 Msg = diag::err_no_viable_destructor;
18826 DisplayKind = OCD_AllCandidates;
18827 break;
18828 }
18829
18830 if (Msg) {
18831 // OpenCL have got their own thing going with destructors. It's slightly broken,
18832 // but we allow it.
18833 if (!S.LangOpts.OpenCL) {
18834 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18835 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18836 Record->setInvalidDecl();
18837 }
18838 // It's a bit hacky: At this point we've raised an error but we want the
18839 // rest of the compiler to continue somehow working. However almost
18840 // everything we'll try to do with the class will depend on there being a
18841 // destructor. So let's pretend the first one is selected and hope for the
18842 // best.
18843 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18844 }
18845}
18846
18847/// [class.mem.special]p5
18848/// Two special member functions are of the same kind if:
18849/// - they are both default constructors,
18850/// - they are both copy or move constructors with the same first parameter
18851/// type, or
18852/// - they are both copy or move assignment operators with the same first
18853/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18855 CXXMethodDecl *M1,
18856 CXXMethodDecl *M2,
18858 // We don't want to compare templates to non-templates: See
18859 // https://github.com/llvm/llvm-project/issues/59206
18861 return bool(M1->getDescribedFunctionTemplate()) ==
18863 // FIXME: better resolve CWG
18864 // https://cplusplus.github.io/CWG/issues/2787.html
18865 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18866 M2->getNonObjectParameter(0)->getType()))
18867 return false;
18870 return false;
18871
18872 return true;
18873}
18874
18875/// [class.mem.special]p6:
18876/// An eligible special member function is a special member function for which:
18877/// - the function is not deleted,
18878/// - the associated constraints, if any, are satisfied, and
18879/// - no special member function of the same kind whose associated constraints
18880/// [CWG2595], if any, are satisfied is more constrained.
18884 SmallVector<bool, 4> SatisfactionStatus;
18885
18886 for (CXXMethodDecl *Method : Methods) {
18887 const Expr *Constraints = Method->getTrailingRequiresClause();
18888 if (!Constraints)
18889 SatisfactionStatus.push_back(true);
18890 else {
18891 ConstraintSatisfaction Satisfaction;
18892 if (S.CheckFunctionConstraints(Method, Satisfaction))
18893 SatisfactionStatus.push_back(false);
18894 else
18895 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18896 }
18897 }
18898
18899 for (size_t i = 0; i < Methods.size(); i++) {
18900 if (!SatisfactionStatus[i])
18901 continue;
18902 CXXMethodDecl *Method = Methods[i];
18903 CXXMethodDecl *OrigMethod = Method;
18904 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18905 OrigMethod = cast<CXXMethodDecl>(MF);
18906
18907 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18908 bool AnotherMethodIsMoreConstrained = false;
18909 for (size_t j = 0; j < Methods.size(); j++) {
18910 if (i == j || !SatisfactionStatus[j])
18911 continue;
18912 CXXMethodDecl *OtherMethod = Methods[j];
18913 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18914 OtherMethod = cast<CXXMethodDecl>(MF);
18915
18916 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18917 CSM))
18918 continue;
18919
18920 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18921 if (!OtherConstraints)
18922 continue;
18923 if (!Constraints) {
18924 AnotherMethodIsMoreConstrained = true;
18925 break;
18926 }
18927 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18928 {Constraints},
18929 AnotherMethodIsMoreConstrained)) {
18930 // There was an error with the constraints comparison. Exit the loop
18931 // and don't consider this function eligible.
18932 AnotherMethodIsMoreConstrained = true;
18933 }
18934 if (AnotherMethodIsMoreConstrained)
18935 break;
18936 }
18937 // FIXME: Do not consider deleted methods as eligible after implementing
18938 // DR1734 and DR1496.
18939 if (!AnotherMethodIsMoreConstrained) {
18940 Method->setIneligibleOrNotSelected(false);
18941 Record->addedEligibleSpecialMemberFunction(Method,
18942 1 << llvm::to_underlying(CSM));
18943 }
18944 }
18945}
18946
18949 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18950 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18951 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18952 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18953 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18954
18955 for (auto *Decl : Record->decls()) {
18956 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18957 if (!MD) {
18958 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18959 if (FTD)
18960 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18961 }
18962 if (!MD)
18963 continue;
18964 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18965 if (CD->isInvalidDecl())
18966 continue;
18967 if (CD->isDefaultConstructor())
18968 DefaultConstructors.push_back(MD);
18969 else if (CD->isCopyConstructor())
18970 CopyConstructors.push_back(MD);
18971 else if (CD->isMoveConstructor())
18972 MoveConstructors.push_back(MD);
18973 } else if (MD->isCopyAssignmentOperator()) {
18974 CopyAssignmentOperators.push_back(MD);
18975 } else if (MD->isMoveAssignmentOperator()) {
18976 MoveAssignmentOperators.push_back(MD);
18977 }
18978 }
18979
18980 SetEligibleMethods(S, Record, DefaultConstructors,
18982 SetEligibleMethods(S, Record, CopyConstructors,
18984 SetEligibleMethods(S, Record, MoveConstructors,
18986 SetEligibleMethods(S, Record, CopyAssignmentOperators,
18988 SetEligibleMethods(S, Record, MoveAssignmentOperators,
18990}
18991
18992void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18993 ArrayRef<Decl *> Fields, SourceLocation LBrac,
18994 SourceLocation RBrac,
18995 const ParsedAttributesView &Attrs) {
18996 assert(EnclosingDecl && "missing record or interface decl");
18997
18998 // If this is an Objective-C @implementation or category and we have
18999 // new fields here we should reset the layout of the interface since
19000 // it will now change.
19001 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19002 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19003 switch (DC->getKind()) {
19004 default: break;
19005 case Decl::ObjCCategory:
19006 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19007 break;
19008 case Decl::ObjCImplementation:
19009 Context.
19010 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19011 break;
19012 }
19013 }
19014
19015 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19016 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19017
19018 // Start counting up the number of named members; make sure to include
19019 // members of anonymous structs and unions in the total.
19020 unsigned NumNamedMembers = 0;
19021 if (Record) {
19022 for (const auto *I : Record->decls()) {
19023 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19024 if (IFD->getDeclName())
19025 ++NumNamedMembers;
19026 }
19027 }
19028
19029 // Verify that all the fields are okay.
19031
19032 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19033 i != end; ++i) {
19034 FieldDecl *FD = cast<FieldDecl>(*i);
19035
19036 // Get the type for the field.
19037 const Type *FDTy = FD->getType().getTypePtr();
19038
19039 if (!FD->isAnonymousStructOrUnion()) {
19040 // Remember all fields written by the user.
19041 RecFields.push_back(FD);
19042 }
19043
19044 // If the field is already invalid for some reason, don't emit more
19045 // diagnostics about it.
19046 if (FD->isInvalidDecl()) {
19047 EnclosingDecl->setInvalidDecl();
19048 continue;
19049 }
19050
19051 // C99 6.7.2.1p2:
19052 // A structure or union shall not contain a member with
19053 // incomplete or function type (hence, a structure shall not
19054 // contain an instance of itself, but may contain a pointer to
19055 // an instance of itself), except that the last member of a
19056 // structure with more than one named member may have incomplete
19057 // array type; such a structure (and any union containing,
19058 // possibly recursively, a member that is such a structure)
19059 // shall not be a member of a structure or an element of an
19060 // array.
19061 bool IsLastField = (i + 1 == Fields.end());
19062 if (FDTy->isFunctionType()) {
19063 // Field declared as a function.
19064 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19065 << FD->getDeclName();
19066 FD->setInvalidDecl();
19067 EnclosingDecl->setInvalidDecl();
19068 continue;
19069 } else if (FDTy->isIncompleteArrayType() &&
19070 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19071 if (Record) {
19072 // Flexible array member.
19073 // Microsoft and g++ is more permissive regarding flexible array.
19074 // It will accept flexible array in union and also
19075 // as the sole element of a struct/class.
19076 unsigned DiagID = 0;
19077 if (!Record->isUnion() && !IsLastField) {
19078 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19079 << FD->getDeclName() << FD->getType()
19080 << llvm::to_underlying(Record->getTagKind());
19081 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19082 FD->setInvalidDecl();
19083 EnclosingDecl->setInvalidDecl();
19084 continue;
19085 } else if (Record->isUnion())
19086 DiagID = getLangOpts().MicrosoftExt
19087 ? diag::ext_flexible_array_union_ms
19088 : diag::ext_flexible_array_union_gnu;
19089 else if (NumNamedMembers < 1)
19090 DiagID = getLangOpts().MicrosoftExt
19091 ? diag::ext_flexible_array_empty_aggregate_ms
19092 : diag::ext_flexible_array_empty_aggregate_gnu;
19093
19094 if (DiagID)
19095 Diag(FD->getLocation(), DiagID)
19096 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19097 // While the layout of types that contain virtual bases is not specified
19098 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19099 // virtual bases after the derived members. This would make a flexible
19100 // array member declared at the end of an object not adjacent to the end
19101 // of the type.
19102 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19103 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19104 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19105 if (!getLangOpts().C99)
19106 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19107 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
19108
19109 // If the element type has a non-trivial destructor, we would not
19110 // implicitly destroy the elements, so disallow it for now.
19111 //
19112 // FIXME: GCC allows this. We should probably either implicitly delete
19113 // the destructor of the containing class, or just allow this.
19114 QualType BaseElem = Context.getBaseElementType(FD->getType());
19115 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19116 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19117 << FD->getDeclName() << FD->getType();
19118 FD->setInvalidDecl();
19119 EnclosingDecl->setInvalidDecl();
19120 continue;
19121 }
19122 // Okay, we have a legal flexible array member at the end of the struct.
19123 Record->setHasFlexibleArrayMember(true);
19124 } else {
19125 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19126 // unless they are followed by another ivar. That check is done
19127 // elsewhere, after synthesized ivars are known.
19128 }
19129 } else if (!FDTy->isDependentType() &&
19130 (LangOpts.HLSL // HLSL allows sizeless builtin types
19132 diag::err_incomplete_type)
19134 FD->getLocation(), FD->getType(),
19135 diag::err_field_incomplete_or_sizeless))) {
19136 // Incomplete type
19137 FD->setInvalidDecl();
19138 EnclosingDecl->setInvalidDecl();
19139 continue;
19140 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
19141 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
19142 // A type which contains a flexible array member is considered to be a
19143 // flexible array member.
19144 Record->setHasFlexibleArrayMember(true);
19145 if (!Record->isUnion()) {
19146 // If this is a struct/class and this is not the last element, reject
19147 // it. Note that GCC supports variable sized arrays in the middle of
19148 // structures.
19149 if (!IsLastField)
19150 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19151 << FD->getDeclName() << FD->getType();
19152 else {
19153 // We support flexible arrays at the end of structs in
19154 // other structs as an extension.
19155 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19156 << FD->getDeclName();
19157 }
19158 }
19159 }
19160 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19162 diag::err_abstract_type_in_decl,
19164 // Ivars can not have abstract class types
19165 FD->setInvalidDecl();
19166 }
19167 if (Record && FDTTy->getDecl()->hasObjectMember())
19168 Record->setHasObjectMember(true);
19169 if (Record && FDTTy->getDecl()->hasVolatileMember())
19170 Record->setHasVolatileMember(true);
19171 } else if (FDTy->isObjCObjectType()) {
19172 /// A field cannot be an Objective-c object
19173 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19176 FD->setType(T);
19177 } else if (Record && Record->isUnion() &&
19179 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19180 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19183 // For backward compatibility, fields of C unions declared in system
19184 // headers that have non-trivial ObjC ownership qualifications are marked
19185 // as unavailable unless the qualifier is explicit and __strong. This can
19186 // break ABI compatibility between programs compiled with ARC and MRR, but
19187 // is a better option than rejecting programs using those unions under
19188 // ARC.
19189 FD->addAttr(UnavailableAttr::CreateImplicit(
19190 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19191 FD->getLocation()));
19192 } else if (getLangOpts().ObjC &&
19193 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19194 !Record->hasObjectMember()) {
19195 if (FD->getType()->isObjCObjectPointerType() ||
19196 FD->getType().isObjCGCStrong())
19197 Record->setHasObjectMember(true);
19198 else if (Context.getAsArrayType(FD->getType())) {
19199 QualType BaseType = Context.getBaseElementType(FD->getType());
19200 if (BaseType->isRecordType() &&
19201 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19202 Record->setHasObjectMember(true);
19203 else if (BaseType->isObjCObjectPointerType() ||
19204 BaseType.isObjCGCStrong())
19205 Record->setHasObjectMember(true);
19206 }
19207 }
19208
19209 if (Record && !getLangOpts().CPlusPlus &&
19210 !shouldIgnoreForRecordTriviality(FD)) {
19211 QualType FT = FD->getType();
19213 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19215 Record->isUnion())
19216 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19217 }
19220 Record->setNonTrivialToPrimitiveCopy(true);
19221 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19222 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19223 }
19224 if (FT.isDestructedType()) {
19225 Record->setNonTrivialToPrimitiveDestroy(true);
19226 Record->setParamDestroyedInCallee(true);
19227 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19228 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19229 }
19230
19231 if (const auto *RT = FT->getAs<RecordType>()) {
19232 if (RT->getDecl()->getArgPassingRestrictions() ==
19234 Record->setArgPassingRestrictions(
19237 Record->setArgPassingRestrictions(
19239 }
19240
19241 if (Record && FD->getType().isVolatileQualified())
19242 Record->setHasVolatileMember(true);
19243 // Keep track of the number of named members.
19244 if (FD->getIdentifier())
19245 ++NumNamedMembers;
19246 }
19247
19248 // Okay, we successfully defined 'Record'.
19249 if (Record) {
19250 bool Completed = false;
19251 if (S) {
19252 Scope *Parent = S->getParent();
19253 if (Parent && Parent->isTypeAliasScope() &&
19254 Parent->isTemplateParamScope())
19255 Record->setInvalidDecl();
19256 }
19257
19258 if (CXXRecord) {
19259 if (!CXXRecord->isInvalidDecl()) {
19260 // Set access bits correctly on the directly-declared conversions.
19262 I = CXXRecord->conversion_begin(),
19263 E = CXXRecord->conversion_end(); I != E; ++I)
19264 I.setAccess((*I)->getAccess());
19265 }
19266
19267 // Add any implicitly-declared members to this class.
19269
19270 if (!CXXRecord->isDependentType()) {
19271 if (!CXXRecord->isInvalidDecl()) {
19272 // If we have virtual base classes, we may end up finding multiple
19273 // final overriders for a given virtual function. Check for this
19274 // problem now.
19275 if (CXXRecord->getNumVBases()) {
19276 CXXFinalOverriderMap FinalOverriders;
19277 CXXRecord->getFinalOverriders(FinalOverriders);
19278
19279 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19280 MEnd = FinalOverriders.end();
19281 M != MEnd; ++M) {
19282 for (OverridingMethods::iterator SO = M->second.begin(),
19283 SOEnd = M->second.end();
19284 SO != SOEnd; ++SO) {
19285 assert(SO->second.size() > 0 &&
19286 "Virtual function without overriding functions?");
19287 if (SO->second.size() == 1)
19288 continue;
19289
19290 // C++ [class.virtual]p2:
19291 // In a derived class, if a virtual member function of a base
19292 // class subobject has more than one final overrider the
19293 // program is ill-formed.
19294 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19295 << (const NamedDecl *)M->first << Record;
19296 Diag(M->first->getLocation(),
19297 diag::note_overridden_virtual_function);
19299 OM = SO->second.begin(),
19300 OMEnd = SO->second.end();
19301 OM != OMEnd; ++OM)
19302 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19303 << (const NamedDecl *)M->first << OM->Method->getParent();
19304
19305 Record->setInvalidDecl();
19306 }
19307 }
19308 CXXRecord->completeDefinition(&FinalOverriders);
19309 Completed = true;
19310 }
19311 }
19312 ComputeSelectedDestructor(*this, CXXRecord);
19314 }
19315 }
19316
19317 if (!Completed)
19318 Record->completeDefinition();
19319
19320 // Handle attributes before checking the layout.
19322
19323 // Check to see if a FieldDecl is a pointer to a function.
19324 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19325 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19326 if (!FD) {
19327 // Check whether this is a forward declaration that was inserted by
19328 // Clang. This happens when a non-forward declared / defined type is
19329 // used, e.g.:
19330 //
19331 // struct foo {
19332 // struct bar *(*f)();
19333 // struct bar *(*g)();
19334 // };
19335 //
19336 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19337 // incomplete definition.
19338 if (const auto *TD = dyn_cast<TagDecl>(D))
19339 return !TD->isCompleteDefinition();
19340 return false;
19341 }
19342 QualType FieldType = FD->getType().getDesugaredType(Context);
19343 if (isa<PointerType>(FieldType)) {
19344 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19345 return PointeeType.getDesugaredType(Context)->isFunctionType();
19346 }
19347 return false;
19348 };
19349
19350 // Maybe randomize the record's decls. We automatically randomize a record
19351 // of function pointers, unless it has the "no_randomize_layout" attribute.
19352 if (!getLangOpts().CPlusPlus &&
19353 (Record->hasAttr<RandomizeLayoutAttr>() ||
19354 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19355 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19356 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19357 !Record->isRandomized()) {
19358 SmallVector<Decl *, 32> NewDeclOrdering;
19360 NewDeclOrdering))
19361 Record->reorderDecls(NewDeclOrdering);
19362 }
19363
19364 // We may have deferred checking for a deleted destructor. Check now.
19365 if (CXXRecord) {
19366 auto *Dtor = CXXRecord->getDestructor();
19367 if (Dtor && Dtor->isImplicit() &&
19369 CXXRecord->setImplicitDestructorIsDeleted();
19370 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19371 }
19372 }
19373
19374 if (Record->hasAttrs()) {
19376
19377 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19378 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19379 IA->getRange(), IA->getBestCase(),
19380 IA->getInheritanceModel());
19381 }
19382
19383 // Check if the structure/union declaration is a type that can have zero
19384 // size in C. For C this is a language extension, for C++ it may cause
19385 // compatibility problems.
19386 bool CheckForZeroSize;
19387 if (!getLangOpts().CPlusPlus) {
19388 CheckForZeroSize = true;
19389 } else {
19390 // For C++ filter out types that cannot be referenced in C code.
19391 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19392 CheckForZeroSize =
19393 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19394 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19395 CXXRecord->isCLike();
19396 }
19397 if (CheckForZeroSize) {
19398 bool ZeroSize = true;
19399 bool IsEmpty = true;
19400 unsigned NonBitFields = 0;
19401 for (RecordDecl::field_iterator I = Record->field_begin(),
19402 E = Record->field_end();
19403 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19404 IsEmpty = false;
19405 if (I->isUnnamedBitField()) {
19406 if (!I->isZeroLengthBitField(Context))
19407 ZeroSize = false;
19408 } else {
19409 ++NonBitFields;
19410 QualType FieldType = I->getType();
19411 if (FieldType->isIncompleteType() ||
19412 !Context.getTypeSizeInChars(FieldType).isZero())
19413 ZeroSize = false;
19414 }
19415 }
19416
19417 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19418 // allowed in C++, but warn if its declaration is inside
19419 // extern "C" block.
19420 if (ZeroSize) {
19421 Diag(RecLoc, getLangOpts().CPlusPlus ?
19422 diag::warn_zero_size_struct_union_in_extern_c :
19423 diag::warn_zero_size_struct_union_compat)
19424 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19425 }
19426
19427 // Structs without named members are extension in C (C99 6.7.2.1p7),
19428 // but are accepted by GCC. In C2y, this became implementation-defined
19429 // (C2y 6.7.3.2p10).
19430 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
19431 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
19432 : diag::ext_no_named_members_in_struct_union)
19433 << Record->isUnion();
19434 }
19435 }
19436 } else {
19437 ObjCIvarDecl **ClsFields =
19438 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19439 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19440 ID->setEndOfDefinitionLoc(RBrac);
19441 // Add ivar's to class's DeclContext.
19442 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19443 ClsFields[i]->setLexicalDeclContext(ID);
19444 ID->addDecl(ClsFields[i]);
19445 }
19446 // Must enforce the rule that ivars in the base classes may not be
19447 // duplicates.
19448 if (ID->getSuperClass())
19449 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19450 } else if (ObjCImplementationDecl *IMPDecl =
19451 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19452 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19453 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19454 // Ivar declared in @implementation never belongs to the implementation.
19455 // Only it is in implementation's lexical context.
19456 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19457 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
19458 RBrac);
19459 IMPDecl->setIvarLBraceLoc(LBrac);
19460 IMPDecl->setIvarRBraceLoc(RBrac);
19461 } else if (ObjCCategoryDecl *CDecl =
19462 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19463 // case of ivars in class extension; all other cases have been
19464 // reported as errors elsewhere.
19465 // FIXME. Class extension does not have a LocEnd field.
19466 // CDecl->setLocEnd(RBrac);
19467 // Add ivar's to class extension's DeclContext.
19468 // Diagnose redeclaration of private ivars.
19469 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19470 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19471 if (IDecl) {
19472 if (const ObjCIvarDecl *ClsIvar =
19473 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19474 Diag(ClsFields[i]->getLocation(),
19475 diag::err_duplicate_ivar_declaration);
19476 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19477 continue;
19478 }
19479 for (const auto *Ext : IDecl->known_extensions()) {
19480 if (const ObjCIvarDecl *ClsExtIvar
19481 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19482 Diag(ClsFields[i]->getLocation(),
19483 diag::err_duplicate_ivar_declaration);
19484 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19485 continue;
19486 }
19487 }
19488 }
19489 ClsFields[i]->setLexicalDeclContext(CDecl);
19490 CDecl->addDecl(ClsFields[i]);
19491 }
19492 CDecl->setIvarLBraceLoc(LBrac);
19493 CDecl->setIvarRBraceLoc(RBrac);
19494 }
19495 }
19497}
19498
19499/// Determine whether the given integral value is representable within
19500/// the given type T.
19502 llvm::APSInt &Value,
19503 QualType T) {
19504 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19505 "Integral type required!");
19506 unsigned BitWidth = Context.getIntWidth(T);
19507
19508 if (Value.isUnsigned() || Value.isNonNegative()) {
19510 --BitWidth;
19511 return Value.getActiveBits() <= BitWidth;
19512 }
19513 return Value.getSignificantBits() <= BitWidth;
19514}
19515
19516// Given an integral type, return the next larger integral type
19517// (or a NULL type of no such type exists).
19519 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19520 // enum checking below.
19521 assert((T->isIntegralType(Context) ||
19522 T->isEnumeralType()) && "Integral type required!");
19523 const unsigned NumTypes = 4;
19524 QualType SignedIntegralTypes[NumTypes] = {
19525 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19526 };
19527 QualType UnsignedIntegralTypes[NumTypes] = {
19528 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19529 Context.UnsignedLongLongTy
19530 };
19531
19532 unsigned BitWidth = Context.getTypeSize(T);
19533 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19534 : UnsignedIntegralTypes;
19535 for (unsigned I = 0; I != NumTypes; ++I)
19536 if (Context.getTypeSize(Types[I]) > BitWidth)
19537 return Types[I];
19538
19539 return QualType();
19540}
19541
19543 EnumConstantDecl *LastEnumConst,
19544 SourceLocation IdLoc,
19546 Expr *Val) {
19547 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19548 llvm::APSInt EnumVal(IntWidth);
19549 QualType EltTy;
19550
19552 Val = nullptr;
19553
19554 if (Val)
19555 Val = DefaultLvalueConversion(Val).get();
19556
19557 if (Val) {
19558 if (Enum->isDependentType() || Val->isTypeDependent() ||
19559 Val->containsErrors())
19560 EltTy = Context.DependentTy;
19561 else {
19562 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19563 // underlying type, but do allow it in all other contexts.
19564 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19565 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19566 // constant-expression in the enumerator-definition shall be a converted
19567 // constant expression of the underlying type.
19568 EltTy = Enum->getIntegerType();
19569 ExprResult Converted =
19570 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19572 if (Converted.isInvalid())
19573 Val = nullptr;
19574 else
19575 Val = Converted.get();
19576 } else if (!Val->isValueDependent() &&
19577 !(Val =
19579 .get())) {
19580 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19581 } else {
19582 if (Enum->isComplete()) {
19583 EltTy = Enum->getIntegerType();
19584
19585 // In Obj-C and Microsoft mode, require the enumeration value to be
19586 // representable in the underlying type of the enumeration. In C++11,
19587 // we perform a non-narrowing conversion as part of converted constant
19588 // expression checking.
19589 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19591 .getTriple()
19592 .isWindowsMSVCEnvironment()) {
19593 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19594 } else {
19595 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19596 }
19597 }
19598
19599 // Cast to the underlying type.
19600 Val = ImpCastExprToType(Val, EltTy,
19601 EltTy->isBooleanType() ? CK_IntegralToBoolean
19602 : CK_IntegralCast)
19603 .get();
19604 } else if (getLangOpts().CPlusPlus) {
19605 // C++11 [dcl.enum]p5:
19606 // If the underlying type is not fixed, the type of each enumerator
19607 // is the type of its initializing value:
19608 // - If an initializer is specified for an enumerator, the
19609 // initializing value has the same type as the expression.
19610 EltTy = Val->getType();
19611 } else {
19612 // C99 6.7.2.2p2:
19613 // The expression that defines the value of an enumeration constant
19614 // shall be an integer constant expression that has a value
19615 // representable as an int.
19616
19617 // Complain if the value is not representable in an int.
19619 Diag(IdLoc, getLangOpts().C23
19620 ? diag::warn_c17_compat_enum_value_not_int
19621 : diag::ext_c23_enum_value_not_int)
19622 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
19623 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19624 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19625 // Force the type of the expression to 'int'.
19626 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19627 }
19628 EltTy = Val->getType();
19629 }
19630 }
19631 }
19632 }
19633
19634 if (!Val) {
19635 if (Enum->isDependentType())
19636 EltTy = Context.DependentTy;
19637 else if (!LastEnumConst) {
19638 // C++0x [dcl.enum]p5:
19639 // If the underlying type is not fixed, the type of each enumerator
19640 // is the type of its initializing value:
19641 // - If no initializer is specified for the first enumerator, the
19642 // initializing value has an unspecified integral type.
19643 //
19644 // GCC uses 'int' for its unspecified integral type, as does
19645 // C99 6.7.2.2p3.
19646 if (Enum->isFixed()) {
19647 EltTy = Enum->getIntegerType();
19648 }
19649 else {
19650 EltTy = Context.IntTy;
19651 }
19652 } else {
19653 // Assign the last value + 1.
19654 EnumVal = LastEnumConst->getInitVal();
19655 ++EnumVal;
19656 EltTy = LastEnumConst->getType();
19657
19658 // Check for overflow on increment.
19659 if (EnumVal < LastEnumConst->getInitVal()) {
19660 // C++0x [dcl.enum]p5:
19661 // If the underlying type is not fixed, the type of each enumerator
19662 // is the type of its initializing value:
19663 //
19664 // - Otherwise the type of the initializing value is the same as
19665 // the type of the initializing value of the preceding enumerator
19666 // unless the incremented value is not representable in that type,
19667 // in which case the type is an unspecified integral type
19668 // sufficient to contain the incremented value. If no such type
19669 // exists, the program is ill-formed.
19671 if (T.isNull() || Enum->isFixed()) {
19672 // There is no integral type larger enough to represent this
19673 // value. Complain, then allow the value to wrap around.
19674 EnumVal = LastEnumConst->getInitVal();
19675 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19676 ++EnumVal;
19677 if (Enum->isFixed())
19678 // When the underlying type is fixed, this is ill-formed.
19679 Diag(IdLoc, diag::err_enumerator_wrapped)
19680 << toString(EnumVal, 10)
19681 << EltTy;
19682 else
19683 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19684 << toString(EnumVal, 10);
19685 } else {
19686 EltTy = T;
19687 }
19688
19689 // Retrieve the last enumerator's value, extent that type to the
19690 // type that is supposed to be large enough to represent the incremented
19691 // value, then increment.
19692 EnumVal = LastEnumConst->getInitVal();
19693 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19694 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19695 ++EnumVal;
19696
19697 // If we're not in C++, diagnose the overflow of enumerator values,
19698 // which in C99 means that the enumerator value is not representable in
19699 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
19700 // are representable in some larger integral type and we allow it in
19701 // older language modes as an extension.
19702 // Exclude fixed enumerators since they are diagnosed with an error for
19703 // this case.
19704 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
19705 Diag(IdLoc, getLangOpts().C23
19706 ? diag::warn_c17_compat_enum_value_not_int
19707 : diag::ext_c23_enum_value_not_int)
19708 << 1 << toString(EnumVal, 10) << 1;
19709 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
19710 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19711 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19712 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
19713 : diag::ext_c23_enum_value_not_int)
19714 << 1 << toString(EnumVal, 10) << 1;
19715 }
19716 }
19717 }
19718
19719 if (!EltTy->isDependentType()) {
19720 // Make the enumerator value match the signedness and size of the
19721 // enumerator's type.
19722 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19723 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19724 }
19725
19726 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19727 Val, EnumVal);
19728}
19729
19731 SourceLocation IILoc) {
19732 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19734 return SkipBodyInfo();
19735
19736 // We have an anonymous enum definition. Look up the first enumerator to
19737 // determine if we should merge the definition with an existing one and
19738 // skip the body.
19739 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19741 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19742 if (!PrevECD)
19743 return SkipBodyInfo();
19744
19745 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19746 NamedDecl *Hidden;
19747 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19749 Skip.Previous = Hidden;
19750 return Skip;
19751 }
19752
19753 return SkipBodyInfo();
19754}
19755
19756Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19758 const ParsedAttributesView &Attrs,
19759 SourceLocation EqualLoc, Expr *Val) {
19760 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19761 EnumConstantDecl *LastEnumConst =
19762 cast_or_null<EnumConstantDecl>(lastEnumConst);
19763
19764 // The scope passed in may not be a decl scope. Zip up the scope tree until
19765 // we find one that is.
19766 S = getNonFieldDeclScope(S);
19767
19768 // Verify that there isn't already something declared with this name in this
19769 // scope.
19770 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
19771 RedeclarationKind::ForVisibleRedeclaration);
19772 LookupName(R, S);
19773 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19774
19775 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19776 // Maybe we will complain about the shadowed template parameter.
19777 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19778 // Just pretend that we didn't see the previous declaration.
19779 PrevDecl = nullptr;
19780 }
19781
19782 // C++ [class.mem]p15:
19783 // If T is the name of a class, then each of the following shall have a name
19784 // different from T:
19785 // - every enumerator of every member of class T that is an unscoped
19786 // enumerated type
19787 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19789 DeclarationNameInfo(Id, IdLoc));
19790
19791 EnumConstantDecl *New =
19792 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19793 if (!New)
19794 return nullptr;
19795
19796 if (PrevDecl) {
19797 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19798 // Check for other kinds of shadowing not already handled.
19799 CheckShadow(New, PrevDecl, R);
19800 }
19801
19802 // When in C++, we may get a TagDecl with the same name; in this case the
19803 // enum constant will 'hide' the tag.
19804 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19805 "Received TagDecl when not in C++!");
19806 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19807 if (isa<EnumConstantDecl>(PrevDecl))
19808 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19809 else
19810 Diag(IdLoc, diag::err_redefinition) << Id;
19811 notePreviousDefinition(PrevDecl, IdLoc);
19812 return nullptr;
19813 }
19814 }
19815
19816 // Process attributes.
19817 ProcessDeclAttributeList(S, New, Attrs);
19818 AddPragmaAttributes(S, New);
19819 ProcessAPINotes(New);
19820
19821 // Register this decl in the current scope stack.
19822 New->setAccess(TheEnumDecl->getAccess());
19823 PushOnScopeChains(New, S);
19824
19826
19827 return New;
19828}
19829
19830// Returns true when the enum initial expression does not trigger the
19831// duplicate enum warning. A few common cases are exempted as follows:
19832// Element2 = Element1
19833// Element2 = Element1 + 1
19834// Element2 = Element1 - 1
19835// Where Element2 and Element1 are from the same enum.
19837 Expr *InitExpr = ECD->getInitExpr();
19838 if (!InitExpr)
19839 return true;
19840 InitExpr = InitExpr->IgnoreImpCasts();
19841
19842 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19843 if (!BO->isAdditiveOp())
19844 return true;
19845 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19846 if (!IL)
19847 return true;
19848 if (IL->getValue() != 1)
19849 return true;
19850
19851 InitExpr = BO->getLHS();
19852 }
19853
19854 // This checks if the elements are from the same enum.
19855 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19856 if (!DRE)
19857 return true;
19858
19859 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19860 if (!EnumConstant)
19861 return true;
19862
19863 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19864 Enum)
19865 return true;
19866
19867 return false;
19868}
19869
19870// Emits a warning when an element is implicitly set a value that
19871// a previous element has already been set to.
19874 // Avoid anonymous enums
19875 if (!Enum->getIdentifier())
19876 return;
19877
19878 // Only check for small enums.
19879 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19880 return;
19881
19882 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19883 return;
19884
19885 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19886 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19887
19888 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19889
19890 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19891 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19892
19893 // Use int64_t as a key to avoid needing special handling for map keys.
19894 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19895 llvm::APSInt Val = D->getInitVal();
19896 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19897 };
19898
19899 DuplicatesVector DupVector;
19900 ValueToVectorMap EnumMap;
19901
19902 // Populate the EnumMap with all values represented by enum constants without
19903 // an initializer.
19904 for (auto *Element : Elements) {
19905 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19906
19907 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19908 // this constant. Skip this enum since it may be ill-formed.
19909 if (!ECD) {
19910 return;
19911 }
19912
19913 // Constants with initializers are handled in the next loop.
19914 if (ECD->getInitExpr())
19915 continue;
19916
19917 // Duplicate values are handled in the next loop.
19918 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19919 }
19920
19921 if (EnumMap.size() == 0)
19922 return;
19923
19924 // Create vectors for any values that has duplicates.
19925 for (auto *Element : Elements) {
19926 // The last loop returned if any constant was null.
19927 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19928 if (!ValidDuplicateEnum(ECD, Enum))
19929 continue;
19930
19931 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19932 if (Iter == EnumMap.end())
19933 continue;
19934
19935 DeclOrVector& Entry = Iter->second;
19936 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19937 // Ensure constants are different.
19938 if (D == ECD)
19939 continue;
19940
19941 // Create new vector and push values onto it.
19942 auto Vec = std::make_unique<ECDVector>();
19943 Vec->push_back(D);
19944 Vec->push_back(ECD);
19945
19946 // Update entry to point to the duplicates vector.
19947 Entry = Vec.get();
19948
19949 // Store the vector somewhere we can consult later for quick emission of
19950 // diagnostics.
19951 DupVector.emplace_back(std::move(Vec));
19952 continue;
19953 }
19954
19955 ECDVector *Vec = cast<ECDVector *>(Entry);
19956 // Make sure constants are not added more than once.
19957 if (*Vec->begin() == ECD)
19958 continue;
19959
19960 Vec->push_back(ECD);
19961 }
19962
19963 // Emit diagnostics.
19964 for (const auto &Vec : DupVector) {
19965 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19966
19967 // Emit warning for one enum constant.
19968 auto *FirstECD = Vec->front();
19969 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19970 << FirstECD << toString(FirstECD->getInitVal(), 10)
19971 << FirstECD->getSourceRange();
19972
19973 // Emit one note for each of the remaining enum constants with
19974 // the same value.
19975 for (auto *ECD : llvm::drop_begin(*Vec))
19976 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19977 << ECD << toString(ECD->getInitVal(), 10)
19978 << ECD->getSourceRange();
19979 }
19980}
19981
19982bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19983 bool AllowMask) const {
19984 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19985 assert(ED->isCompleteDefinition() && "expected enum definition");
19986
19987 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19988 llvm::APInt &FlagBits = R.first->second;
19989
19990 if (R.second) {
19991 for (auto *E : ED->enumerators()) {
19992 const auto &EVal = E->getInitVal();
19993 // Only single-bit enumerators introduce new flag values.
19994 if (EVal.isPowerOf2())
19995 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19996 }
19997 }
19998
19999 // A value is in a flag enum if either its bits are a subset of the enum's
20000 // flag bits (the first condition) or we are allowing masks and the same is
20001 // true of its complement (the second condition). When masks are allowed, we
20002 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20003 //
20004 // While it's true that any value could be used as a mask, the assumption is
20005 // that a mask will have all of the insignificant bits set. Anything else is
20006 // likely a logic error.
20007 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20008 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20009}
20010
20012 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20013 const ParsedAttributesView &Attrs) {
20014 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20016
20017 ProcessDeclAttributeList(S, Enum, Attrs);
20019
20020 if (Enum->isDependentType()) {
20021 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20022 EnumConstantDecl *ECD =
20023 cast_or_null<EnumConstantDecl>(Elements[i]);
20024 if (!ECD) continue;
20025
20026 ECD->setType(EnumType);
20027 }
20028
20029 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20030 return;
20031 }
20032
20033 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20034 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
20035 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
20036
20037 // Verify that all the values are okay, compute the size of the values, and
20038 // reverse the list.
20039 unsigned NumNegativeBits = 0;
20040 unsigned NumPositiveBits = 0;
20041 bool MembersRepresentableByInt = true;
20042
20043 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20044 EnumConstantDecl *ECD =
20045 cast_or_null<EnumConstantDecl>(Elements[i]);
20046 if (!ECD) continue; // Already issued a diagnostic.
20047
20048 llvm::APSInt InitVal = ECD->getInitVal();
20049
20050 // Keep track of the size of positive and negative values.
20051 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
20052 // If the enumerator is zero that should still be counted as a positive
20053 // bit since we need a bit to store the value zero.
20054 unsigned ActiveBits = InitVal.getActiveBits();
20055 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
20056 } else {
20057 NumNegativeBits =
20058 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
20059 }
20060 MembersRepresentableByInt &=
20062 }
20063
20064 // If we have an empty set of enumerators we still need one bit.
20065 // From [dcl.enum]p8
20066 // If the enumerator-list is empty, the values of the enumeration are as if
20067 // the enumeration had a single enumerator with value 0
20068 if (!NumPositiveBits && !NumNegativeBits)
20069 NumPositiveBits = 1;
20070
20071 // Figure out the type that should be used for this enum.
20072 QualType BestType;
20073 unsigned BestWidth;
20074
20075 // C++0x N3000 [conv.prom]p3:
20076 // An rvalue of an unscoped enumeration type whose underlying
20077 // type is not fixed can be converted to an rvalue of the first
20078 // of the following types that can represent all the values of
20079 // the enumeration: int, unsigned int, long int, unsigned long
20080 // int, long long int, or unsigned long long int.
20081 // C99 6.4.4.3p2:
20082 // An identifier declared as an enumeration constant has type int.
20083 // The C99 rule is modified by C23.
20084 QualType BestPromotionType;
20085
20086 bool Packed = Enum->hasAttr<PackedAttr>();
20087 // -fshort-enums is the equivalent to specifying the packed attribute on all
20088 // enum definitions.
20089 if (LangOpts.ShortEnums)
20090 Packed = true;
20091
20092 // If the enum already has a type because it is fixed or dictated by the
20093 // target, promote that type instead of analyzing the enumerators.
20094 if (Enum->isComplete()) {
20095 BestType = Enum->getIntegerType();
20096 if (Context.isPromotableIntegerType(BestType))
20097 BestPromotionType = Context.getPromotedIntegerType(BestType);
20098 else
20099 BestPromotionType = BestType;
20100
20101 BestWidth = Context.getIntWidth(BestType);
20102 }
20103 else if (NumNegativeBits) {
20104 // If there is a negative value, figure out the smallest integer type (of
20105 // int/long/longlong) that fits.
20106 // If it's packed, check also if it fits a char or a short.
20107 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
20108 BestType = Context.SignedCharTy;
20109 BestWidth = CharWidth;
20110 } else if (Packed && NumNegativeBits <= ShortWidth &&
20111 NumPositiveBits < ShortWidth) {
20112 BestType = Context.ShortTy;
20113 BestWidth = ShortWidth;
20114 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
20115 BestType = Context.IntTy;
20116 BestWidth = IntWidth;
20117 } else {
20118 BestWidth = Context.getTargetInfo().getLongWidth();
20119
20120 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
20121 BestType = Context.LongTy;
20122 } else {
20123 BestWidth = Context.getTargetInfo().getLongLongWidth();
20124
20125 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
20126 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20127 BestType = Context.LongLongTy;
20128 }
20129 }
20130 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
20131 } else {
20132 // If there is no negative value, figure out the smallest type that fits
20133 // all of the enumerator values.
20134 // If it's packed, check also if it fits a char or a short.
20135 if (Packed && NumPositiveBits <= CharWidth) {
20136 BestType = Context.UnsignedCharTy;
20137 BestPromotionType = Context.IntTy;
20138 BestWidth = CharWidth;
20139 } else if (Packed && NumPositiveBits <= ShortWidth) {
20140 BestType = Context.UnsignedShortTy;
20141 BestPromotionType = Context.IntTy;
20142 BestWidth = ShortWidth;
20143 } else if (NumPositiveBits <= IntWidth) {
20144 BestType = Context.UnsignedIntTy;
20145 BestWidth = IntWidth;
20146 BestPromotionType
20147 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20149 } else if (NumPositiveBits <=
20150 (BestWidth = Context.getTargetInfo().getLongWidth())) {
20151 BestType = Context.UnsignedLongTy;
20152 BestPromotionType
20153 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20155 } else {
20156 BestWidth = Context.getTargetInfo().getLongLongWidth();
20157 if (NumPositiveBits > BestWidth) {
20158 // This can happen with bit-precise integer types, but those are not
20159 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
20160 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
20161 // a 128-bit integer, we should consider doing the same.
20162 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20163 }
20164 BestType = Context.UnsignedLongLongTy;
20165 BestPromotionType
20166 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
20168 }
20169 }
20170
20171 // Loop over all of the enumerator constants, changing their types to match
20172 // the type of the enum if needed.
20173 for (auto *D : Elements) {
20174 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20175 if (!ECD) continue; // Already issued a diagnostic.
20176
20177 // C99 says the enumerators have int type, but we allow, as an
20178 // extension, the enumerators to be larger than int size. If each
20179 // enumerator value fits in an int, type it as an int, otherwise type it the
20180 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20181 // that X has type 'int', not 'unsigned'.
20182
20183 // Determine whether the value fits into an int.
20184 llvm::APSInt InitVal = ECD->getInitVal();
20185
20186 // If it fits into an integer type, force it. Otherwise force it to match
20187 // the enum decl type.
20188 QualType NewTy;
20189 unsigned NewWidth;
20190 bool NewSign;
20191 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20192 MembersRepresentableByInt) {
20193 // C23 6.7.3.3.3p15:
20194 // The enumeration member type for an enumerated type without fixed
20195 // underlying type upon completion is:
20196 // - int if all the values of the enumeration are representable as an
20197 // int; or,
20198 // - the enumerated type
20199 NewTy = Context.IntTy;
20200 NewWidth = IntWidth;
20201 NewSign = true;
20202 } else if (ECD->getType() == BestType) {
20203 // Already the right type!
20204 if (getLangOpts().CPlusPlus)
20205 // C++ [dcl.enum]p4: Following the closing brace of an
20206 // enum-specifier, each enumerator has the type of its
20207 // enumeration.
20208 ECD->setType(EnumType);
20209 continue;
20210 } else {
20211 NewTy = BestType;
20212 NewWidth = BestWidth;
20213 NewSign = BestType->isSignedIntegerOrEnumerationType();
20214 }
20215
20216 // Adjust the APSInt value.
20217 InitVal = InitVal.extOrTrunc(NewWidth);
20218 InitVal.setIsSigned(NewSign);
20219 ECD->setInitVal(Context, InitVal);
20220
20221 // Adjust the Expr initializer and type.
20222 if (ECD->getInitExpr() &&
20223 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20224 ECD->setInitExpr(ImplicitCastExpr::Create(
20225 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20226 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20227 if (getLangOpts().CPlusPlus)
20228 // C++ [dcl.enum]p4: Following the closing brace of an
20229 // enum-specifier, each enumerator has the type of its
20230 // enumeration.
20231 ECD->setType(EnumType);
20232 else
20233 ECD->setType(NewTy);
20234 }
20235
20236 Enum->completeDefinition(BestType, BestPromotionType,
20237 NumPositiveBits, NumNegativeBits);
20238
20239 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20240
20241 if (Enum->isClosedFlag()) {
20242 for (Decl *D : Elements) {
20243 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20244 if (!ECD) continue; // Already issued a diagnostic.
20245
20246 llvm::APSInt InitVal = ECD->getInitVal();
20247 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20248 !IsValueInFlagEnum(Enum, InitVal, true))
20249 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20250 << ECD << Enum;
20251 }
20252 }
20253
20254 // Now that the enum type is defined, ensure it's not been underaligned.
20255 if (Enum->hasAttrs())
20257}
20258
20260 SourceLocation StartLoc,
20261 SourceLocation EndLoc) {
20262 StringLiteral *AsmString = cast<StringLiteral>(expr);
20263
20265 AsmString, StartLoc,
20266 EndLoc);
20267 CurContext->addDecl(New);
20268 return New;
20269}
20270
20272 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20273 CurContext->addDecl(New);
20274 PushDeclContext(S, New);
20276 PushCompoundScope(false);
20277 return New;
20278}
20279
20281 D->setStmt(Statement);
20285}
20286
20288 IdentifierInfo* AliasName,
20289 SourceLocation PragmaLoc,
20290 SourceLocation NameLoc,
20291 SourceLocation AliasNameLoc) {
20292 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20294 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20296 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20297 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20298
20299 // If a declaration that:
20300 // 1) declares a function or a variable
20301 // 2) has external linkage
20302 // already exists, add a label attribute to it.
20303 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20304 if (isDeclExternC(PrevDecl))
20305 PrevDecl->addAttr(Attr);
20306 else
20307 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20308 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20309 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20310 } else
20311 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20312}
20313
20315 SourceLocation PragmaLoc,
20316 SourceLocation NameLoc) {
20317 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20318
20319 if (PrevDecl) {
20320 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20321 } else {
20322 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20323 }
20324}
20325
20327 IdentifierInfo* AliasName,
20328 SourceLocation PragmaLoc,
20329 SourceLocation NameLoc,
20330 SourceLocation AliasNameLoc) {
20331 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20333 WeakInfo W = WeakInfo(Name, NameLoc);
20334
20335 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20336 if (!PrevDecl->hasAttr<AliasAttr>())
20337 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20339 } else {
20340 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20341 }
20342}
20343
20345 bool Final) {
20346 assert(FD && "Expected non-null FunctionDecl");
20347
20348 // SYCL functions can be template, so we check if they have appropriate
20349 // attribute prior to checking if it is a template.
20350 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20352
20353 // Templates are emitted when they're instantiated.
20354 if (FD->isDependentContext())
20356
20357 // Check whether this function is an externally visible definition.
20358 auto IsEmittedForExternalSymbol = [this, FD]() {
20359 // We have to check the GVA linkage of the function's *definition* -- if we
20360 // only have a declaration, we don't know whether or not the function will
20361 // be emitted, because (say) the definition could include "inline".
20362 const FunctionDecl *Def = FD->getDefinition();
20363
20364 // We can't compute linkage when we skip function bodies.
20365 return Def && !Def->hasSkippedBody() &&
20367 getASTContext().GetGVALinkageForFunction(Def));
20368 };
20369
20370 if (LangOpts.OpenMPIsTargetDevice) {
20371 // In OpenMP device mode we will not emit host only functions, or functions
20372 // we don't need due to their linkage.
20373 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20374 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20375 // DevTy may be changed later by
20376 // #pragma omp declare target to(*) device_type(*).
20377 // Therefore DevTy having no value does not imply host. The emission status
20378 // will be checked again at the end of compilation unit with Final = true.
20379 if (DevTy)
20380 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20382 // If we have an explicit value for the device type, or we are in a target
20383 // declare context, we need to emit all extern and used symbols.
20384 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20385 if (IsEmittedForExternalSymbol())
20387 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20388 // we'll omit it.
20389 if (Final)
20391 } else if (LangOpts.OpenMP > 45) {
20392 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20393 // function. In 5.0, no_host was introduced which might cause a function to
20394 // be omitted.
20395 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20396 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20397 if (DevTy)
20398 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20400 }
20401
20402 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20404
20405 if (LangOpts.CUDA) {
20406 // When compiling for device, host functions are never emitted. Similarly,
20407 // when compiling for host, device and global functions are never emitted.
20408 // (Technically, we do emit a host-side stub for global functions, but this
20409 // doesn't count for our purposes here.)
20411 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20413 if (!LangOpts.CUDAIsDevice &&
20416
20417 if (IsEmittedForExternalSymbol())
20419 }
20420
20421 // Otherwise, the function is known-emitted if it's in our set of
20422 // known-emitted functions.
20424}
20425
20427 // Host-side references to a __global__ function refer to the stub, so the
20428 // function itself is never emitted and therefore should not be marked.
20429 // If we have host fn calls kernel fn calls host+device, the HD function
20430 // does not get instantiated on the host. We model this by omitting at the
20431 // call to the kernel from the callgraph. This ensures that, when compiling
20432 // for host, only HD functions actually called from the host get marked as
20433 // known-emitted.
20434 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20436}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
#define SM(sm)
Definition: Cuda.cpp:84
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
const Decl * D
IndirectLocalPath & Path
Expr * E
enum clang::sema::@1718::IndirectLocalPathEntry::EntryKind Kind
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition: Decl.cpp:2218
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Iter
Definition: HTMLLogger.cpp:153
static const Decl * getCanonicalDecl(const Decl *D)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition: MachO.h:27
llvm::MachO::Record Record
Definition: MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition: Mangle.cpp:57
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition: Redeclaration.h:18
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
uint32_t Id
Definition: SemaARM.cpp:1134
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:15905
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6822
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition: SemaDecl.cpp:151
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15402
static bool isMainVar(DeclarationName Name, VarDecl *VD)
Definition: SemaDecl.cpp:7422
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11390
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:206
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3314
static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6913
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
Definition: SemaDecl.cpp:3479
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:796
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6520
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
Definition: SemaDecl.cpp:1471
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:6558
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2270
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9209
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
Definition: SemaDecl.cpp:3426
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2784
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8190
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9555
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3232
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
Definition: SemaDecl.cpp:8566
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11792
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
Definition: SemaDecl.cpp:2673
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4439
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
Definition: SemaDecl.cpp:11886
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15386
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaDecl.cpp:11510
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2037
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
Definition: SemaDecl.cpp:15021
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:562
static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6948
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
Definition: SemaDecl.cpp:11399
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99's...
Definition: SemaDecl.cpp:7163
static bool isRepresentableIntegerValue(ASTContext &Context, llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
Definition: SemaDecl.cpp:19501
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:19872
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
Definition: SemaDecl.cpp:4986
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
Definition: SemaDecl.cpp:2916
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:16920
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3461
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:7000
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
Definition: SemaDecl.cpp:5922
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
Definition: SemaDecl.cpp:4853
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9245
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
Definition: SemaDecl.cpp:9738
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
Definition: SemaDecl.cpp:15934
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3368
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8535
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2642
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9427
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3031
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8215
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:17080
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion, StorageClass SC)
We are trying to inject an anonymous member into the given scope; check if there's an existing declar...
Definition: SemaDecl.cpp:5273
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
Definition: SemaDecl.cpp:8452
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
Definition: SemaDecl.cpp:1913
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9749
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, StorageClass SC, SmallVectorImpl< NamedDecl * > &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
Definition: SemaDecl.cpp:5349
OpenCLParamType
Definition: SemaDecl.cpp:9418
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9422
@ ValidKernelParam
Definition: SemaDecl.cpp:9419
@ InvalidKernelParam
Definition: SemaDecl.cpp:9423
@ RecordKernelParam
Definition: SemaDecl.cpp:9424
@ PtrKernelParam
Definition: SemaDecl.cpp:9421
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9420
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
Definition: SemaDecl.cpp:6031
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, CXXMethodDecl *M1, CXXMethodDecl *M2, CXXSpecialMemberKind CSM)
[class.mem.special]p5 Two special member functions are of the same kind if:
Definition: SemaDecl.cpp:18854
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:582
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record)
[class.dtor]p4: At the end of the definition of a class, overload resolution is performed among the p...
Definition: SemaDecl.cpp:18788
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7208
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5433
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11319
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
Definition: SemaDecl.cpp:9729
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3275
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3405
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:16904
static void checkInheritableAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6921
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2164
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4336
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
Definition: SemaDecl.cpp:9052
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:5957
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, ArrayRef< CXXMethodDecl * > Methods, CXXSpecialMemberKind CSM)
[class.mem.special]p6: An eligible special member function is a special member function for which:
Definition: SemaDecl.cpp:18881
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:811
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7235
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8179
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8186
@ SDK_Field
Definition: SemaDecl.cpp:8183
@ SDK_Global
Definition: SemaDecl.cpp:8181
@ SDK_Local
Definition: SemaDecl.cpp:8180
@ SDK_Typedef
Definition: SemaDecl.cpp:8184
@ SDK_StaticMember
Definition: SemaDecl.cpp:8182
@ SDK_Using
Definition: SemaDecl.cpp:8185
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4799
static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7394
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3389
static void checkWeakAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6869
static void checkSelectAnyAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6901
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9449
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5447
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12513
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7286
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
Definition: SemaDecl.cpp:1782
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:18947
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11132
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
Definition: SemaDecl.cpp:1771
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2890
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:6442
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:14829
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7382
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:5904
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1824
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:11073
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6783
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5412
static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, SourceLocation NameLoc, bool WantNontrivialTypeSourceInfo=true)
Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
Definition: SemaDecl.cpp:248
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
Definition: SemaDecl.cpp:11541
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const VarDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
Definition: SemaDecl.cpp:8206
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
Definition: SemaDecl.cpp:11365
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:7014
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11150
static void checkAliasAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6888
static void filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
Definition: SemaDecl.cpp:2397
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:19836
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19518
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6879
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7194
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2661
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:10980
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11414
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1798
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
Definition: SemaDecl.cpp:17117
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to Wasm.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Definition: SourceCode.cpp:152
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
const NestedNameSpecifier * Specifier
StateNode * Previous
std::string Label
__device__ int
#define bool
Definition: amdgpuintrin.h:20
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
Definition: SemaDecl.cpp:15892
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:15894
llvm::APInt getValue() const
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:73
virtual void HandleInlineFunctionDefinition(FunctionDecl *D)
This callback is invoked each time an inline (method or friend) function definition in a class is com...
Definition: ASTConsumer.h:58
virtual bool shouldSkipFunctionBody(Decl *D)
This callback is called for each function if the Parser was initialized with SkipFunctionBodies set t...
Definition: ASTConsumer.h:146
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:113
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
SourceManager & getSourceManager()
Definition: ASTContext.h:741
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2915
QualType getParenType(QualType NamedType) const
CanQualType LongTy
Definition: ASTContext.h:1169
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
ExternCContextDecl * getExternCContextDecl() const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2218
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getRecordType(const RecordDecl *Decl) const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
void setObjCIdRedefinitionType(QualType RedefType)
Set the user-written type that redefines id.
Definition: ASTContext.h:1998
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:2108
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
void setObjCSelRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:2024
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2086
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2921
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
CanQualType DependentTy
Definition: ASTContext.h:1188
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
IdentifierTable & Idents
Definition: ASTContext.h:680
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:530
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2206
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:2120
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:3014
CanQualType CharTy
Definition: ASTContext.h:1162
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
CanQualType IntTy
Definition: ASTContext.h:1169
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1169
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2196
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2763
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2482
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1533
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2918
CanQualType ShortTy
Definition: ASTContext.h:1169
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:2011
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2312
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:2096
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1169
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2384
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2390
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2387
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2396
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2393
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2513
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:153
bool isUnset() const
Definition: Ownership.h:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3357
Wrapper for source info for arrays.
Definition: TypeLoc.h:1592
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1594
Expr * getSizeExpr() const
Definition: TypeLoc.h:1614
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1622
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1602
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
Attr - This represents one attribute.
Definition: Attr.h:43
attr::Kind getKind() const
Definition: Attr.h:89
bool isInherited() const
Definition: Attr.h:98
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition: Attr.h:103
SourceLocation getLocation() const
Definition: Attr.h:96
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:637
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:733
Type source information for an attributed type.
Definition: TypeLoc.h:875
const T * getAttrAs()
Definition: TypeLoc.h:905
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:889
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6127
QualType getModifiedType() const
Definition: Type.h:6157
bool isCallingConv() const
Definition: Type.cpp:4206
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6556
AutoTypeKeyword getKeyword() const
Definition: Type.h:6587
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4324
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
A binding in a decomposition declaration.
Definition: DeclCXX.h:4125
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4474
bool doesNotEscape() const
Definition: Decl.h:4625
This class is used for builtin types like 'int'.
Definition: Type.h:3034
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
bool performsCallback(unsigned ID, llvm::SmallVectorImpl< int > &Encoding) const
Determine whether this builtin has callback behavior (see llvm::AbstractCallSites for details).
Definition: Builtins.cpp:215
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:260
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition: Builtins.h:220
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:135
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:282
bool isConstWithoutErrnoAndExceptions(unsigned ID) const
Return true if this function has no side effects and doesn't read memory, except for possibly errno o...
Definition: Builtins.h:245
bool allowTypeMismatch(unsigned ID) const
Determines whether a declaration of this builtin should be recognized even if the type doesn't match ...
Definition: Builtins.h:200
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:109
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:165
bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like scanf in its formatting rules and, if so, set the index to the...
Definition: Builtins.cpp:210
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:180
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:158
bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like printf in its formatting rules and, if so, set the index to th...
Definition: Builtins.cpp:205
bool isConstWithoutExceptions(unsigned ID) const
Definition: Builtins.h:249
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:172
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:114
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:125
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:120
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclCXX.h:195
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2815
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2880
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2982
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2250
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2949
A mapping from each virtual member function to its set of final overriders.
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2549
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2603
bool isVirtual() const
Definition: DeclCXX.h:2133
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2668
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2582
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2368
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2239
bool isConst() const
Definition: DeclCXX.h:2130
bool isStatic() const
Definition: DeclCXX.cpp:2280
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2560
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2174
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1346
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1252
base_class_iterator bases_end()
Definition: DeclCXX.h:629
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1378
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1563
base_class_range bases()
Definition: DeclCXX.h:620
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1388
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:131
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:2024
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition: DeclCXX.h:627
capture_const_range captures() const
Definition: DeclCXX.h:1109
bool hasDefinition() const
Definition: DeclCXX.h:572
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1991
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1071
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1995
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1300
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:236
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:123
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:149
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4262
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:205
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:245
bool isZeroSize() const
Return true if the size is zero.
Definition: Type.h:3685
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1368
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2218
bool isFileContext() const
Definition: DeclBase.h:2160
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2045
bool isObjCContainer() const
Definition: DeclBase.h:2128
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1400
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
bool isClosure() const
Definition: DeclBase.h:2122
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2105
bool isNamespace() const
Definition: DeclBase.h:2178
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1301
bool isTranslationUnit() const
Definition: DeclBase.h:2165
bool isRecord() const
Definition: DeclBase.h:2169
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1990
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1687
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1768
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1637
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2008
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1424
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2349
bool isFunctionOrMethod() const
Definition: DeclBase.h:2141
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1285
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1385
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1404
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2082
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1415
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition: DeclGroup.h:68
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
ValueDecl * getDecl()
Definition: Expr.h:1333
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:648
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:829
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:309
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:595
static const TST TST_typename
Definition: DeclSpec.h:306
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition: DeclSpec.cpp:645
bool isNoreturnSpecified() const
Definition: DeclSpec.h:661
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:860
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:575
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:574
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:709
static const TST TST_interface
Definition: DeclSpec.h:304
static const TST TST_typeofExpr
Definition: DeclSpec.h:308
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:616
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:708
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:662
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:505
static const TST TST_union
Definition: DeclSpec.h:302
SCS
storage-class-specifier
Definition: DeclSpec.h:251
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
static const TST TST_int
Definition: DeclSpec.h:285
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:830
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1504
ParsedType getRepAsType() const
Definition: DeclSpec.h:547
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:788
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:502
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:873
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:626
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:617
Expr * getRepAsExpr() const
Definition: DeclSpec.h:555
static const TST TST_enum
Definition: DeclSpec.h:301
static const TST TST_decltype
Definition: DeclSpec.h:311
static bool isDeclRep(TST T)
Definition: DeclSpec.h:469
bool isInlineSpecified() const
Definition: DeclSpec.h:637
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:618
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:310
static const TST TST_class
Definition: DeclSpec.h:305
static const TST TST_void
Definition: DeclSpec.h:279
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:558
static const TST TST_atomic
Definition: DeclSpec.h:321
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:511
Decl * getRepAsDecl() const
Definition: DeclSpec.h:551
static const TST TST_unspecified
Definition: DeclSpec.h:278
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:620
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:649
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:792
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:267
static const TST TST_error
Definition: DeclSpec.h:328
bool isTypeSpecOwned() const
Definition: DeclSpec.h:541
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:640
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:621
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:619
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:821
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
static const TST TST_typeofType
Definition: DeclSpec.h:307
static const TST TST_auto
Definition: DeclSpec.h:318
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:832
static const TST TST_struct
Definition: DeclSpec.h:303
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1050
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1065
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition: DeclBase.cpp:314
bool isInStdNamespace() const
Definition: DeclBase.cpp:422
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1215
bool isFromGlobalModule() const
Whether this declaration comes from global module.
Definition: DeclBase.cpp:1160
T * getAttr() const
Definition: DeclBase.h:576
bool hasAttrs() const
Definition: DeclBase.h:521
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:520
void addAttr(Attr *A)
Definition: DeclBase.cpp:1010
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:523
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:764
bool isInNamedModule() const
Whether this declaration comes from a named module.
Definition: DeclBase.cpp:1164
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1140
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:99
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:635
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:882
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1208
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1206
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1207
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:281
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1109
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:574
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:835
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:246
void dropAttrs()
Definition: DeclBase.cpp:1003
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition: DeclBase.h:210
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition: DeclBase.h:1169
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2766
bool isInvalidDecl() const
Definition: DeclBase.h:591
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1158
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:505
SourceLocation getLocation() const
Definition: DeclBase.h:442
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:822
void setImplicit(bool I=true)
Definition: DeclBase.h:597
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:611
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:549
DeclContext * getDeclContext()
Definition: DeclBase.h:451
attr_range attrs() const
Definition: DeclBase.h:538
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
void dropAttr()
Definition: DeclBase.h:559
AttrVec & getAttrs()
Definition: DeclBase.h:527
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:355
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1624
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
bool hasAttr() const
Definition: DeclBase.h:580
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1224
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:359
Kind getKind() const
Definition: DeclBase.h:445
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:735
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:792
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:777
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2039
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2079
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1977
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:822
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:769
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1989
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:810
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2023
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2401
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2050
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2686
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2342
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2397
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2689
A decomposition declaration.
Definition: DeclCXX.h:4184
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3428
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1792
SourceRange getSourceRange() const
Definition: DeclSpec.h:1839
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1837
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6522
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:6543
bool isDeduced() const
Definition: Type.h:6544
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2454
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2434
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2443
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:954
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2354
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2368
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3277
llvm::APSInt getInitVal() const
Definition: Decl.h:3297
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5476
const Expr * getInitExpr() const
Definition: Decl.h:3295
Represents an enum.
Definition: Decl.h:3847
enumerator_range enumerators() const
Definition: Decl.h:3980
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4052
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4016
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4019
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4066
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4875
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4920
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4061
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4895
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:4002
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4007
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
This represents one expression.
Definition: Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3090
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3086
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3070
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:978
void applyChanges(FPOptionsOverride FPO)
Definition: LangOptions.h:1091
bool isFPConstrained() const
Definition: LangOptions.h:906
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Definition: LangOptions.h:1085
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3124
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4570
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4607
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3250
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4555
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5608
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:101
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2565
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2404
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4064
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3609
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4057
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3262
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2249
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2577
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2556
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3883
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3638
param_iterator param_end()
Definition: Decl.h:2662
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2571
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3582
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2317
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2305
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3494
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4172
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2376
void setWillHaveBody(bool V=true)
Definition: Decl.h:2562
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2371
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4182
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3623
param_iterator param_begin()
Definition: Decl.h:2661
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2698
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3096
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3009
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3320
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4116
@ TK_MemberSpecialization
Definition: Decl.h:1947
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2763
bool isStatic() const
Definition: Decl.h:2804
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4382
void setTrivial(bool IT)
Definition: Decl.h:2306
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4003
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isDeletedAsWritten() const
Definition: Decl.h:2472
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2393
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2288
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3498
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2292
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2356
bool isImmediateEscalating() const
Definition: Decl.cpp:3275
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2284
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2555
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2217
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3313
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2791
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3372
bool param_empty() const
Definition: Decl.h:2660
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2124
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3187
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2153
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3578
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2349
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4405
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2808
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3997
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3989
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2401
void setDefaulted(bool D=true)
Definition: Decl.h:2314
bool isConsteval() const
Definition: Decl.h:2410
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2737
void setBody(Stmt *B)
Definition: Decl.cpp:3255
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3512
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3133
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2387
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4024
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3702
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2146
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3163
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2363
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3210
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2774
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3564
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2561
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:5039
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5373
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4903
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
unsigned getNumParams() const
Definition: Type.h:5355
QualType getParamType(unsigned i) const
Definition: Type.h:5357
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5561
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5388
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5479
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5366
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5362
ArrayRef< QualType > param_types() const
Definition: Type.h:5511
Declaration of a template function.
Definition: DeclTemplate.h:959
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Definition: DeclTemplate.h:541
Wrapper for source info for functions.
Definition: TypeLoc.h:1459
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4432
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4547
CallingConv getCC() const
Definition: Type.h:4494
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4513
unsigned getRegParm() const
Definition: Type.h:4487
bool getNoCallerSavedRegs() const
Definition: Type.h:4483
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
bool getHasRegParm() const
Definition: Type.h:4485
bool getNoReturn() const
Definition: Type.h:4480
bool getProducesResult() const
Definition: Type.h:4481
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4527
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4541
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4655
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3537
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4613
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4609
unsigned getRegParmType() const
Definition: Type.h:4646
CallingConv getCallConv() const
Definition: Type.h:4654
QualType getReturnType() const
Definition: Type.h:4643
bool getCmseNSCallAttr() const
Definition: Type.h:4653
@ SME_PStateSMEnabledMask
Definition: Type.h:4587
@ SME_PStateSMCompatibleMask
Definition: Type.h:4588
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
bool isPlaceholder() const
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
iterator begin(DeclarationName Name)
Returns an iterator over decls with the name 'Name'.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
void InsertDeclAfter(iterator Pos, NamedDecl *D)
Insert the given declaration after the given iterator position.
iterator end()
Returns the end iterator.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
bool isDeclInScope(Decl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2082
Represents a C array with an unspecified size.
Definition: Type.h:3764
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3321
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5504
void setInherited(bool I)
Definition: Attr.h:155
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2524
Describes an C or C++ initializer list.
Definition: Expr.h:5088
child_range children()
Definition: Expr.h:5280
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
Describes the sequence of initializations required to initialize a given object or reference with a s...
step_iterator step_begin() const
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:7584
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Describes an entity that is being initialized.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:973
Represents the declaration of a label.
Definition: Decl.h:503
bool isResolvedMSAsmLabel() const
Definition: Decl.h:538
LabelStmt * getStmt() const
Definition: Decl.h:527
bool isMSAsmLabel() const
Definition: Decl.h:537
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:289
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:672
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:816
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:721
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
Definition: LangOptions.cpp:79
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
Definition: LangOptions.h:591
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:727
bool isSYCL() const
Definition: LangOptions.h:771
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:573
void push_back(const T &LocalValue)
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition: Lexer.cpp:1357
Represents a linkage specification.
Definition: DeclCXX.h:2952
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:3012
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
DeclClass * getAsSingle() const
Definition: Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isAmbiguous() const
Definition: Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:670
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition: Lookup.h:146
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
Describes a module or submodule.
Definition: Module.h:115
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:121
Module * Parent
The parent of this module.
Definition: Module.h:164
bool isPrivateModule() const
Definition: Module.h:220
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:619
bool isModuleImplementation() const
Is this a module implementation.
Definition: Module.h:635
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:624
bool isImplicitGlobalModule() const
Definition: Module.h:216
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:240
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:195
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:693
@ ClassId_NSObject
Definition: NSAPI.h:30
This represents a decl that may have a name.
Definition: Decl.h:253
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:466
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1079
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:458
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:408
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:699
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1919
bool isExternallyVisible() const
Definition: Decl.h:412
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:376
Represent a C++ namespace.
Definition: Decl.h:551
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:602
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
SourceRange getLocalSourceRange() const
Retrieve the source range covering just the last part of this nested-name-specifier,...
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool containsErrors() const
Whether this nested name specifier contains an error.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2774
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:79
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1761
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
Definition: DeclObjC.cpp:1831
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:941
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
param_const_iterator param_end() const
Definition: DeclObjC.h:358
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
bool isOptional() const
Definition: DeclObjC.h:505
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:350
bool isFragile() const
The inverse of isNonFragile(): does this runtime follow the set of implied behaviors for a "fragile" ...
Definition: ObjCRuntime.h:97
Wrapper for void* pointer.
Definition: Ownership.h:50
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(PtrTy P)
Definition: Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
MapType::iterator iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:255
Expr ** getExprs()
Definition: Expr.h:5905
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5894
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1234
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1247
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1230
Sugar for parentheses used when specifying types.
Definition: Type.h:3172
Represents a parameter to a function.
Definition: Decl.h:1725
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1785
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1789
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
QualType getOriginalType() const
Definition: Decl.cpp:2931
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2922
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:836
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:916
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:956
AttributePool & getPool() const
Definition: ParsedAttr.h:963
PipeType - OpenCL20.
Definition: Type.h:7780
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1313
Wrapper for source info for pointers.
Definition: TypeLoc.h:1332
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1338
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
HeaderSearch & getHeaderSearchInfo() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8015
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:8009
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition: Type.h:8078
@ DK_nontrivial_c_struct
Definition: Type.h:1524
PrimitiveDefaultInitializeKind
Definition: Type.h:1452
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2867
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:102
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1209
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1291
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2915
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8057
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition: Type.h:8072
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7971
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getCanonicalType() const
Definition: Type.h:7983
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2899
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1428
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8004
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
bool isCanonical() const
Definition: Type.h:7988
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1304
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1437
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2641
NonConstantStorageReason
Definition: Type.h:1013
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1482
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1487
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:8066
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7871
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7878
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4420
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
bool hasConst() const
Definition: Type.h:450
void removeConst()
Definition: Type.h:452
void addConst()
Definition: Type.h:453
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
bool empty() const
Definition: Type.h:640
Represents a struct/union/class.
Definition: Decl.h:4148
bool hasObjectMember() const
Definition: Decl.h:4208
field_range fields() const
Definition: Decl.h:4354
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5038
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5058
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5104
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4339
field_iterator field_begin() const
Definition: Decl.cpp:5092
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:7258
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:864
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
redecl_iterator redecls_end() const
Definition: Redeclarable.h:302
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4981
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:222
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3046
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3094
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition: Scope.h:382
void RemoveDecl(Decl *D)
Definition: Scope.h:354
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:385
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:582
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:271
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
void checkAllowedInitializer(VarDecl *VD)
Definition: SemaCUDA.cpp:656
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1068
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition: SemaCUDA.cpp:738
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:1003
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:803
void CheckEntryPoint(FunctionDecl *FD)
Definition: SemaHLSL.cpp:353
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:253
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition: SemaHLSL.cpp:320
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition: SemaHLSL.cpp:287
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition: SemaHLSL.cpp:267
void ActOnVariableDeclarator(VarDecl *VD)
Definition: SemaHLSL.cpp:2494
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Definition: SemaObjC.cpp:1161
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
Definition: SemaObjC.cpp:1447
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: SemaObjC.h:591
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Decl *D, SmallVectorImpl< FunctionDecl * > &Bases)
Register D as specialization of all base functions in Bases in the current omp begin/end declare vari...
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl< FunctionDecl * > &Bases)
The declarator D defines a function in the scope S which is nested in an omp begin/end declare varian...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D, const llvm::StringMap< bool > &FeatureMap)
Definition: SemaRISCV.cpp:1372
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition: SemaSwift.cpp:26
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition: SemaWasm.cpp:266
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition: SemaWasm.cpp:245
bool IsAlignAttr() const
Definition: Sema.h:1500
Mode getAlignMode() const
Definition: Sema.h:1502
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3003
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:984
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:996
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition: Sema.h:3247
static NameClassification VarTemplate(TemplateName Name)
Definition: Sema.h:3257
static NameClassification Unknown()
Definition: Sema.h:3227
static NameClassification OverloadSet(ExprResult E)
Definition: Sema.h:3231
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition: Sema.h:3275
static NameClassification FunctionTemplate(TemplateName Name)
Definition: Sema.h:3263
static NameClassification NonType(NamedDecl *D)
Definition: Sema.h:3237
static NameClassification Concept(TemplateName Name)
Definition: Sema.h:3269
static NameClassification UndeclaredNonType()
Definition: Sema.h:3243
static NameClassification TypeTemplate(TemplateName Name)
Definition: Sema.h:3251
static NameClassification Error()
Definition: Sema.h:3225
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12079
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12109
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:463
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14284
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:11006
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6394
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:3095
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6677
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12636
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition: Sema.cpp:2386
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:731
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
Definition: SemaDecl.cpp:2469
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:9082
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
Definition: SemaDecl.cpp:6597
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9776
bool CheckExplicitObjectOverride(CXXMethodDecl *New, const CXXMethodDecl *Old)
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1559
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15177
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old)
Merge the exception specifications of two variable declarations.
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7837
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:5828
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:8979
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8983
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:9002
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9018
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:9015
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8991
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:8986
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6613
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2180
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5306
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15876
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12931
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:36
NonTrivialCUnionContext
Definition: Sema.h:3617
@ NTCUC_CopyInit
Definition: Sema.h:3627
@ NTCUC_AutoVar
Definition: Sema.h:3625
@ NTCUC_DefaultInitializedObject
Definition: Sema.h:3623
@ NTCUC_FunctionReturn
Definition: Sema.h:3621
@ NTCUC_FunctionParam
Definition: Sema.h:3619
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld, bool NewDeclIsDefn)
MergeFunctionDecl - We just parsed a function 'New' from declarator D which has the same name and sco...
Definition: SemaDecl.cpp:3519
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Definition: SemaDecl.cpp:6090
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
Definition: SemaLookup.cpp:995
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:18275
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
Definition: SemaDecl.cpp:7430
SemaOpenMP & OpenMP()
Definition: Sema.h:1125
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6075
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:866
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18207
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:4318
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:3077
PragmaClangSection PragmaClangRodataSection
Definition: Sema.h:1426
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:16415
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:6025
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:15043
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
Definition: SemaAttr.cpp:1190
SemaCUDA & CUDA()
Definition: Sema.h:1070
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17387
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
void ActOnExitFunctionContext()
Definition: SemaDecl.cpp:1455
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
Definition: SemaAttr.cpp:272
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2290
Preprocessor & getPreprocessor() const
Definition: Sema.h:530
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6828
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1657
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:1651
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
Definition: SemaAttr.cpp:1268
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6218
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17145
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4805
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition: SemaAttr.cpp:53
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
Definition: SemaDecl.cpp:12345
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16616
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
Definition: SemaDecl.cpp:2099
@ Delete
deleted-function-body
ExprResult VerifyBitField(SourceLocation FieldLoc, const IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
Definition: SemaDecl.cpp:18294
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
Definition: SemaDecl.cpp:18390
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
Definition: SemaDecl.cpp:14657
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
Definition: SemaDecl.cpp:1431
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15512
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1568
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3397
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition: SemaDecl.cpp:641
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
Definition: SemaDecl.cpp:1657
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: SemaDecl.cpp:20259
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15164
ASTContext & Context
Definition: Sema.h:908
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14677
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5782
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:528
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20280
void * SkippedDefinitionContext
Definition: Sema.h:3942
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:916
SemaObjC & ObjC()
Definition: Sema.h:1110
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
Definition: SemaDecl.cpp:5311
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4915
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:70
@ AllowFold
Definition: Sema.h:7238
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1497
PragmaStack< bool > StrictGuardStackCheckStack
Definition: Sema.h:1654
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition: Sema.h:3085
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
Definition: SemaDecl.cpp:2331
ASTContext & getASTContext() const
Definition: Sema.h:531
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
void CheckCoroutineWrapper(FunctionDecl *FD)
Definition: SemaDecl.cpp:15948
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
Definition: SemaDecl.cpp:1713
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17820
PragmaStack< StringLiteral * > ConstSegStack
Definition: Sema.h:1650
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:690
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:665
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3101
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition: SemaAttr.cpp:111
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
Definition: SemaDecl.cpp:4762
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9435
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20426
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:816
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
Definition: SemaDecl.cpp:5464
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1573
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:16951
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:9039
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11782
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7955
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition: SemaAttr.cpp:792
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:4352
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2178
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
Definition: SemaDecl.cpp:1247
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition: Sema.h:4157
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16850
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition: Sema.h:526
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:81
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2196
void PopCompoundScope()
Definition: Sema.cpp:2328
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:19730
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition: Sema.h:13908
@ UPPC_EnumeratorValue
The enumerator value.
Definition: Sema.h:13911
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13923
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13917
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13896
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13935
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition: Sema.h:13920
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13899
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition: Sema.h:13902
const LangOptions & getLangOpts() const
Definition: Sema.h:524
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
SourceLocation CurInitSegLoc
Definition: Sema.h:1690
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:::lifetimebound]] attr for std:: functions and methods.
Definition: SemaAttr.cpp:219
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition: Sema.h:3102
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1388
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
Definition: SemaDecl.cpp:6573
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
Definition: SemaDecl.cpp:6607
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1598
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition: Sema.h:907
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
Definition: SemaDecl.cpp:8239
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition: Sema.cpp:1978
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
const LangOptions & LangOpts
Definition: Sema.h:906
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2404
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:14989
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15352
SemaHLSL & HLSL()
Definition: Sema.h:1075
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1830
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11912
CXXRecordDecl * getStdBadAlloc() const
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
Definition: SemaDecl.cpp:18485
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
PragmaClangSection PragmaClangRelroSection
Definition: Sema.h:1427
SemaRISCV & RISCV()
Definition: Sema.h:1140
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition: Sema.h:15153
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
Definition: SemaStmt.cpp:3671
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:205
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20059
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
SemaSwift & Swift()
Definition: Sema.h:1150
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
Definition: SemaAttr.cpp:1312
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:1639
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
Definition: SemaDecl.cpp:15834
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6473
PragmaStack< StringLiteral * > BSSSegStack
Definition: Sema.h:1649
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:735
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9531
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:8119
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition: SemaDecl.cpp:860
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
Definition: SemaDecl.cpp:16926
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1375
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8386
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:12532
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:19756
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:939
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2323
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14909
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2287
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2262
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:20314
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18683
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6470
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1324
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
Definition: SemaDecl.cpp:18165
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
Definition: SemaInit.cpp:9788
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8914
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:14983
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition: Sema.h:1689
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20344
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9581
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
Definition: SemaDecl.cpp:8934
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:15458
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:18156
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15382
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1043
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:14949
SemaOpenCL & OpenCL()
Definition: Sema.h:1120
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5787
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15219
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
Definition: SemaDecl.cpp:8427
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1289
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4707
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
Definition: SemaDecl.cpp:15809
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition: Sema.h:3099
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9190
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
Definition: SemaDecl.cpp:15858
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT)
Determines if we can perform a correct type check for D as a redeclaration of PrevDecl.
Definition: SemaDecl.cpp:11018
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13483
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3835
@ NTK_Typedef
Definition: Sema.h:3840
@ NTK_NonUnion
Definition: Sema.h:3838
@ NTK_TypeAlias
Definition: Sema.h:3841
@ NTK_NonClass
Definition: Sema.h:3837
@ NTK_NonEnum
Definition: Sema.h:3839
@ NTK_NonStruct
Definition: Sema.h:3836
@ NTK_TemplateTemplateArgument
Definition: Sema.h:3844
@ NTK_TypeAliasTemplate
Definition: Sema.h:3843
@ NTK_Template
Definition: Sema.h:3842
SourceManager & getSourceManager() const
Definition: Sema.h:529
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_bits attribute.
Definition: Sema.h:3052
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
Definition: SemaDecl.cpp:4277
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:20011
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1340
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
Definition: SemaDecl.cpp:11193
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:18142
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
PragmaClangSection PragmaClangTextSection
Definition: Sema.h:1428
@ NTCUK_Destruct
Definition: Sema.h:3647
@ NTCUK_Init
Definition: Sema.h:3646
@ NTCUK_Copy
Definition: Sema.h:3648
PragmaClangSection PragmaClangDataSection
Definition: Sema.h:1425
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20245
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15886
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13903
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
Definition: SemaDecl.cpp:1228
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
Definition: SemaDecl.cpp:20287
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition: SemaAttr.cpp:89
MaybeODRUseExprSet MaybeODRUseExprs
Definition: Sema.h:6280
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
Definition: SemaDecl.cpp:20271
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8262
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
@ CTK_NonError
Definition: Sema.h:9376
@ CTK_ErrorRecovery
Definition: Sema.h:9377
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14313
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14834
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2344
RedeclarationKind forRedeclarationInCurContext() const
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:4468
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:6047
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition: SemaDecl.cpp:592
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
@ CCEK_Enumerator
Enumerator value with fixed underlying type.
Definition: Sema.h:9993
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:18746
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3083
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
Definition: SemaDecl.cpp:1893
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition: Sema.h:3073
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:286
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19542
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12567
ASTConsumer & Consumer
Definition: Sema.h:909
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4220
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:9780
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:9772
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:9776
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6477
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2050
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:944
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1684
@ FirstDecl
Parsing the first decl in a TU.
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:16547
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition: Sema.h:4036
@ AMK_None
Don't merge availability attributes at all.
Definition: Sema.h:4038
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:4044
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:4047
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:4050
@ AMK_Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition: Sema.h:4041
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14953
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5703
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14620
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Definition: SemaDecl.cpp:17135
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
Definition: SemaDecl.cpp:4785
SemaPPC & PPC()
Definition: Sema.h:1130
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:76
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9068
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15304
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:871
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1336
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20894
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18992
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD)
Only called on function definitions; if there is a MSVC #pragma optimize in scope,...
Definition: SemaAttr.cpp:1291
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
Definition: SemaDecl.cpp:11042
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:3092
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17897
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7910
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1308
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition: Sema.h:911
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
Definition: SemaDecl.cpp:5740
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15943
DiagnosticsEngine & Diags
Definition: Sema.h:910
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:525
FPOptions CurFPFeatures
Definition: Sema.h:904
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15939
NamespaceDecl * getStdNamespace() const
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6630
PragmaStack< StringLiteral * > DataSegStack
Definition: Sema.h:1648
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:691
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7253
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
Definition: SemaDecl.cpp:14984
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11276
@ TPC_ClassTemplateMember
Definition: Sema.h:11274
@ TPC_FunctionTemplate
Definition: Sema.h:11273
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11277
@ TPC_VarTemplate
Definition: Sema.h:11272
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
Definition: SemaDecl.cpp:6714
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16402
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2068
void PopDeclContext()
Definition: SemaDecl.cpp:1315
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6059
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1579
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8879
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13945
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
Definition: SemaDecl.cpp:13113
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1564
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:16794
OffsetOfKind
Definition: Sema.h:3859
@ OOK_Outside
Definition: Sema.h:3861
@ OOK_Macro
Definition: Sema.h:3866
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13386
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
Definition: SemaDecl.cpp:18382
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, IdentifierInfo *IIEnvironment)
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
Definition: SemaDecl.cpp:4313
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void ActOnCXXForRangeDecl(Decl *D)
Definition: SemaDecl.cpp:14230
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:282
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition: Sema.h:3067
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1961
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21161
PragmaClangSection PragmaClangBSSSection
Definition: Sema.h:1424
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6049
@ AbstractVariableType
Definition: Sema.h:5752
@ AbstractReturnType
Definition: Sema.h:5750
@ AbstractFieldType
Definition: Sema.h:5753
@ AbstractIvarType
Definition: Sema.h:5754
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
void CheckAlignasUnderalignment(Decl *D)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
Definition: SemaDecl.cpp:1703
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7959
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
Definition: SemaDecl.cpp:1237
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
Definition: SemaType.cpp:8133
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:20326
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8598
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
Definition: SemaDecl.cpp:1322
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13079
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:2435
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2750
llvm::SmallPtrSet< const NamedDecl *, 4 > TypoCorrectedFunctionDefinitions
The function definitions which were renamed as part of typo-correction to match their respective decl...
Definition: Sema.h:3048
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
Definition: SemaAttr.cpp:1275
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
Definition: SemaDecl.cpp:15823
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
Definition: SemaDecl.cpp:13365
SemaWasm & Wasm()
Definition: Sema.h:1160
IdentifierResolver IdResolver
Definition: Sema.h:2996
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
Definition: SemaDecl.cpp:19982
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2335
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:681
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
Definition: SemaDecl.cpp:15193
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition: Sema.h:7918
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling)
TemplateNameKindForDiagnostics
Describes the detailed kind of a template name. Used in diagnostics.
Definition: Sema.h:3368
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6036
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
Definition: SemaDecl.cpp:16867
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:317
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8261
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Definition: SemaDecl.cpp:1264
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
OptionalFileEntryRef getFileEntryRefForID(FileID FID) const
Returns the FileEntryRef for the provided FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
child_range children()
Definition: Stmt.cpp:294
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1931
StringRef getString() const
Definition: Expr.h:1855
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3564
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3839
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3687
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3662
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3648
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3667
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4760
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4751
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4743
bool isUnion() const
Definition: Decl.h:3770
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4806
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4843
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3788
TagKind getTagKind() const
Definition: Decl.h:3759
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:238
Exposes information about the current target.
Definition: TargetInfo.h:220
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1540
unsigned getShortWidth() const
getShortWidth/Align - Return the size of 'signed short' and 'unsigned short' for this target,...
Definition: TargetInfo.h:514
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:519
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1826
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:529
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1583
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1591
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1530
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1399
unsigned getCharWidth() const
Definition: TargetInfo.h:509
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:565
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:524
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1504
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1300
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1493
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:656
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6661
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4340
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:99
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
A declaration that models statements at global scope.
Definition: Decl.h:4437
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5623
Represents a declaration of a type.
Definition: Decl.h:3370
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3396
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:338
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1256
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:206
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition: TypeLoc.cpp:749
SourceLocation getTemplateKeywordLoc() const
Get the SourceLocation of the template keyword (if any).
Definition: TypeLoc.cpp:756
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2715
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7902
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7913
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6924
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3178
The base class of the type hierarchy.
Definition: Type.h:1828
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2511
bool isStructureType() const
Definition: Type.cpp:662
bool isDecltypeType() const
Definition: Type.h:8383
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isDependentSizedArrayType() const
Definition: Type.h:8278
bool isBlockPointerType() const
Definition: Type.h:8200
bool isVoidType() const
Definition: Type.h:8510
bool isBooleanType() const
Definition: Type.h:8638
bool isFunctionReferenceType() const
Definition: Type.h:8233
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8688
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2937
bool isIncompleteArrayType() const
Definition: Type.h:8266
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8809
bool isDependentAddressSpaceType() const
Definition: Type.h:8324
bool isConstantArrayType() const
Definition: Type.h:8262
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8668
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isArrayType() const
Definition: Type.h:8258
bool isFunctionPointerType() const
Definition: Type.h:8226
bool isPointerType() const
Definition: Type.h:8186
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2517
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
bool isEnumeralType() const
Definition: Type.h:8290
bool isScalarType() const
Definition: Type.h:8609
bool isVariableArrayType() const
Definition: Type.h:8270
bool isClkEventT() const
Definition: Type.h:8401
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8625
bool isImageType() const
Definition: Type.h:8413
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isPipeType() const
Definition: Type.h:8420
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isBitIntType() const
Definition: Type.h:8424
bool isOpenCLSpecificType() const
Definition: Type.h:8449
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2372
bool isHalfType() const
Definition: Type.h:8514
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2045
bool isHLSLSpecificType() const
Definition: Type.h:8467
const RecordType * getAsStructureType() const
Definition: Type.cpp:754
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2501
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2700
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8681
bool isAtomicType() const
Definition: Type.h:8341
bool isFunctionProtoType() const
Definition: Type.h:2535
bool isObjCIdType() const
Definition: Type.h:8361
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isObjCObjectType() const
Definition: Type.h:8332
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5048
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8644
bool isEventT() const
Definition: Type.h:8397
bool isPointerOrReferenceType() const
Definition: Type.h:8190
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4991
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:8748
bool isFunctionType() const
Definition: Type.h:8182
bool isObjCObjectPointerType() const
Definition: Type.h:8328
bool isMemberFunctionPointerType() const
Definition: Type.h:8244
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2541
bool isFloatingType() const
Definition: Type.cpp:2283
bool isAnyPointerType() const
Definition: Type.h:8194
TypeClass getTypeClass() const
Definition: Type.h:2341
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:2050
bool isSamplerT() const
Definition: Type.h:8393
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:638
bool isNullPtrType() const
Definition: Type.h:8543
bool isRecordType() const
Definition: Type.h:8286
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4763
bool isUnionType() const
Definition: Type.cpp:704
bool isFunctionNoProtoType() const
Definition: Type.h:2534
bool isReserveIDT() const
Definition: Type.h:8409
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1924
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2513
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3514
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5525
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3413
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3463
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3478
QualType getUnderlyingType() const
Definition: Decl.h:3468
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3474
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5534
TypedefNameDecl * getDecl() const
Definition: Type.h:5740
QualType desugar() const
Definition: Type.cpp:3920
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
decl_iterator end()
decl_iterator begin()
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:419
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3338
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3402
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3182
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5394
Represents a variable declaration or definition.
Definition: Decl.h:882
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2786
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2140
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1469
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1513
TLSKind getTLSKind() const
Definition: Decl.cpp:2157
bool hasInit() const
Definition: Decl.cpp:2387
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1396
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2249
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2179
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2433
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2246
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
bool isCXXCondDecl() const
Definition: Decl.h:1559
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:893
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:896
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:890
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2152
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1541
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1177
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
void setInlineSpecified()
Definition: Decl.h:1502
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1159
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2748
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1293
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1124
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1495
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1128
const Expr * getInit() const
Definition: Decl.h:1319
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1168
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1135
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2418
void setConstexpr(bool IC)
Definition: Decl.h:1516
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:905
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:908
void setInit(Expr *I)
Definition: Decl.cpp:2449
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2334
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1249
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1246
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1252
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2791
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2234
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1204
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1119
void setImplicitlyInline()
Definition: Decl.h:1507
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1420
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1536
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2682
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1213
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2755
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1430
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2662
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3808
Expr * getSizeExpr() const
Definition: Type.h:3827
Captures information about a #pragma weak directive.
Definition: Weak.h:25
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isVariableCapture() const
Definition: ScopeInfo.h:650
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:755
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1093
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:737
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition: ScopeInfo.h:141
void addByrefBlockVar(VarDecl *VD)
Definition: ScopeInfo.h:498
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition: ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition: ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition: ScopeInfo.h:145
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition: ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:884
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition: ScopeInfo.h:915
ParmVarDecl * ExplicitObjectParameter
Definition: ScopeInfo.h:881
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:871
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:874
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:896
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
Definition: Randstruct.cpp:173
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:32
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ TST_struct
Definition: Specifiers.h:81
@ TST_class
Definition: Specifiers.h:82
@ TST_union
Definition: Specifiers.h:80
@ TST_enum
Definition: Specifiers.h:79
@ TST_interface
Definition: Specifiers.h:83
ImplicitTypenameContext
Definition: DeclSpec.h:1886
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ GNUMode
Definition: LangStandard.h:63
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ GVA_AvailableExternally
Definition: Linkage.h:74
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:30
CUDAFunctionTarget
Definition: Cuda.h:145
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
OverloadCandidateDisplayKind
Definition: Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_ConstructorTemplateId
A constructor named via a template-id.
@ IK_ConstructorName
A constructor name.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:40
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition: Linkage.h:63
@ CLanguageLinkage
Definition: Linkage.h:64
@ CXXLanguageLinkage
Definition: Linkage.h:65
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Auto
Definition: Specifiers.h:256
@ SC_PrivateExtern
Definition: Specifiers.h:253
@ SC_Extern
Definition: Specifiers.h:251
@ SC_Register
Definition: Specifiers.h:257
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:235
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:241
@ TSCS_unspecified
Definition: Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:238
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Parameter
The parameter type of a method or function.
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:50
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:307
TagUseKind
Definition: Sema.h:446
TagTypeKind
The kind of a tag type.
Definition: Type.h:6871
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
@ Union
The "union" keyword.
@ Enum
The "enum" keyword.
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:108
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
ExprResult ExprError()
Definition: Ownership.h:264
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1488
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
@ TU_Complete
The translation unit is a complete translation unit.
Definition: LangOptions.h:1098
int hasAttribute(AttributeCommonInfo::Syntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:34
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:422
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition: Lambda.h:22
@ LCD_ByRef
Definition: Lambda.h:25
@ LCD_None
Definition: Lambda.h:23
@ LCD_ByCopy
Definition: Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:229
const FunctionProtoType * T
MultiVersionKind
Definition: Decl.h:1914
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1274
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:364
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_C
Definition: Specifiers.h:279
@ CC_X86StdCall
Definition: Specifiers.h:280
@ None
The alignment was not explicit in code.
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition: Decl.cpp:5782
ReservedIdentifierStatus
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_public
Definition: Specifiers.h:124
@ AS_protected
Definition: Specifiers.h:125
@ AS_none
Definition: Specifiers.h:127
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1428
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1579
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1403
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1362
const IdentifierInfo * Ident
Definition: DeclSpec.h:1334
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1251
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1663
enum clang::DeclaratorChunk::@222 Kind
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:158
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1644
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1687
RetTy visit(QualType FT, Ts &&... Args)
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Extra information about a function prototype.
Definition: Type.h:5187
FunctionEffectsRef FunctionEffects
Definition: Type.h:5197
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:5207
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:58
std::vector< std::string > Features
Definition: TargetInfo.h:59
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
SourceLocation PragmaLocation
Definition: Sema.h:1421
ValueType CurrentValue
Definition: Sema.h:1624
bool CheckSameAsPrevious
Definition: Sema.h:350
NamedDecl * Previous
Definition: Sema.h:351
NamedDecl * New
Definition: Sema.h:352
Information about a template-id annotation token.
unsigned NumArgs
NumArgs - The number of template arguments.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.