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"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
25#include "clang/AST/Expr.h"
26#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 <functional>
65#include <optional>
66#include <unordered_map>
67
68using namespace clang;
69using namespace sema;
70
72 if (OwnedType) {
73 Decl *Group[2] = { OwnedType, Ptr };
75 }
76
78}
79
80namespace {
81
82class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
83 public:
84 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
85 bool AllowTemplates = false,
86 bool AllowNonTemplates = true)
87 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
88 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
89 WantExpressionKeywords = false;
90 WantCXXNamedCasts = false;
91 WantRemainingKeywords = false;
92 }
93
94 bool ValidateCandidate(const TypoCorrection &candidate) override {
95 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
96 if (!AllowInvalidDecl && ND->isInvalidDecl())
97 return false;
98
100 return AllowTemplates;
101
102 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
103 if (!IsType)
104 return false;
105
106 if (AllowNonTemplates)
107 return true;
108
109 // An injected-class-name of a class template (specialization) is valid
110 // as a template or as a non-template.
111 if (AllowTemplates) {
112 auto *RD = dyn_cast<CXXRecordDecl>(ND);
113 if (!RD || !RD->isInjectedClassName())
114 return false;
115 RD = cast<CXXRecordDecl>(RD->getDeclContext());
116 return RD->getDescribedClassTemplate() ||
117 isa<ClassTemplateSpecializationDecl>(RD);
118 }
119
120 return false;
121 }
122
123 return !WantClassName && candidate.isKeyword();
124 }
125
126 std::unique_ptr<CorrectionCandidateCallback> clone() override {
127 return std::make_unique<TypeNameValidatorCCC>(*this);
128 }
129
130 private:
131 bool AllowInvalidDecl;
132 bool WantClassName;
133 bool AllowTemplates;
134 bool AllowNonTemplates;
135};
136
137} // end anonymous namespace
138
139namespace {
140enum class UnqualifiedTypeNameLookupResult {
141 NotFound,
142 FoundNonType,
143 FoundType
144};
145} // end anonymous namespace
146
147/// Tries to perform unqualified lookup of the type decls in bases for
148/// dependent class.
149/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
150/// type decl, \a FoundType if only type decls are found.
151static UnqualifiedTypeNameLookupResult
153 SourceLocation NameLoc,
154 const CXXRecordDecl *RD) {
155 if (!RD->hasDefinition())
156 return UnqualifiedTypeNameLookupResult::NotFound;
157 // Look for type decls in base classes.
158 UnqualifiedTypeNameLookupResult FoundTypeDecl =
159 UnqualifiedTypeNameLookupResult::NotFound;
160 for (const auto &Base : RD->bases()) {
161 const CXXRecordDecl *BaseRD = nullptr;
162 if (auto *BaseTT = Base.getType()->getAs<TagType>())
163 BaseRD = BaseTT->getAsCXXRecordDecl();
164 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
165 // Look for type decls in dependent base classes that have known primary
166 // templates.
167 if (!TST || !TST->isDependentType())
168 continue;
169 auto *TD = TST->getTemplateName().getAsTemplateDecl();
170 if (!TD)
171 continue;
172 if (auto *BasePrimaryTemplate =
173 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
174 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
175 BaseRD = BasePrimaryTemplate;
176 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
178 CTD->findPartialSpecialization(Base.getType()))
179 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
180 BaseRD = PS;
181 }
182 }
183 }
184 if (BaseRD) {
185 for (NamedDecl *ND : BaseRD->lookup(&II)) {
186 if (!isa<TypeDecl>(ND))
187 return UnqualifiedTypeNameLookupResult::FoundNonType;
188 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
189 }
190 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
191 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
192 case UnqualifiedTypeNameLookupResult::FoundNonType:
193 return UnqualifiedTypeNameLookupResult::FoundNonType;
194 case UnqualifiedTypeNameLookupResult::FoundType:
195 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
196 break;
197 case UnqualifiedTypeNameLookupResult::NotFound:
198 break;
199 }
200 }
201 }
202 }
203
204 return FoundTypeDecl;
205}
206
208 const IdentifierInfo &II,
209 SourceLocation NameLoc) {
210 // Lookup in the parent class template context, if any.
211 const CXXRecordDecl *RD = nullptr;
212 UnqualifiedTypeNameLookupResult FoundTypeDecl =
213 UnqualifiedTypeNameLookupResult::NotFound;
214 for (DeclContext *DC = S.CurContext;
215 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
216 DC = DC->getParent()) {
217 // Look for type decls in dependent base classes that have known primary
218 // templates.
219 RD = dyn_cast<CXXRecordDecl>(DC);
220 if (RD && RD->getDescribedClassTemplate())
221 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
222 }
223 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
224 return nullptr;
225
226 // We found some types in dependent base classes. Recover as if the user
227 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
228 // lookup during template instantiation.
229 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
230
231 ASTContext &Context = S.Context;
232 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
233 cast<Type>(Context.getRecordType(RD)));
234 QualType T =
236
237 CXXScopeSpec SS;
238 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
239
240 TypeLocBuilder Builder;
241 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
242 DepTL.setNameLoc(NameLoc);
244 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
245 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
246}
247
248/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
250 SourceLocation NameLoc,
251 bool WantNontrivialTypeSourceInfo = true) {
252 switch (T->getTypeClass()) {
253 case Type::DeducedTemplateSpecialization:
254 case Type::Enum:
255 case Type::InjectedClassName:
256 case Type::Record:
257 case Type::Typedef:
258 case Type::UnresolvedUsing:
259 case Type::Using:
260 break;
261 // These can never be qualified so an ElaboratedType node
262 // would carry no additional meaning.
263 case Type::ObjCInterface:
264 case Type::ObjCTypeParam:
265 case Type::TemplateTypeParm:
266 return ParsedType::make(T);
267 default:
268 llvm_unreachable("Unexpected Type Class");
269 }
270
271 if (!SS || SS->isEmpty())
273 ElaboratedTypeKeyword::None, nullptr, T, nullptr));
274
276 if (!WantNontrivialTypeSourceInfo)
277 return ParsedType::make(ElTy);
278
279 TypeLocBuilder Builder;
280 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
281 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
284 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
285}
286
288 Scope *S, CXXScopeSpec *SS, bool isClassName,
289 bool HasTrailingDot, ParsedType ObjectTypePtr,
290 bool IsCtorOrDtorName,
291 bool WantNontrivialTypeSourceInfo,
292 bool IsClassTemplateDeductionContext,
293 ImplicitTypenameContext AllowImplicitTypename,
294 IdentifierInfo **CorrectedII) {
295 // FIXME: Consider allowing this outside C++1z mode as an extension.
296 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
297 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
298 !isClassName && !HasTrailingDot;
299
300 // Determine where we will perform name lookup.
301 DeclContext *LookupCtx = nullptr;
302 if (ObjectTypePtr) {
303 QualType ObjectType = ObjectTypePtr.get();
304 if (ObjectType->isRecordType())
305 LookupCtx = computeDeclContext(ObjectType);
306 } else if (SS && SS->isNotEmpty()) {
307 LookupCtx = computeDeclContext(*SS, false);
308
309 if (!LookupCtx) {
310 if (isDependentScopeSpecifier(*SS)) {
311 // C++ [temp.res]p3:
312 // A qualified-id that refers to a type and in which the
313 // nested-name-specifier depends on a template-parameter (14.6.2)
314 // shall be prefixed by the keyword typename to indicate that the
315 // qualified-id denotes a type, forming an
316 // elaborated-type-specifier (7.1.5.3).
317 //
318 // We therefore do not perform any name lookup if the result would
319 // refer to a member of an unknown specialization.
320 // In C++2a, in several contexts a 'typename' is not required. Also
321 // allow this as an extension.
322 if (AllowImplicitTypename == ImplicitTypenameContext::No &&
323 !isClassName && !IsCtorOrDtorName)
324 return nullptr;
325 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
326 if (IsImplicitTypename) {
327 SourceLocation QualifiedLoc = SS->getRange().getBegin();
329 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
330 else
331 Diag(QualifiedLoc, diag::ext_implicit_typename)
332 << SS->getScopeRep() << II.getName()
333 << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
334 }
335
336 // We know from the grammar that this name refers to a type,
337 // so build a dependent node to describe the type.
338 if (WantNontrivialTypeSourceInfo)
339 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
340 (ImplicitTypenameContext)IsImplicitTypename)
341 .get();
342
345 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
347 SourceLocation(), QualifierLoc, II, NameLoc);
348 return ParsedType::make(T);
349 }
350
351 return nullptr;
352 }
353
354 if (!LookupCtx->isDependentContext() &&
355 RequireCompleteDeclContext(*SS, LookupCtx))
356 return nullptr;
357 }
358
359 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
360 // lookup for class-names.
361 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
363 LookupResult Result(*this, &II, NameLoc, Kind);
364 if (LookupCtx) {
365 // Perform "qualified" name lookup into the declaration context we
366 // computed, which is either the type of the base of a member access
367 // expression or the declaration context associated with a prior
368 // nested-name-specifier.
369 LookupQualifiedName(Result, LookupCtx);
370
371 if (ObjectTypePtr && Result.empty()) {
372 // C++ [basic.lookup.classref]p3:
373 // If the unqualified-id is ~type-name, the type-name is looked up
374 // in the context of the entire postfix-expression. If the type T of
375 // the object expression is of a class type C, the type-name is also
376 // looked up in the scope of class C. At least one of the lookups shall
377 // find a name that refers to (possibly cv-qualified) T.
378 LookupName(Result, S);
379 }
380 } else {
381 // Perform unqualified name lookup.
382 LookupName(Result, S);
383
384 // For unqualified lookup in a class template in MSVC mode, look into
385 // dependent base classes where the primary class template is known.
386 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
387 if (ParsedType TypeInBase =
388 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
389 return TypeInBase;
390 }
391 }
392
393 NamedDecl *IIDecl = nullptr;
394 UsingShadowDecl *FoundUsingShadow = nullptr;
395 switch (Result.getResultKind()) {
397 if (CorrectedII) {
398 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
399 AllowDeducedTemplate);
400 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
401 S, SS, CCC, CTK_ErrorRecovery);
402 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
403 TemplateTy Template;
404 bool MemberOfUnknownSpecialization;
406 TemplateName.setIdentifier(NewII, NameLoc);
408 CXXScopeSpec NewSS, *NewSSPtr = SS;
409 if (SS && NNS) {
410 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
411 NewSSPtr = &NewSS;
412 }
413 if (Correction && (NNS || NewII != &II) &&
414 // Ignore a correction to a template type as the to-be-corrected
415 // identifier is not a template (typo correction for template names
416 // is handled elsewhere).
417 !(getLangOpts().CPlusPlus && NewSSPtr &&
418 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
419 Template, MemberOfUnknownSpecialization))) {
420 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
421 isClassName, HasTrailingDot, ObjectTypePtr,
422 IsCtorOrDtorName,
423 WantNontrivialTypeSourceInfo,
424 IsClassTemplateDeductionContext);
425 if (Ty) {
426 diagnoseTypo(Correction,
427 PDiag(diag::err_unknown_type_or_class_name_suggest)
428 << Result.getLookupName() << isClassName);
429 if (SS && NNS)
430 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
431 *CorrectedII = NewII;
432 return Ty;
433 }
434 }
435 }
436 Result.suppressDiagnostics();
437 return nullptr;
439 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
441 SS->getScopeRep(), &II);
442 TypeLocBuilder TLB;
446 TL.setNameLoc(NameLoc);
448 }
449 [[fallthrough]];
452 Result.suppressDiagnostics();
453 return nullptr;
454
456 // Recover from type-hiding ambiguities by hiding the type. We'll
457 // do the lookup again when looking for an object, and we can
458 // diagnose the error then. If we don't do this, then the error
459 // about hiding the type will be immediately followed by an error
460 // that only makes sense if the identifier was treated like a type.
461 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
462 Result.suppressDiagnostics();
463 return nullptr;
464 }
465
466 // Look to see if we have a type anywhere in the list of results.
467 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
468 Res != ResEnd; ++Res) {
469 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
470 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
471 RealRes) ||
472 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
473 if (!IIDecl ||
474 // Make the selection of the recovery decl deterministic.
475 RealRes->getLocation() < IIDecl->getLocation()) {
476 IIDecl = RealRes;
477 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
478 }
479 }
480 }
481
482 if (!IIDecl) {
483 // None of the entities we found is a type, so there is no way
484 // to even assume that the result is a type. In this case, don't
485 // complain about the ambiguity. The parser will either try to
486 // perform this lookup again (e.g., as an object name), which
487 // will produce the ambiguity, or will complain that it expected
488 // a type name.
489 Result.suppressDiagnostics();
490 return nullptr;
491 }
492
493 // We found a type within the ambiguous lookup; diagnose the
494 // ambiguity and then return that type. This might be the right
495 // answer, or it might not be, but it suppresses any attempt to
496 // perform the name lookup again.
497 break;
498
500 IIDecl = Result.getFoundDecl();
501 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
502 break;
503 }
504
505 assert(IIDecl && "Didn't find decl");
506
507 QualType T;
508 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
509 // C++ [class.qual]p2: A lookup that would find the injected-class-name
510 // instead names the constructors of the class, except when naming a class.
511 // This is ill-formed when we're not actually forming a ctor or dtor name.
512 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
513 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
514 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
515 FoundRD->isInjectedClassName() &&
516 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
517 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
518 << &II << /*Type*/1;
519
520 DiagnoseUseOfDecl(IIDecl, NameLoc);
521
523 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
524 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
525 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
526 if (!HasTrailingDot)
528 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
529 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
530 (void)DiagnoseUseOfDecl(UD, NameLoc);
531 // Recover with 'int'
533 } else if (AllowDeducedTemplate) {
534 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
535 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
537 SS ? SS->getScopeRep() : nullptr, /*TemplateKeyword=*/false,
538 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
540 false);
541 // Don't wrap in a further UsingType.
542 FoundUsingShadow = nullptr;
543 }
544 }
545
546 if (T.isNull()) {
547 // If it's not plausibly a type, suppress diagnostics.
548 Result.suppressDiagnostics();
549 return nullptr;
550 }
551
552 if (FoundUsingShadow)
553 T = Context.getUsingType(FoundUsingShadow, T);
554
555 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
556}
557
558// Builds a fake NNS for the given decl context.
559static NestedNameSpecifier *
561 for (;; DC = DC->getLookupParent()) {
562 DC = DC->getPrimaryContext();
563 auto *ND = dyn_cast<NamespaceDecl>(DC);
564 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
565 return NestedNameSpecifier::Create(Context, nullptr, ND);
566 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
567 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
568 RD->getTypeForDecl());
569 else if (isa<TranslationUnitDecl>(DC))
571 }
572 llvm_unreachable("something isn't in TU scope?");
573}
574
575/// Find the parent class with dependent bases of the innermost enclosing method
576/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
577/// up allowing unqualified dependent type names at class-level, which MSVC
578/// correctly rejects.
579static const CXXRecordDecl *
581 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
582 DC = DC->getPrimaryContext();
583 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
584 if (MD->getParent()->hasAnyDependentBases())
585 return MD->getParent();
586 }
587 return nullptr;
588}
589
591 SourceLocation NameLoc,
592 bool IsTemplateTypeArg) {
593 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
594
595 NestedNameSpecifier *NNS = nullptr;
596 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
597 // If we weren't able to parse a default template argument, delay lookup
598 // until instantiation time by making a non-dependent DependentTypeName. We
599 // pretend we saw a NestedNameSpecifier referring to the current scope, and
600 // lookup is retried.
601 // FIXME: This hurts our diagnostic quality, since we get errors like "no
602 // type named 'Foo' in 'current_namespace'" when the user didn't write any
603 // name specifiers.
605 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
606 } else if (const CXXRecordDecl *RD =
608 // Build a DependentNameType that will perform lookup into RD at
609 // instantiation time.
610 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
611 RD->getTypeForDecl());
612
613 // Diagnose that this identifier was undeclared, and retry the lookup during
614 // template instantiation.
615 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
616 << RD;
617 } else {
618 // This is not a situation that we should recover from.
619 return ParsedType();
620 }
621
622 QualType T =
624
625 // Build type location information. We synthesized the qualifier, so we have
626 // to build a fake NestedNameSpecifierLoc.
627 NestedNameSpecifierLocBuilder NNSLocBuilder;
628 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
629 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
630
631 TypeLocBuilder Builder;
632 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
633 DepTL.setNameLoc(NameLoc);
635 DepTL.setQualifierLoc(QualifierLoc);
636 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
637}
638
640 // Do a tag name lookup in this scope.
641 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
642 LookupName(R, S, false);
645 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
646 switch (TD->getTagKind()) {
652 return DeclSpec::TST_union;
654 return DeclSpec::TST_class;
656 return DeclSpec::TST_enum;
657 }
658 }
659
661}
662
664 if (CurContext->isRecord()) {
666 return true;
667
668 const Type *Ty = SS->getScopeRep()->getAsType();
669
670 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
671 for (const auto &Base : RD->bases())
672 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
673 return true;
674 return S->isFunctionPrototypeScope();
675 }
676 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
677}
678
680 SourceLocation IILoc,
681 Scope *S,
682 CXXScopeSpec *SS,
683 ParsedType &SuggestedType,
684 bool IsTemplateName) {
685 // Don't report typename errors for editor placeholders.
686 if (II->isEditorPlaceholder())
687 return;
688 // We don't have anything to suggest (yet).
689 SuggestedType = nullptr;
690
691 // There may have been a typo in the name of the type. Look up typo
692 // results, in case we have something that we can suggest.
693 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
694 /*AllowTemplates=*/IsTemplateName,
695 /*AllowNonTemplates=*/!IsTemplateName);
696 if (TypoCorrection Corrected =
698 CCC, CTK_ErrorRecovery)) {
699 // FIXME: Support error recovery for the template-name case.
700 bool CanRecover = !IsTemplateName;
701 if (Corrected.isKeyword()) {
702 // We corrected to a keyword.
703 diagnoseTypo(Corrected,
704 PDiag(IsTemplateName ? diag::err_no_template_suggest
705 : diag::err_unknown_typename_suggest)
706 << II);
707 II = Corrected.getCorrectionAsIdentifierInfo();
708 } else {
709 // We found a similarly-named type or interface; suggest that.
710 if (!SS || !SS->isSet()) {
711 diagnoseTypo(Corrected,
712 PDiag(IsTemplateName ? diag::err_no_template_suggest
713 : diag::err_unknown_typename_suggest)
714 << II, CanRecover);
715 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
716 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
717 bool DroppedSpecifier =
718 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
719 diagnoseTypo(Corrected,
720 PDiag(IsTemplateName
721 ? diag::err_no_member_template_suggest
722 : diag::err_unknown_nested_typename_suggest)
723 << II << DC << DroppedSpecifier << SS->getRange(),
724 CanRecover);
725 } else {
726 llvm_unreachable("could not have corrected a typo here");
727 }
728
729 if (!CanRecover)
730 return;
731
732 CXXScopeSpec tmpSS;
733 if (Corrected.getCorrectionSpecifier())
734 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
735 SourceRange(IILoc));
736 // FIXME: Support class template argument deduction here.
737 SuggestedType =
738 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
739 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
740 /*IsCtorOrDtorName=*/false,
741 /*WantNontrivialTypeSourceInfo=*/true);
742 }
743 return;
744 }
745
746 if (getLangOpts().CPlusPlus && !IsTemplateName) {
747 // See if II is a class template that the user forgot to pass arguments to.
748 UnqualifiedId Name;
749 Name.setIdentifier(II, IILoc);
750 CXXScopeSpec EmptySS;
751 TemplateTy TemplateResult;
752 bool MemberOfUnknownSpecialization;
753 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
754 Name, nullptr, true, TemplateResult,
755 MemberOfUnknownSpecialization) == TNK_Type_template) {
756 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
757 return;
758 }
759 }
760
761 // FIXME: Should we move the logic that tries to recover from a missing tag
762 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
763
764 if (!SS || (!SS->isSet() && !SS->isInvalid()))
765 Diag(IILoc, IsTemplateName ? diag::err_no_template
766 : diag::err_unknown_typename)
767 << II;
768 else if (DeclContext *DC = computeDeclContext(*SS, false))
769 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
770 : diag::err_typename_nested_not_found)
771 << II << DC << SS->getRange();
772 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
773 SuggestedType =
774 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
775 } else if (isDependentScopeSpecifier(*SS)) {
776 unsigned DiagID = diag::err_typename_missing;
777 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
778 DiagID = diag::ext_typename_missing;
779
780 Diag(SS->getRange().getBegin(), DiagID)
781 << SS->getScopeRep() << II->getName()
782 << SourceRange(SS->getRange().getBegin(), IILoc)
783 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
784 SuggestedType = ActOnTypenameType(S, SourceLocation(),
785 *SS, *II, IILoc).get();
786 } else {
787 assert(SS && SS->isInvalid() &&
788 "Invalid scope specifier has already been diagnosed");
789 }
790}
791
792/// Determine whether the given result set contains either a type name
793/// or
794static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
795 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
796 NextToken.is(tok::less);
797
798 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
799 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
800 return true;
801
802 if (CheckTemplate && isa<TemplateDecl>(*I))
803 return true;
804 }
805
806 return false;
807}
808
810 Scope *S, CXXScopeSpec &SS,
811 IdentifierInfo *&Name,
812 SourceLocation NameLoc) {
813 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
814 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
815 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
816 StringRef FixItTagName;
817 switch (Tag->getTagKind()) {
819 FixItTagName = "class ";
820 break;
821
823 FixItTagName = "enum ";
824 break;
825
827 FixItTagName = "struct ";
828 break;
829
831 FixItTagName = "__interface ";
832 break;
833
835 FixItTagName = "union ";
836 break;
837 }
838
839 StringRef TagName = FixItTagName.drop_back();
840 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
841 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
842 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
843
844 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
845 I != IEnd; ++I)
846 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
847 << Name << TagName;
848
849 // Replace lookup results with just the tag decl.
851 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
852 return true;
853 }
854
855 return false;
856}
857
859 IdentifierInfo *&Name,
860 SourceLocation NameLoc,
861 const Token &NextToken,
863 DeclarationNameInfo NameInfo(Name, NameLoc);
864 ObjCMethodDecl *CurMethod = getCurMethodDecl();
865
866 assert(NextToken.isNot(tok::coloncolon) &&
867 "parse nested name specifiers before calling ClassifyName");
868 if (getLangOpts().CPlusPlus && SS.isSet() &&
869 isCurrentClassName(*Name, S, &SS)) {
870 // Per [class.qual]p2, this names the constructors of SS, not the
871 // injected-class-name. We don't have a classification for that.
872 // There's not much point caching this result, since the parser
873 // will reject it later.
875 }
876
877 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
878 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
879 /*AllowBuiltinCreation=*/!CurMethod);
880
881 if (SS.isInvalid())
883
884 // For unqualified lookup in a class template in MSVC mode, look into
885 // dependent base classes where the primary class template is known.
886 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
887 if (ParsedType TypeInBase =
888 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
889 return TypeInBase;
890 }
891
892 // Perform lookup for Objective-C instance variables (including automatically
893 // synthesized instance variables), if we're in an Objective-C method.
894 // FIXME: This lookup really, really needs to be folded in to the normal
895 // unqualified lookup mechanism.
896 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
897 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
898 if (Ivar.isInvalid())
900 if (Ivar.isUsable())
901 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
902
903 // We defer builtin creation until after ivar lookup inside ObjC methods.
904 if (Result.empty())
906 }
907
908 bool SecondTry = false;
909 bool IsFilteredTemplateName = false;
910
911Corrected:
912 switch (Result.getResultKind()) {
914 // If an unqualified-id is followed by a '(', then we have a function
915 // call.
916 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
917 // In C++, this is an ADL-only call.
918 // FIXME: Reference?
921
922 // C90 6.3.2.2:
923 // If the expression that precedes the parenthesized argument list in a
924 // function call consists solely of an identifier, and if no
925 // declaration is visible for this identifier, the identifier is
926 // implicitly declared exactly as if, in the innermost block containing
927 // the function call, the declaration
928 //
929 // extern int identifier ();
930 //
931 // appeared.
932 //
933 // We also allow this in C99 as an extension. However, this is not
934 // allowed in all language modes as functions without prototypes may not
935 // be supported.
936 if (getLangOpts().implicitFunctionsAllowed()) {
937 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
939 }
940 }
941
942 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
943 // In C++20 onwards, this could be an ADL-only call to a function
944 // template, and we're required to assume that this is a template name.
945 //
946 // FIXME: Find a way to still do typo correction in this case.
947 TemplateName Template =
950 }
951
952 // In C, we first see whether there is a tag type by the same name, in
953 // which case it's likely that the user just forgot to write "enum",
954 // "struct", or "union".
955 if (!getLangOpts().CPlusPlus && !SecondTry &&
956 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
957 break;
958 }
959
960 // Perform typo correction to determine if there is another name that is
961 // close to this name.
962 if (!SecondTry && CCC) {
963 SecondTry = true;
964 if (TypoCorrection Corrected =
965 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
966 &SS, *CCC, CTK_ErrorRecovery)) {
967 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
968 unsigned QualifiedDiag = diag::err_no_member_suggest;
969
970 NamedDecl *FirstDecl = Corrected.getFoundDecl();
971 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
972 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
973 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
974 UnqualifiedDiag = diag::err_no_template_suggest;
975 QualifiedDiag = diag::err_no_member_template_suggest;
976 } else if (UnderlyingFirstDecl &&
977 (isa<TypeDecl>(UnderlyingFirstDecl) ||
978 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
979 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
980 UnqualifiedDiag = diag::err_unknown_typename_suggest;
981 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
982 }
983
984 if (SS.isEmpty()) {
985 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
986 } else {// FIXME: is this even reachable? Test it.
987 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
988 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
989 Name->getName() == CorrectedStr;
990 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
991 << Name << computeDeclContext(SS, false)
992 << DroppedSpecifier << SS.getRange());
993 }
994
995 // Update the name, so that the caller has the new name.
996 Name = Corrected.getCorrectionAsIdentifierInfo();
997
998 // Typo correction corrected to a keyword.
999 if (Corrected.isKeyword())
1000 return Name;
1001
1002 // Also update the LookupResult...
1003 // FIXME: This should probably go away at some point
1004 Result.clear();
1005 Result.setLookupName(Corrected.getCorrection());
1006 if (FirstDecl)
1007 Result.addDecl(FirstDecl);
1008
1009 // If we found an Objective-C instance variable, let
1010 // LookupInObjCMethod build the appropriate expression to
1011 // reference the ivar.
1012 // FIXME: This is a gross hack.
1013 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1014 DeclResult R =
1015 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1016 if (R.isInvalid())
1018 if (R.isUsable())
1019 return NameClassification::NonType(Ivar);
1020 }
1021
1022 goto Corrected;
1023 }
1024 }
1025
1026 // We failed to correct; just fall through and let the parser deal with it.
1027 Result.suppressDiagnostics();
1029
1031 // We performed name lookup into the current instantiation, and there were
1032 // dependent bases, so we treat this result the same way as any other
1033 // dependent nested-name-specifier.
1034
1035 // C++ [temp.res]p2:
1036 // A name used in a template declaration or definition and that is
1037 // dependent on a template-parameter is assumed not to name a type
1038 // unless the applicable name lookup finds a type name or the name is
1039 // qualified by the keyword typename.
1040 //
1041 // FIXME: If the next token is '<', we might want to ask the parser to
1042 // perform some heroics to see if we actually have a
1043 // template-argument-list, which would indicate a missing 'template'
1044 // keyword here.
1046 }
1047
1051 break;
1052
1054 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1055 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1056 /*AllowDependent=*/false)) {
1057 // C++ [temp.local]p3:
1058 // A lookup that finds an injected-class-name (10.2) can result in an
1059 // ambiguity in certain cases (for example, if it is found in more than
1060 // one base class). If all of the injected-class-names that are found
1061 // refer to specializations of the same class template, and if the name
1062 // is followed by a template-argument-list, the reference refers to the
1063 // class template itself and not a specialization thereof, and is not
1064 // ambiguous.
1065 //
1066 // This filtering can make an ambiguous result into an unambiguous one,
1067 // so try again after filtering out template names.
1069 if (!Result.isAmbiguous()) {
1070 IsFilteredTemplateName = true;
1071 break;
1072 }
1073 }
1074
1075 // Diagnose the ambiguity and return an error.
1077 }
1078
1079 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1080 (IsFilteredTemplateName ||
1082 Result, /*AllowFunctionTemplates=*/true,
1083 /*AllowDependent=*/false,
1084 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1086 // C++ [temp.names]p3:
1087 // After name lookup (3.4) finds that a name is a template-name or that
1088 // an operator-function-id or a literal- operator-id refers to a set of
1089 // overloaded functions any member of which is a function template if
1090 // this is followed by a <, the < is always taken as the delimiter of a
1091 // template-argument-list and never as the less-than operator.
1092 // C++2a [temp.names]p2:
1093 // A name is also considered to refer to a template if it is an
1094 // unqualified-id followed by a < and name lookup finds either one
1095 // or more functions or finds nothing.
1096 if (!IsFilteredTemplateName)
1098
1099 bool IsFunctionTemplate;
1100 bool IsVarTemplate;
1101 TemplateName Template;
1102 if (Result.end() - Result.begin() > 1) {
1103 IsFunctionTemplate = true;
1104 Template = Context.getOverloadedTemplateName(Result.begin(),
1105 Result.end());
1106 } else if (!Result.empty()) {
1107 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1108 *Result.begin(), /*AllowFunctionTemplates=*/true,
1109 /*AllowDependent=*/false));
1110 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1111 IsVarTemplate = isa<VarTemplateDecl>(TD);
1112
1113 UsingShadowDecl *FoundUsingShadow =
1114 dyn_cast<UsingShadowDecl>(*Result.begin());
1115 assert(!FoundUsingShadow ||
1116 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1118 SS.getScopeRep(),
1119 /*TemplateKeyword=*/false,
1120 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1121 } else {
1122 // All results were non-template functions. This is a function template
1123 // name.
1124 IsFunctionTemplate = true;
1125 Template = Context.getAssumedTemplateName(NameInfo.getName());
1126 }
1127
1128 if (IsFunctionTemplate) {
1129 // Function templates always go through overload resolution, at which
1130 // point we'll perform the various checks (e.g., accessibility) we need
1131 // to based on which function we selected.
1132 Result.suppressDiagnostics();
1133
1134 return NameClassification::FunctionTemplate(Template);
1135 }
1136
1137 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1139 }
1140
1141 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1143 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1144 T = Context.getUsingType(USD, T);
1145 return buildNamedType(*this, &SS, T, NameLoc);
1146 };
1147
1148 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1149 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1150 DiagnoseUseOfDecl(Type, NameLoc);
1151 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1152 return BuildTypeFor(Type, *Result.begin());
1153 }
1154
1155 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1156 if (!Class) {
1157 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1158 if (ObjCCompatibleAliasDecl *Alias =
1159 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1160 Class = Alias->getClassInterface();
1161 }
1162
1163 if (Class) {
1164 DiagnoseUseOfDecl(Class, NameLoc);
1165
1166 if (NextToken.is(tok::period)) {
1167 // Interface. <something> is parsed as a property reference expression.
1168 // Just return "unknown" as a fall-through for now.
1169 Result.suppressDiagnostics();
1171 }
1172
1174 return ParsedType::make(T);
1175 }
1176
1177 if (isa<ConceptDecl>(FirstDecl)) {
1178 // We want to preserve the UsingShadowDecl for concepts.
1179 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1182 TemplateName(cast<TemplateDecl>(FirstDecl)));
1183 }
1184
1185 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1186 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1188 }
1189
1190 // We can have a type template here if we're classifying a template argument.
1191 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1192 !isa<VarTemplateDecl>(FirstDecl))
1194 TemplateName(cast<TemplateDecl>(FirstDecl)));
1195
1196 // Check for a tag type hidden by a non-type decl in a few cases where it
1197 // seems likely a type is wanted instead of the non-type that was found.
1198 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1199 if ((NextToken.is(tok::identifier) ||
1200 (NextIsOp &&
1201 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1202 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1203 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1204 DiagnoseUseOfDecl(Type, NameLoc);
1205 return BuildTypeFor(Type, *Result.begin());
1206 }
1207
1208 // If we already know which single declaration is referenced, just annotate
1209 // that declaration directly. Defer resolving even non-overloaded class
1210 // member accesses, as we need to defer certain access checks until we know
1211 // the context.
1212 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1213 if (Result.isSingleResult() && !ADL &&
1214 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1215 return NameClassification::NonType(Result.getRepresentativeDecl());
1216
1217 // Otherwise, this is an overload set that we will need to resolve later.
1218 Result.suppressDiagnostics();
1220 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1221 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1222 /*KnownDependent=*/false));
1223}
1224
1227 SourceLocation NameLoc) {
1228 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1229 CXXScopeSpec SS;
1230 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1231 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1232}
1233
1236 IdentifierInfo *Name,
1237 SourceLocation NameLoc,
1238 bool IsAddressOfOperand) {
1239 DeclarationNameInfo NameInfo(Name, NameLoc);
1240 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1241 NameInfo, IsAddressOfOperand,
1242 /*TemplateArgs=*/nullptr);
1243}
1244
1247 SourceLocation NameLoc,
1248 const Token &NextToken) {
1249 if (getCurMethodDecl() && SS.isEmpty())
1250 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1251 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1252
1253 // Reconstruct the lookup result.
1254 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1255 Result.addDecl(Found);
1256 Result.resolveKind();
1257
1258 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1259 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1260}
1261
1263 // For an implicit class member access, transform the result into a member
1264 // access expression if necessary.
1265 auto *ULE = cast<UnresolvedLookupExpr>(E);
1266 if ((*ULE->decls_begin())->isCXXClassMember()) {
1267 CXXScopeSpec SS;
1268 SS.Adopt(ULE->getQualifierLoc());
1269
1270 // Reconstruct the lookup result.
1271 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1273 Result.setNamingClass(ULE->getNamingClass());
1274 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1275 Result.addDecl(*I, I.getAccess());
1276 Result.resolveKind();
1278 nullptr, S);
1279 }
1280
1281 // Otherwise, this is already in the form we needed, and no further checks
1282 // are necessary.
1283 return ULE;
1284}
1285
1288 auto *TD = Name.getAsTemplateDecl();
1289 if (!TD)
1291 if (isa<ClassTemplateDecl>(TD))
1293 if (isa<FunctionTemplateDecl>(TD))
1295 if (isa<VarTemplateDecl>(TD))
1297 if (isa<TypeAliasTemplateDecl>(TD))
1299 if (isa<TemplateTemplateParmDecl>(TD))
1301 if (isa<ConceptDecl>(TD))
1304}
1305
1307 assert(DC->getLexicalParent() == CurContext &&
1308 "The next DeclContext should be lexically contained in the current one.");
1309 CurContext = DC;
1310 S->setEntity(DC);
1311}
1312
1314 assert(CurContext && "DeclContext imbalance!");
1315
1317 assert(CurContext && "Popped translation unit!");
1318}
1319
1321 Decl *D) {
1322 // Unlike PushDeclContext, the context to which we return is not necessarily
1323 // the containing DC of TD, because the new context will be some pre-existing
1324 // TagDecl definition instead of a fresh one.
1325 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1326 CurContext = cast<TagDecl>(D)->getDefinition();
1327 assert(CurContext && "skipping definition of undefined tag");
1328 // Start lookups from the parent of the current context; we don't want to look
1329 // into the pre-existing complete definition.
1330 S->setEntity(CurContext->getLookupParent());
1331 return Result;
1332}
1333
1335 CurContext = static_cast<decltype(CurContext)>(Context);
1336}
1337
1339 // C++0x [basic.lookup.unqual]p13:
1340 // A name used in the definition of a static data member of class
1341 // X (after the qualified-id of the static member) is looked up as
1342 // if the name was used in a member function of X.
1343 // C++0x [basic.lookup.unqual]p14:
1344 // If a variable member of a namespace is defined outside of the
1345 // scope of its namespace then any name used in the definition of
1346 // the variable member (after the declarator-id) is looked up as
1347 // if the definition of the variable member occurred in its
1348 // namespace.
1349 // Both of these imply that we should push a scope whose context
1350 // is the semantic context of the declaration. We can't use
1351 // PushDeclContext here because that context is not necessarily
1352 // lexically contained in the current context. Fortunately,
1353 // the containing scope should have the appropriate information.
1354
1355 assert(!S->getEntity() && "scope already has entity");
1356
1357#ifndef NDEBUG
1358 Scope *Ancestor = S->getParent();
1359 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1360 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1361#endif
1362
1363 CurContext = DC;
1364 S->setEntity(DC);
1365
1366 if (S->getParent()->isTemplateParamScope()) {
1367 // Also set the corresponding entities for all immediately-enclosing
1368 // template parameter scopes.
1369 EnterTemplatedContext(S->getParent(), DC);
1370 }
1371}
1372
1374 assert(S->getEntity() == CurContext && "Context imbalance!");
1375
1376 // Switch back to the lexical context. The safety of this is
1377 // enforced by an assert in EnterDeclaratorContext.
1378 Scope *Ancestor = S->getParent();
1379 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1380 CurContext = Ancestor->getEntity();
1381
1382 // We don't need to do anything with the scope, which is going to
1383 // disappear.
1384}
1385
1387 assert(S->isTemplateParamScope() &&
1388 "expected to be initializing a template parameter scope");
1389
1390 // C++20 [temp.local]p7:
1391 // In the definition of a member of a class template that appears outside
1392 // of the class template definition, the name of a member of the class
1393 // template hides the name of a template-parameter of any enclosing class
1394 // templates (but not a template-parameter of the member if the member is a
1395 // class or function template).
1396 // C++20 [temp.local]p9:
1397 // In the definition of a class template or in the definition of a member
1398 // of such a template that appears outside of the template definition, for
1399 // each non-dependent base class (13.8.2.1), if the name of the base class
1400 // or the name of a member of the base class is the same as the name of a
1401 // template-parameter, the base class name or member name hides the
1402 // template-parameter name (6.4.10).
1403 //
1404 // This means that a template parameter scope should be searched immediately
1405 // after searching the DeclContext for which it is a template parameter
1406 // scope. For example, for
1407 // template<typename T> template<typename U> template<typename V>
1408 // void N::A<T>::B<U>::f(...)
1409 // we search V then B<U> (and base classes) then U then A<T> (and base
1410 // classes) then T then N then ::.
1411 unsigned ScopeDepth = getTemplateDepth(S);
1412 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1413 DeclContext *SearchDCAfterScope = DC;
1414 for (; DC; DC = DC->getLookupParent()) {
1415 if (const TemplateParameterList *TPL =
1416 cast<Decl>(DC)->getDescribedTemplateParams()) {
1417 unsigned DCDepth = TPL->getDepth() + 1;
1418 if (DCDepth > ScopeDepth)
1419 continue;
1420 if (ScopeDepth == DCDepth)
1421 SearchDCAfterScope = DC = DC->getLookupParent();
1422 break;
1423 }
1424 }
1425 S->setLookupEntity(SearchDCAfterScope);
1426 }
1427}
1428
1430 // We assume that the caller has already called
1431 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1432 FunctionDecl *FD = D->getAsFunction();
1433 if (!FD)
1434 return;
1435
1436 // Same implementation as PushDeclContext, but enters the context
1437 // from the lexical parent, rather than the top-level class.
1438 assert(CurContext == FD->getLexicalParent() &&
1439 "The next DeclContext should be lexically contained in the current one.");
1440 CurContext = FD;
1441 S->setEntity(CurContext);
1442
1443 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1444 ParmVarDecl *Param = FD->getParamDecl(P);
1445 // If the parameter has an identifier, then add it to the scope
1446 if (Param->getIdentifier()) {
1447 S->AddDecl(Param);
1448 IdResolver.AddDecl(Param);
1449 }
1450 }
1451}
1452
1454 // Same implementation as PopDeclContext, but returns to the lexical parent,
1455 // rather than the top-level class.
1456 assert(CurContext && "DeclContext imbalance!");
1458 assert(CurContext && "Popped translation unit!");
1459}
1460
1461/// Determine whether overloading is allowed for a new function
1462/// declaration considering prior declarations of the same name.
1463///
1464/// This routine determines whether overloading is possible, not
1465/// whether a new declaration actually overloads a previous one.
1466/// It will return true in C++ (where overloads are always permitted)
1467/// or, as a C extension, when either the new declaration or a
1468/// previous one is declared with the 'overloadable' attribute.
1470 ASTContext &Context,
1471 const FunctionDecl *New) {
1472 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1473 return true;
1474
1475 // Multiversion function declarations are not overloads in the
1476 // usual sense of that term, but lookup will report that an
1477 // overload set was found if more than one multiversion function
1478 // declaration is present for the same name. It is therefore
1479 // inadequate to assume that some prior declaration(s) had
1480 // the overloadable attribute; checking is required. Since one
1481 // declaration is permitted to omit the attribute, it is necessary
1482 // to check at least two; hence the 'any_of' check below. Note that
1483 // the overloadable attribute is implicitly added to declarations
1484 // that were required to have it but did not.
1485 if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1486 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1487 return ND->hasAttr<OverloadableAttr>();
1488 });
1489 } else if (Previous.getResultKind() == LookupResult::Found)
1490 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1491
1492 return false;
1493}
1494
1495void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1496 // Move up the scope chain until we find the nearest enclosing
1497 // non-transparent context. The declaration will be introduced into this
1498 // scope.
1499 while (S->getEntity() && S->getEntity()->isTransparentContext())
1500 S = S->getParent();
1501
1502 // Add scoped declarations into their context, so that they can be
1503 // found later. Declarations without a context won't be inserted
1504 // into any context.
1505 if (AddToContext)
1507
1508 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1509 // are function-local declarations.
1510 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1511 return;
1512
1513 // Template instantiations should also not be pushed into scope.
1514 if (isa<FunctionDecl>(D) &&
1515 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1516 return;
1517
1518 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1519 S->AddDecl(D);
1520 return;
1521 }
1522 // If this replaces anything in the current scope,
1523 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1524 IEnd = IdResolver.end();
1525 for (; I != IEnd; ++I) {
1526 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1527 S->RemoveDecl(*I);
1529
1530 // Should only need to replace one decl.
1531 break;
1532 }
1533 }
1534
1535 S->AddDecl(D);
1536
1537 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1538 // Implicitly-generated labels may end up getting generated in an order that
1539 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1540 // the label at the appropriate place in the identifier chain.
1541 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1542 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1543 if (IDC == CurContext) {
1544 if (!S->isDeclScope(*I))
1545 continue;
1546 } else if (IDC->Encloses(CurContext))
1547 break;
1548 }
1549
1551 } else {
1553 }
1555}
1556
1558 bool AllowInlineNamespace) const {
1559 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1560}
1561
1563 DeclContext *TargetDC = DC->getPrimaryContext();
1564 do {
1565 if (DeclContext *ScopeDC = S->getEntity())
1566 if (ScopeDC->getPrimaryContext() == TargetDC)
1567 return S;
1568 } while ((S = S->getParent()));
1569
1570 return nullptr;
1571}
1572
1574 DeclContext*,
1575 ASTContext&);
1576
1578 bool ConsiderLinkage,
1579 bool AllowInlineNamespace) {
1581 while (F.hasNext()) {
1582 NamedDecl *D = F.next();
1583
1584 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1585 continue;
1586
1587 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1588 continue;
1589
1590 F.erase();
1591 }
1592
1593 F.done();
1594}
1595
1597 // [module.interface]p7:
1598 // A declaration is attached to a module as follows:
1599 // - If the declaration is a non-dependent friend declaration that nominates a
1600 // function with a declarator-id that is a qualified-id or template-id or that
1601 // nominates a class other than with an elaborated-type-specifier with neither
1602 // a nested-name-specifier nor a simple-template-id, it is attached to the
1603 // module to which the friend is attached ([basic.link]).
1604 if (New->getFriendObjectKind() &&
1608 return false;
1609 }
1610
1611 Module *NewM = New->getOwningModule();
1612 Module *OldM = Old->getOwningModule();
1613
1614 if (NewM && NewM->isPrivateModule())
1615 NewM = NewM->Parent;
1616 if (OldM && OldM->isPrivateModule())
1617 OldM = OldM->Parent;
1618
1619 if (NewM == OldM)
1620 return false;
1621
1622 if (NewM && OldM) {
1623 // A module implementation unit has visibility of the decls in its
1624 // implicitly imported interface.
1625 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1626 return false;
1627
1628 // Partitions are part of the module, but a partition could import another
1629 // module, so verify that the PMIs agree.
1630 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1631 getASTContext().isInSameModule(NewM, OldM))
1632 return false;
1633 }
1634
1635 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1636 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1637 if (NewIsModuleInterface || OldIsModuleInterface) {
1638 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1639 // if a declaration of D [...] appears in the purview of a module, all
1640 // other such declarations shall appear in the purview of the same module
1641 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1642 << New
1643 << NewIsModuleInterface
1644 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1645 << OldIsModuleInterface
1646 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1647 Diag(Old->getLocation(), diag::note_previous_declaration);
1648 New->setInvalidDecl();
1649 return true;
1650 }
1651
1652 return false;
1653}
1654
1656 // [module.interface]p1:
1657 // An export-declaration shall inhabit a namespace scope.
1658 //
1659 // So it is meaningless to talk about redeclaration which is not at namespace
1660 // scope.
1661 if (!New->getLexicalDeclContext()
1663 ->isFileContext() ||
1664 !Old->getLexicalDeclContext()
1666 ->isFileContext())
1667 return false;
1668
1669 bool IsNewExported = New->isInExportDeclContext();
1670 bool IsOldExported = Old->isInExportDeclContext();
1671
1672 // It should be irrevelant if both of them are not exported.
1673 if (!IsNewExported && !IsOldExported)
1674 return false;
1675
1676 if (IsOldExported)
1677 return false;
1678
1679 // If the Old declaration are not attached to named modules
1680 // and the New declaration are attached to global module.
1681 // It should be fine to allow the export since it doesn't change
1682 // the linkage of declarations. See
1683 // https://github.com/llvm/llvm-project/issues/98583 for details.
1684 if (!Old->isInNamedModule() && New->getOwningModule() &&
1686 return false;
1687
1688 assert(IsNewExported);
1689
1690 auto Lk = Old->getFormalLinkage();
1691 int S = 0;
1692 if (Lk == Linkage::Internal)
1693 S = 1;
1694 else if (Lk == Linkage::Module)
1695 S = 2;
1696 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1697 Diag(Old->getLocation(), diag::note_previous_declaration);
1698 return true;
1699}
1700
1703 return true;
1704
1705 if (CheckRedeclarationExported(New, Old))
1706 return true;
1707
1708 return false;
1709}
1710
1712 const NamedDecl *Old) const {
1713 assert(getASTContext().isSameEntity(New, Old) &&
1714 "New and Old are not the same definition, we should diagnostic it "
1715 "immediately instead of checking it.");
1716 assert(const_cast<Sema *>(this)->isReachable(New) &&
1717 const_cast<Sema *>(this)->isReachable(Old) &&
1718 "We shouldn't see unreachable definitions here.");
1719
1720 Module *NewM = New->getOwningModule();
1721 Module *OldM = Old->getOwningModule();
1722
1723 // We only checks for named modules here. The header like modules is skipped.
1724 // FIXME: This is not right if we import the header like modules in the module
1725 // purview.
1726 //
1727 // For example, assuming "header.h" provides definition for `D`.
1728 // ```C++
1729 // //--- M.cppm
1730 // export module M;
1731 // import "header.h"; // or #include "header.h" but import it by clang modules
1732 // actually.
1733 //
1734 // //--- Use.cpp
1735 // import M;
1736 // import "header.h"; // or uses clang modules.
1737 // ```
1738 //
1739 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1740 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1741 // reject it. But the current implementation couldn't detect the case since we
1742 // don't record the information about the importee modules.
1743 //
1744 // But this might not be painful in practice. Since the design of C++20 Named
1745 // Modules suggests us to use headers in global module fragment instead of
1746 // module purview.
1747 if (NewM && NewM->isHeaderLikeModule())
1748 NewM = nullptr;
1749 if (OldM && OldM->isHeaderLikeModule())
1750 OldM = nullptr;
1751
1752 if (!NewM && !OldM)
1753 return true;
1754
1755 // [basic.def.odr]p14.3
1756 // Each such definition shall not be attached to a named module
1757 // ([module.unit]).
1758 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1759 return true;
1760
1761 // Then New and Old lives in the same TU if their share one same module unit.
1762 if (NewM)
1763 NewM = NewM->getTopLevelModule();
1764 if (OldM)
1765 OldM = OldM->getTopLevelModule();
1766 return OldM == NewM;
1767}
1768
1770 if (D->getDeclContext()->isFileContext())
1771 return false;
1772
1773 return isa<UsingShadowDecl>(D) ||
1774 isa<UnresolvedUsingTypenameDecl>(D) ||
1775 isa<UnresolvedUsingValueDecl>(D);
1776}
1777
1778/// Removes using shadow declarations not at class scope from the lookup
1779/// results.
1782 while (F.hasNext())
1784 F.erase();
1785
1786 F.done();
1787}
1788
1789/// Check for this common pattern:
1790/// @code
1791/// class S {
1792/// S(const S&); // DO NOT IMPLEMENT
1793/// void operator=(const S&); // DO NOT IMPLEMENT
1794/// };
1795/// @endcode
1797 // FIXME: Should check for private access too but access is set after we get
1798 // the decl here.
1799 if (D->doesThisDeclarationHaveABody())
1800 return false;
1801
1802 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1803 return CD->isCopyConstructor();
1804 return D->isCopyAssignmentOperator();
1805}
1806
1807bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1808 const DeclContext *DC = D->getDeclContext();
1809 while (!DC->isTranslationUnit()) {
1810 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1811 if (!RD->hasNameForLinkage())
1812 return true;
1813 }
1814 DC = DC->getParent();
1815 }
1816
1817 return !D->isExternallyVisible();
1818}
1819
1820// FIXME: This needs to be refactored; some other isInMainFile users want
1821// these semantics.
1822static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1824 return false;
1825 return S.SourceMgr.isInMainFile(Loc);
1826}
1827
1829 assert(D);
1830
1831 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1832 return false;
1833
1834 // Ignore all entities declared within templates, and out-of-line definitions
1835 // of members of class templates.
1838 return false;
1839
1840 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1841 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1842 return false;
1843 // A non-out-of-line declaration of a member specialization was implicitly
1844 // instantiated; it's the out-of-line declaration that we're interested in.
1845 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1846 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1847 return false;
1848
1849 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1850 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1851 return false;
1852 } else {
1853 // 'static inline' functions are defined in headers; don't warn.
1854 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1855 return false;
1856 }
1857
1858 if (FD->doesThisDeclarationHaveABody() &&
1860 return false;
1861 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1862 // Constants and utility variables are defined in headers with internal
1863 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1864 // like "inline".)
1865 if (!isMainFileLoc(*this, VD->getLocation()))
1866 return false;
1867
1868 if (Context.DeclMustBeEmitted(VD))
1869 return false;
1870
1871 if (VD->isStaticDataMember() &&
1872 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1873 return false;
1874 if (VD->isStaticDataMember() &&
1875 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1876 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1877 return false;
1878
1879 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1880 return false;
1881 } else {
1882 return false;
1883 }
1884
1885 // Only warn for unused decls internal to the translation unit.
1886 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1887 // for inline functions defined in the main source file, for instance.
1888 return mightHaveNonExternalLinkage(D);
1889}
1890
1892 if (!D)
1893 return;
1894
1895 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1896 const FunctionDecl *First = FD->getFirstDecl();
1898 return; // First should already be in the vector.
1899 }
1900
1901 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1902 const VarDecl *First = VD->getFirstDecl();
1904 return; // First should already be in the vector.
1905 }
1906
1909}
1910
1911static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
1912 const NamedDecl *D) {
1913 if (D->isInvalidDecl())
1914 return false;
1915
1916 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
1917 // For a decomposition declaration, warn if none of the bindings are
1918 // referenced, instead of if the variable itself is referenced (which
1919 // it is, by the bindings' expressions).
1920 bool IsAllPlaceholders = true;
1921 for (const auto *BD : DD->bindings()) {
1922 if (BD->isReferenced() || BD->hasAttr<UnusedAttr>())
1923 return false;
1924 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts);
1925 }
1926 if (IsAllPlaceholders)
1927 return false;
1928 } else if (!D->getDeclName()) {
1929 return false;
1930 } else if (D->isReferenced() || D->isUsed()) {
1931 return false;
1932 }
1933
1934 if (D->isPlaceholderVar(LangOpts))
1935 return false;
1936
1937 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
1938 D->hasAttr<CleanupAttr>())
1939 return false;
1940
1941 if (isa<LabelDecl>(D))
1942 return true;
1943
1944 // Except for labels, we only care about unused decls that are local to
1945 // functions.
1946 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1947 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1948 // For dependent types, the diagnostic is deferred.
1949 WithinFunction =
1950 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1951 if (!WithinFunction)
1952 return false;
1953
1954 if (isa<TypedefNameDecl>(D))
1955 return true;
1956
1957 // White-list anything that isn't a local variable.
1958 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1959 return false;
1960
1961 // Types of valid local variables should be complete, so this should succeed.
1962 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1963
1964 const Expr *Init = VD->getInit();
1965 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
1966 Init = Cleanups->getSubExpr();
1967
1968 const auto *Ty = VD->getType().getTypePtr();
1969
1970 // Only look at the outermost level of typedef.
1971 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1972 // Allow anything marked with __attribute__((unused)).
1973 if (TT->getDecl()->hasAttr<UnusedAttr>())
1974 return false;
1975 }
1976
1977 // Warn for reference variables whose initializtion performs lifetime
1978 // extension.
1979 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
1980 MTE && MTE->getExtendingDecl()) {
1981 Ty = VD->getType().getNonReferenceType().getTypePtr();
1982 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
1983 }
1984
1985 // If we failed to complete the type for some reason, or if the type is
1986 // dependent, don't diagnose the variable.
1987 if (Ty->isIncompleteType() || Ty->isDependentType())
1988 return false;
1989
1990 // Look at the element type to ensure that the warning behaviour is
1991 // consistent for both scalars and arrays.
1992 Ty = Ty->getBaseElementTypeUnsafe();
1993
1994 if (const TagType *TT = Ty->getAs<TagType>()) {
1995 const TagDecl *Tag = TT->getDecl();
1996 if (Tag->hasAttr<UnusedAttr>())
1997 return false;
1998
1999 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2000 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2001 return false;
2002
2003 if (Init) {
2004 const auto *Construct =
2005 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2006 if (Construct && !Construct->isElidable()) {
2007 const CXXConstructorDecl *CD = Construct->getConstructor();
2008 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2009 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2010 return false;
2011 }
2012
2013 // Suppress the warning if we don't know how this is constructed, and
2014 // it could possibly be non-trivial constructor.
2015 if (Init->isTypeDependent()) {
2016 for (const CXXConstructorDecl *Ctor : RD->ctors())
2017 if (!Ctor->isTrivial())
2018 return false;
2019 }
2020
2021 // Suppress the warning if the constructor is unresolved because
2022 // its arguments are dependent.
2023 if (isa<CXXUnresolvedConstructExpr>(Init))
2024 return false;
2025 }
2026 }
2027 }
2028
2029 // TODO: __attribute__((unused)) templates?
2030 }
2031
2032 return true;
2033}
2034
2036 FixItHint &Hint) {
2037 if (isa<LabelDecl>(D)) {
2039 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2040 /*SkipTrailingWhitespaceAndNewline=*/false);
2041 if (AfterColon.isInvalid())
2042 return;
2045 }
2046}
2047
2050 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2051}
2052
2054 DiagReceiverTy DiagReceiver) {
2055 if (D->getTypeForDecl()->isDependentType())
2056 return;
2057
2058 for (auto *TmpD : D->decls()) {
2059 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2060 DiagnoseUnusedDecl(T, DiagReceiver);
2061 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2062 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2063 }
2064}
2065
2068 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2069}
2070
2073 return;
2074
2075 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2076 // typedefs can be referenced later on, so the diagnostics are emitted
2077 // at end-of-translation-unit.
2079 return;
2080 }
2081
2082 FixItHint Hint;
2084
2085 unsigned DiagID;
2086 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2087 DiagID = diag::warn_unused_exception_param;
2088 else if (isa<LabelDecl>(D))
2089 DiagID = diag::warn_unused_label;
2090 else
2091 DiagID = diag::warn_unused_variable;
2092
2093 SourceLocation DiagLoc = D->getLocation();
2094 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2095}
2096
2098 DiagReceiverTy DiagReceiver) {
2099 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2100 // it's not really unused.
2101 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2102 return;
2103
2104 // In C++, `_` variables behave as if they were maybe_unused
2105 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2106 return;
2107
2108 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2109
2110 if (Ty->isReferenceType() || Ty->isDependentType())
2111 return;
2112
2113 if (const TagType *TT = Ty->getAs<TagType>()) {
2114 const TagDecl *Tag = TT->getDecl();
2115 if (Tag->hasAttr<UnusedAttr>())
2116 return;
2117 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2118 // mimic gcc's behavior.
2119 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2120 RD && !RD->hasAttr<WarnUnusedAttr>())
2121 return;
2122 }
2123
2124 // Don't warn about __block Objective-C pointer variables, as they might
2125 // be assigned in the block but not used elsewhere for the purpose of lifetime
2126 // extension.
2127 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2128 return;
2129
2130 // Don't warn about Objective-C pointer variables with precise lifetime
2131 // semantics; they can be used to ensure ARC releases the object at a known
2132 // time, which may mean assignment but no other references.
2133 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2134 return;
2135
2136 auto iter = RefsMinusAssignments.find(VD);
2137 if (iter == RefsMinusAssignments.end())
2138 return;
2139
2140 assert(iter->getSecond() >= 0 &&
2141 "Found a negative number of references to a VarDecl");
2142 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2143 // Assume the given VarDecl is "used" if its ref count stored in
2144 // `RefMinusAssignments` is positive, with one exception.
2145 //
2146 // For a C++ variable whose decl (with initializer) entirely consist the
2147 // condition expression of a if/while/for construct,
2148 // Clang creates a DeclRefExpr for the condition expression rather than a
2149 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2150 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2151 // used in the body of the if/while/for construct.
2152 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2153 if (!UnusedCXXCondDecl)
2154 return;
2155 }
2156
2157 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2158 : diag::warn_unused_but_set_variable;
2159 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2160}
2161
2163 Sema::DiagReceiverTy DiagReceiver) {
2164 // Verify that we have no forward references left. If so, there was a goto
2165 // or address of a label taken, but no definition of it. Label fwd
2166 // definitions are indicated with a null substmt which is also not a resolved
2167 // MS inline assembly label name.
2168 bool Diagnose = false;
2169 if (L->isMSAsmLabel())
2170 Diagnose = !L->isResolvedMSAsmLabel();
2171 else
2172 Diagnose = L->getStmt() == nullptr;
2173 if (Diagnose)
2174 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2175 << L);
2176}
2177
2179 S->applyNRVO();
2180
2181 if (S->decl_empty()) return;
2182 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2183 "Scope shouldn't contain decls!");
2184
2185 /// We visit the decls in non-deterministic order, but we want diagnostics
2186 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2187 /// and sort the diagnostics before emitting them, after we visited all decls.
2188 struct LocAndDiag {
2190 std::optional<SourceLocation> PreviousDeclLoc;
2192 };
2194 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2195 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2196 };
2197 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2198 SourceLocation PreviousDeclLoc,
2199 PartialDiagnostic PD) {
2200 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2201 };
2202
2203 for (auto *TmpD : S->decls()) {
2204 assert(TmpD && "This decl didn't get pushed??");
2205
2206 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2207 NamedDecl *D = cast<NamedDecl>(TmpD);
2208
2209 // Diagnose unused variables in this scope.
2210 if (!S->hasUnrecoverableErrorOccurred()) {
2211 DiagnoseUnusedDecl(D, addDiag);
2212 if (const auto *RD = dyn_cast<RecordDecl>(D))
2213 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2214 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2215 DiagnoseUnusedButSetDecl(VD, addDiag);
2216 RefsMinusAssignments.erase(VD);
2217 }
2218 }
2219
2220 if (!D->getDeclName()) continue;
2221
2222 // If this was a forward reference to a label, verify it was defined.
2223 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2224 CheckPoppedLabel(LD, *this, addDiag);
2225
2226 // Partial translation units that are created in incremental processing must
2227 // not clean up the IdResolver because PTUs should take into account the
2228 // declarations that came from previous PTUs.
2232
2233 // Warn on it if we are shadowing a declaration.
2234 auto ShadowI = ShadowingDecls.find(D);
2235 if (ShadowI != ShadowingDecls.end()) {
2236 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2237 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2238 PDiag(diag::warn_ctor_parm_shadows_field)
2239 << D << FD << FD->getParent());
2240 }
2241 ShadowingDecls.erase(ShadowI);
2242 }
2243 }
2244
2245 llvm::sort(DeclDiags,
2246 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2247 // The particular order for diagnostics is not important, as long
2248 // as the order is deterministic. Using the raw location is going
2249 // to generally be in source order unless there are macro
2250 // expansions involved.
2251 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2252 });
2253 for (const LocAndDiag &D : DeclDiags) {
2254 Diag(D.Loc, D.PD);
2255 if (D.PreviousDeclLoc)
2256 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2257 }
2258}
2259
2261 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2262 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2263 (S->isClassScope() && !getLangOpts().CPlusPlus))
2264 S = S->getParent();
2265 return S;
2266}
2267
2268static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2270 switch (Error) {
2272 return "";
2274 return BuiltinInfo.getHeaderName(ID);
2276 return "stdio.h";
2278 return "setjmp.h";
2280 return "ucontext.h";
2281 }
2282 llvm_unreachable("unhandled error kind");
2283}
2284
2286 unsigned ID, SourceLocation Loc) {
2288
2289 if (getLangOpts().CPlusPlus) {
2292 CLinkageDecl->setImplicit();
2293 Parent->addDecl(CLinkageDecl);
2294 Parent = CLinkageDecl;
2295 }
2296
2299 assert(getLangOpts().CPlusPlus20 &&
2300 "consteval builtins should only be available in C++20 mode");
2301 ConstexprKind = ConstexprSpecKind::Consteval;
2302 }
2303
2305 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2306 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2307 Type->isFunctionProtoType(), ConstexprKind);
2308 New->setImplicit();
2309 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2310
2311 // Create Decl objects for each parameter, adding them to the
2312 // FunctionDecl.
2313 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2315 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2317 Context, New, SourceLocation(), SourceLocation(), nullptr,
2318 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2319 parm->setScopeInfo(0, i);
2320 Params.push_back(parm);
2321 }
2322 New->setParams(Params);
2323 }
2324
2326 return New;
2327}
2328
2330 Scope *S, bool ForRedeclaration,
2333
2335 QualType R = Context.GetBuiltinType(ID, Error);
2336 if (Error) {
2337 if (!ForRedeclaration)
2338 return nullptr;
2339
2340 // If we have a builtin without an associated type we should not emit a
2341 // warning when we were not able to find a type for it.
2342 if (Error == ASTContext::GE_Missing_type ||
2344 return nullptr;
2345
2346 // If we could not find a type for setjmp it is because the jmp_buf type was
2347 // not defined prior to the setjmp declaration.
2348 if (Error == ASTContext::GE_Missing_setjmp) {
2349 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2351 return nullptr;
2352 }
2353
2354 // Generally, we emit a warning that the declaration requires the
2355 // appropriate header.
2356 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2357 << getHeaderName(Context.BuiltinInfo, ID, Error)
2359 return nullptr;
2360 }
2361
2362 if (!ForRedeclaration &&
2365 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2366 : diag::ext_implicit_lib_function_decl)
2367 << Context.BuiltinInfo.getName(ID) << R;
2368 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2369 Diag(Loc, diag::note_include_header_or_declare)
2370 << Header << Context.BuiltinInfo.getName(ID);
2371 }
2372
2373 if (R.isNull())
2374 return nullptr;
2375
2376 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2378
2379 // TUScope is the translation-unit scope to insert this function into.
2380 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2381 // relate Scopes to DeclContexts, and probably eliminate CurContext
2382 // entirely, but we're not there yet.
2383 DeclContext *SavedContext = CurContext;
2384 CurContext = New->getDeclContext();
2386 CurContext = SavedContext;
2387 return New;
2388}
2389
2390/// Typedef declarations don't have linkage, but they still denote the same
2391/// entity if their types are the same.
2392/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2393/// isSameEntity.
2394static void
2397 // This is only interesting when modules are enabled.
2398 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2399 return;
2400
2401 // Empty sets are uninteresting.
2402 if (Previous.empty())
2403 return;
2404
2405 LookupResult::Filter Filter = Previous.makeFilter();
2406 while (Filter.hasNext()) {
2407 NamedDecl *Old = Filter.next();
2408
2409 // Non-hidden declarations are never ignored.
2410 if (S.isVisible(Old))
2411 continue;
2412
2413 // Declarations of the same entity are not ignored, even if they have
2414 // different linkages.
2415 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2416 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2417 Decl->getUnderlyingType()))
2418 continue;
2419
2420 // If both declarations give a tag declaration a typedef name for linkage
2421 // purposes, then they declare the same entity.
2422 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2423 Decl->getAnonDeclWithTypedefName())
2424 continue;
2425 }
2426
2427 Filter.erase();
2428 }
2429
2430 Filter.done();
2431}
2432
2434 QualType OldType;
2435 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2436 OldType = OldTypedef->getUnderlyingType();
2437 else
2438 OldType = Context.getTypeDeclType(Old);
2439 QualType NewType = New->getUnderlyingType();
2440
2441 if (NewType->isVariablyModifiedType()) {
2442 // Must not redefine a typedef with a variably-modified type.
2443 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2444 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2445 << Kind << NewType;
2446 if (Old->getLocation().isValid())
2448 New->setInvalidDecl();
2449 return true;
2450 }
2451
2452 if (OldType != NewType &&
2453 !OldType->isDependentType() &&
2454 !NewType->isDependentType() &&
2455 !Context.hasSameType(OldType, NewType)) {
2456 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2457 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2458 << Kind << NewType << OldType;
2459 if (Old->getLocation().isValid())
2461 New->setInvalidDecl();
2462 return true;
2463 }
2464 return false;
2465}
2466
2468 LookupResult &OldDecls) {
2469 // If the new decl is known invalid already, don't bother doing any
2470 // merging checks.
2471 if (New->isInvalidDecl()) return;
2472
2473 // Allow multiple definitions for ObjC built-in typedefs.
2474 // FIXME: Verify the underlying types are equivalent!
2475 if (getLangOpts().ObjC) {
2476 const IdentifierInfo *TypeID = New->getIdentifier();
2477 switch (TypeID->getLength()) {
2478 default: break;
2479 case 2:
2480 {
2481 if (!TypeID->isStr("id"))
2482 break;
2483 QualType T = New->getUnderlyingType();
2484 if (!T->isPointerType())
2485 break;
2486 if (!T->isVoidPointerType()) {
2488 if (!PT->isStructureType())
2489 break;
2490 }
2492 // Install the built-in type for 'id', ignoring the current definition.
2494 return;
2495 }
2496 case 5:
2497 if (!TypeID->isStr("Class"))
2498 break;
2500 // Install the built-in type for 'Class', ignoring the current definition.
2502 return;
2503 case 3:
2504 if (!TypeID->isStr("SEL"))
2505 break;
2507 // Install the built-in type for 'SEL', ignoring the current definition.
2509 return;
2510 }
2511 // Fall through - the typedef name was not a builtin type.
2512 }
2513
2514 // Verify the old decl was also a type.
2515 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2516 if (!Old) {
2517 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2518 << New->getDeclName();
2519
2520 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2521 if (OldD->getLocation().isValid())
2522 notePreviousDefinition(OldD, New->getLocation());
2523
2524 return New->setInvalidDecl();
2525 }
2526
2527 // If the old declaration is invalid, just give up here.
2528 if (Old->isInvalidDecl())
2529 return New->setInvalidDecl();
2530
2531 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2532 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2533 auto *NewTag = New->getAnonDeclWithTypedefName();
2534 NamedDecl *Hidden = nullptr;
2535 if (OldTag && NewTag &&
2536 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2537 !hasVisibleDefinition(OldTag, &Hidden)) {
2538 // There is a definition of this tag, but it is not visible. Use it
2539 // instead of our tag.
2540 New->setTypeForDecl(OldTD->getTypeForDecl());
2541 if (OldTD->isModed())
2542 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2543 OldTD->getUnderlyingType());
2544 else
2545 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2546
2547 // Make the old tag definition visible.
2549
2550 // If this was an unscoped enumeration, yank all of its enumerators
2551 // out of the scope.
2552 if (isa<EnumDecl>(NewTag)) {
2553 Scope *EnumScope = getNonFieldDeclScope(S);
2554 for (auto *D : NewTag->decls()) {
2555 auto *ED = cast<EnumConstantDecl>(D);
2556 assert(EnumScope->isDeclScope(ED));
2557 EnumScope->RemoveDecl(ED);
2559 ED->getLexicalDeclContext()->removeDecl(ED);
2560 }
2561 }
2562 }
2563 }
2564
2565 // If the typedef types are not identical, reject them in all languages and
2566 // with any extensions enabled.
2567 if (isIncompatibleTypedef(Old, New))
2568 return;
2569
2570 // The types match. Link up the redeclaration chain and merge attributes if
2571 // the old declaration was a typedef.
2572 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2573 New->setPreviousDecl(Typedef);
2574 mergeDeclAttributes(New, Old);
2575 }
2576
2577 if (getLangOpts().MicrosoftExt)
2578 return;
2579
2580 if (getLangOpts().CPlusPlus) {
2581 // C++ [dcl.typedef]p2:
2582 // In a given non-class scope, a typedef specifier can be used to
2583 // redefine the name of any type declared in that scope to refer
2584 // to the type to which it already refers.
2585 if (!isa<CXXRecordDecl>(CurContext))
2586 return;
2587
2588 // C++0x [dcl.typedef]p4:
2589 // In a given class scope, a typedef specifier can be used to redefine
2590 // any class-name declared in that scope that is not also a typedef-name
2591 // to refer to the type to which it already refers.
2592 //
2593 // This wording came in via DR424, which was a correction to the
2594 // wording in DR56, which accidentally banned code like:
2595 //
2596 // struct S {
2597 // typedef struct A { } A;
2598 // };
2599 //
2600 // in the C++03 standard. We implement the C++0x semantics, which
2601 // allow the above but disallow
2602 //
2603 // struct S {
2604 // typedef int I;
2605 // typedef int I;
2606 // };
2607 //
2608 // since that was the intent of DR56.
2609 if (!isa<TypedefNameDecl>(Old))
2610 return;
2611
2612 Diag(New->getLocation(), diag::err_redefinition)
2613 << New->getDeclName();
2615 return New->setInvalidDecl();
2616 }
2617
2618 // Modules always permit redefinition of typedefs, as does C11.
2619 if (getLangOpts().Modules || getLangOpts().C11)
2620 return;
2621
2622 // If we have a redefinition of a typedef in C, emit a warning. This warning
2623 // is normally mapped to an error, but can be controlled with
2624 // -Wtypedef-redefinition. If either the original or the redefinition is
2625 // in a system header, don't emit this for compatibility with GCC.
2626 if (getDiagnostics().getSuppressSystemWarnings() &&
2627 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2628 (Old->isImplicit() ||
2631 return;
2632
2633 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2634 << New->getDeclName();
2636}
2637
2638/// DeclhasAttr - returns true if decl Declaration already has the target
2639/// attribute.
2640static bool DeclHasAttr(const Decl *D, const Attr *A) {
2641 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2642 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2643 for (const auto *i : D->attrs())
2644 if (i->getKind() == A->getKind()) {
2645 if (Ann) {
2646 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2647 return true;
2648 continue;
2649 }
2650 // FIXME: Don't hardcode this check
2651 if (OA && isa<OwnershipAttr>(i))
2652 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2653 return true;
2654 }
2655
2656 return false;
2657}
2658
2660 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2661 return VD->isThisDeclarationADefinition();
2662 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2663 return TD->isCompleteDefinition() || TD->isBeingDefined();
2664 return true;
2665}
2666
2667/// Merge alignment attributes from \p Old to \p New, taking into account the
2668/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2669///
2670/// \return \c true if any attributes were added to \p New.
2671static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2672 // Look for alignas attributes on Old, and pick out whichever attribute
2673 // specifies the strictest alignment requirement.
2674 AlignedAttr *OldAlignasAttr = nullptr;
2675 AlignedAttr *OldStrictestAlignAttr = nullptr;
2676 unsigned OldAlign = 0;
2677 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2678 // FIXME: We have no way of representing inherited dependent alignments
2679 // in a case like:
2680 // template<int A, int B> struct alignas(A) X;
2681 // template<int A, int B> struct alignas(B) X {};
2682 // For now, we just ignore any alignas attributes which are not on the
2683 // definition in such a case.
2684 if (I->isAlignmentDependent())
2685 return false;
2686
2687 if (I->isAlignas())
2688 OldAlignasAttr = I;
2689
2690 unsigned Align = I->getAlignment(S.Context);
2691 if (Align > OldAlign) {
2692 OldAlign = Align;
2693 OldStrictestAlignAttr = I;
2694 }
2695 }
2696
2697 // Look for alignas attributes on New.
2698 AlignedAttr *NewAlignasAttr = nullptr;
2699 unsigned NewAlign = 0;
2700 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2701 if (I->isAlignmentDependent())
2702 return false;
2703
2704 if (I->isAlignas())
2705 NewAlignasAttr = I;
2706
2707 unsigned Align = I->getAlignment(S.Context);
2708 if (Align > NewAlign)
2709 NewAlign = Align;
2710 }
2711
2712 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2713 // Both declarations have 'alignas' attributes. We require them to match.
2714 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2715 // fall short. (If two declarations both have alignas, they must both match
2716 // every definition, and so must match each other if there is a definition.)
2717
2718 // If either declaration only contains 'alignas(0)' specifiers, then it
2719 // specifies the natural alignment for the type.
2720 if (OldAlign == 0 || NewAlign == 0) {
2721 QualType Ty;
2722 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2723 Ty = VD->getType();
2724 else
2725 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2726
2727 if (OldAlign == 0)
2728 OldAlign = S.Context.getTypeAlign(Ty);
2729 if (NewAlign == 0)
2730 NewAlign = S.Context.getTypeAlign(Ty);
2731 }
2732
2733 if (OldAlign != NewAlign) {
2734 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2737 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2738 }
2739 }
2740
2741 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2742 // C++11 [dcl.align]p6:
2743 // if any declaration of an entity has an alignment-specifier,
2744 // every defining declaration of that entity shall specify an
2745 // equivalent alignment.
2746 // C11 6.7.5/7:
2747 // If the definition of an object does not have an alignment
2748 // specifier, any other declaration of that object shall also
2749 // have no alignment specifier.
2750 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2751 << OldAlignasAttr;
2752 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2753 << OldAlignasAttr;
2754 }
2755
2756 bool AnyAdded = false;
2757
2758 // Ensure we have an attribute representing the strictest alignment.
2759 if (OldAlign > NewAlign) {
2760 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2761 Clone->setInherited(true);
2762 New->addAttr(Clone);
2763 AnyAdded = true;
2764 }
2765
2766 // Ensure we have an alignas attribute if the old declaration had one.
2767 if (OldAlignasAttr && !NewAlignasAttr &&
2768 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2769 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2770 Clone->setInherited(true);
2771 New->addAttr(Clone);
2772 AnyAdded = true;
2773 }
2774
2775 return AnyAdded;
2776}
2777
2778#define WANT_DECL_MERGE_LOGIC
2779#include "clang/Sema/AttrParsedAttrImpl.inc"
2780#undef WANT_DECL_MERGE_LOGIC
2781
2783 const InheritableAttr *Attr,
2785 // Diagnose any mutual exclusions between the attribute that we want to add
2786 // and attributes that already exist on the declaration.
2787 if (!DiagnoseMutualExclusions(S, D, Attr))
2788 return false;
2789
2790 // This function copies an attribute Attr from a previous declaration to the
2791 // new declaration D if the new declaration doesn't itself have that attribute
2792 // yet or if that attribute allows duplicates.
2793 // If you're adding a new attribute that requires logic different from
2794 // "use explicit attribute on decl if present, else use attribute from
2795 // previous decl", for example if the attribute needs to be consistent
2796 // between redeclarations, you need to call a custom merge function here.
2797 InheritableAttr *NewAttr = nullptr;
2798 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2799 NewAttr = S.mergeAvailabilityAttr(
2800 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2801 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2802 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2803 AA->getPriority(), AA->getEnvironment());
2804 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2805 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2806 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2807 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2808 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2809 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2810 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2811 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2812 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2813 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2814 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2815 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2816 FA->getFirstArg());
2817 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2818 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2819 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2820 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2821 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2822 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2823 IA->getInheritanceModel());
2824 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2825 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2826 &S.Context.Idents.get(AA->getSpelling()));
2827 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2828 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2829 isa<CUDAGlobalAttr>(Attr))) {
2830 // CUDA target attributes are part of function signature for
2831 // overloading purposes and must not be merged.
2832 return false;
2833 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2834 NewAttr = S.mergeMinSizeAttr(D, *MA);
2835 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2836 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2837 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2838 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2839 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2840 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2841 else if (isa<AlignedAttr>(Attr))
2842 // AlignedAttrs are handled separately, because we need to handle all
2843 // such attributes on a declaration at the same time.
2844 NewAttr = nullptr;
2845 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2846 (AMK == Sema::AMK_Override ||
2849 NewAttr = nullptr;
2850 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2851 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2852 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2853 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2854 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2855 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2856 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2857 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2858 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2859 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2860 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2861 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2862 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2863 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2864 NT->getZ());
2865 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2866 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2867 else if (isa<SuppressAttr>(Attr))
2868 // Do nothing. Each redeclaration should be suppressed separately.
2869 NewAttr = nullptr;
2870 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2871 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2872
2873 if (NewAttr) {
2874 NewAttr->setInherited(true);
2875 D->addAttr(NewAttr);
2876 if (isa<MSInheritanceAttr>(NewAttr))
2877 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2878 return true;
2879 }
2880
2881 return false;
2882}
2883
2884static const NamedDecl *getDefinition(const Decl *D) {
2885 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2886 return TD->getDefinition();
2887 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2888 const VarDecl *Def = VD->getDefinition();
2889 if (Def)
2890 return Def;
2891 return VD->getActingDefinition();
2892 }
2893 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2894 const FunctionDecl *Def = nullptr;
2895 if (FD->isDefined(Def, true))
2896 return Def;
2897 }
2898 return nullptr;
2899}
2900
2901static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2902 for (const auto *Attribute : D->attrs())
2903 if (Attribute->getKind() == Kind)
2904 return true;
2905 return false;
2906}
2907
2908/// checkNewAttributesAfterDef - If we already have a definition, check that
2909/// there are no new attributes in this declaration.
2910static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2911 if (!New->hasAttrs())
2912 return;
2913
2914 const NamedDecl *Def = getDefinition(Old);
2915 if (!Def || Def == New)
2916 return;
2917
2918 AttrVec &NewAttributes = New->getAttrs();
2919 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2920 const Attr *NewAttribute = NewAttributes[I];
2921
2922 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2923 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2924 SkipBodyInfo SkipBody;
2925 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2926
2927 // If we're skipping this definition, drop the "alias" attribute.
2928 if (SkipBody.ShouldSkip) {
2929 NewAttributes.erase(NewAttributes.begin() + I);
2930 --E;
2931 continue;
2932 }
2933 } else {
2934 VarDecl *VD = cast<VarDecl>(New);
2935 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2937 ? diag::err_alias_after_tentative
2938 : diag::err_redefinition;
2939 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2940 if (Diag == diag::err_redefinition)
2941 S.notePreviousDefinition(Def, VD->getLocation());
2942 else
2943 S.Diag(Def->getLocation(), diag::note_previous_definition);
2944 VD->setInvalidDecl();
2945 }
2946 ++I;
2947 continue;
2948 }
2949
2950 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2951 // Tentative definitions are only interesting for the alias check above.
2952 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2953 ++I;
2954 continue;
2955 }
2956 }
2957
2958 if (hasAttribute(Def, NewAttribute->getKind())) {
2959 ++I;
2960 continue; // regular attr merging will take care of validating this.
2961 }
2962
2963 if (isa<C11NoReturnAttr>(NewAttribute)) {
2964 // C's _Noreturn is allowed to be added to a function after it is defined.
2965 ++I;
2966 continue;
2967 } else if (isa<UuidAttr>(NewAttribute)) {
2968 // msvc will allow a subsequent definition to add an uuid to a class
2969 ++I;
2970 continue;
2971 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2972 if (AA->isAlignas()) {
2973 // C++11 [dcl.align]p6:
2974 // if any declaration of an entity has an alignment-specifier,
2975 // every defining declaration of that entity shall specify an
2976 // equivalent alignment.
2977 // C11 6.7.5/7:
2978 // If the definition of an object does not have an alignment
2979 // specifier, any other declaration of that object shall also
2980 // have no alignment specifier.
2981 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2982 << AA;
2983 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2984 << AA;
2985 NewAttributes.erase(NewAttributes.begin() + I);
2986 --E;
2987 continue;
2988 }
2989 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2990 // If there is a C definition followed by a redeclaration with this
2991 // attribute then there are two different definitions. In C++, prefer the
2992 // standard diagnostics.
2993 if (!S.getLangOpts().CPlusPlus) {
2994 S.Diag(NewAttribute->getLocation(),
2995 diag::err_loader_uninitialized_redeclaration);
2996 S.Diag(Def->getLocation(), diag::note_previous_definition);
2997 NewAttributes.erase(NewAttributes.begin() + I);
2998 --E;
2999 continue;
3000 }
3001 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3002 cast<VarDecl>(New)->isInline() &&
3003 !cast<VarDecl>(New)->isInlineSpecified()) {
3004 // Don't warn about applying selectany to implicitly inline variables.
3005 // Older compilers and language modes would require the use of selectany
3006 // to make such variables inline, and it would have no effect if we
3007 // honored it.
3008 ++I;
3009 continue;
3010 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3011 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3012 // declarations after definitions.
3013 ++I;
3014 continue;
3015 }
3016
3017 S.Diag(NewAttribute->getLocation(),
3018 diag::warn_attribute_precede_definition);
3019 S.Diag(Def->getLocation(), diag::note_previous_definition);
3020 NewAttributes.erase(NewAttributes.begin() + I);
3021 --E;
3022 }
3023}
3024
3025static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3026 const ConstInitAttr *CIAttr,
3027 bool AttrBeforeInit) {
3028 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3029
3030 // Figure out a good way to write this specifier on the old declaration.
3031 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3032 // enough of the attribute list spelling information to extract that without
3033 // heroics.
3034 std::string SuitableSpelling;
3035 if (S.getLangOpts().CPlusPlus20)
3036 SuitableSpelling = std::string(
3037 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3038 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3039 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3040 InsertLoc, {tok::l_square, tok::l_square,
3041 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3042 S.PP.getIdentifierInfo("require_constant_initialization"),
3043 tok::r_square, tok::r_square}));
3044 if (SuitableSpelling.empty())
3045 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3046 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3047 S.PP.getIdentifierInfo("require_constant_initialization"),
3048 tok::r_paren, tok::r_paren}));
3049 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3050 SuitableSpelling = "constinit";
3051 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3052 SuitableSpelling = "[[clang::require_constant_initialization]]";
3053 if (SuitableSpelling.empty())
3054 SuitableSpelling = "__attribute__((require_constant_initialization))";
3055 SuitableSpelling += " ";
3056
3057 if (AttrBeforeInit) {
3058 // extern constinit int a;
3059 // int a = 0; // error (missing 'constinit'), accepted as extension
3060 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3061 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3062 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3063 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3064 } else {
3065 // int a = 0;
3066 // constinit extern int a; // error (missing 'constinit')
3067 S.Diag(CIAttr->getLocation(),
3068 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3069 : diag::warn_require_const_init_added_too_late)
3070 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3071 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3072 << CIAttr->isConstinit()
3073 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3074 }
3075}
3076
3079 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3080 UsedAttr *NewAttr = OldAttr->clone(Context);
3081 NewAttr->setInherited(true);
3082 New->addAttr(NewAttr);
3083 }
3084 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3085 RetainAttr *NewAttr = OldAttr->clone(Context);
3086 NewAttr->setInherited(true);
3087 New->addAttr(NewAttr);
3088 }
3089
3090 if (!Old->hasAttrs() && !New->hasAttrs())
3091 return;
3092
3093 // [dcl.constinit]p1:
3094 // If the [constinit] specifier is applied to any declaration of a
3095 // variable, it shall be applied to the initializing declaration.
3096 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3097 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3098 if (bool(OldConstInit) != bool(NewConstInit)) {
3099 const auto *OldVD = cast<VarDecl>(Old);
3100 auto *NewVD = cast<VarDecl>(New);
3101
3102 // Find the initializing declaration. Note that we might not have linked
3103 // the new declaration into the redeclaration chain yet.
3104 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3105 if (!InitDecl &&
3106 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3107 InitDecl = NewVD;
3108
3109 if (InitDecl == NewVD) {
3110 // This is the initializing declaration. If it would inherit 'constinit',
3111 // that's ill-formed. (Note that we do not apply this to the attribute
3112 // form).
3113 if (OldConstInit && OldConstInit->isConstinit())
3114 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3115 /*AttrBeforeInit=*/true);
3116 } else if (NewConstInit) {
3117 // This is the first time we've been told that this declaration should
3118 // have a constant initializer. If we already saw the initializing
3119 // declaration, this is too late.
3120 if (InitDecl && InitDecl != NewVD) {
3121 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3122 /*AttrBeforeInit=*/false);
3123 NewVD->dropAttr<ConstInitAttr>();
3124 }
3125 }
3126 }
3127
3128 // Attributes declared post-definition are currently ignored.
3129 checkNewAttributesAfterDef(*this, New, Old);
3130
3131 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3132 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3133 if (!OldA->isEquivalent(NewA)) {
3134 // This redeclaration changes __asm__ label.
3135 Diag(New->getLocation(), diag::err_different_asm_label);
3136 Diag(OldA->getLocation(), diag::note_previous_declaration);
3137 }
3138 } else if (Old->isUsed()) {
3139 // This redeclaration adds an __asm__ label to a declaration that has
3140 // already been ODR-used.
3141 Diag(New->getLocation(), diag::err_late_asm_label_name)
3142 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3143 }
3144 }
3145
3146 // Re-declaration cannot add abi_tag's.
3147 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3148 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3149 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3150 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3151 Diag(NewAbiTagAttr->getLocation(),
3152 diag::err_new_abi_tag_on_redeclaration)
3153 << NewTag;
3154 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3155 }
3156 }
3157 } else {
3158 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3159 Diag(Old->getLocation(), diag::note_previous_declaration);
3160 }
3161 }
3162
3163 // This redeclaration adds a section attribute.
3164 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3165 if (auto *VD = dyn_cast<VarDecl>(New)) {
3166 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3167 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3168 Diag(Old->getLocation(), diag::note_previous_declaration);
3169 }
3170 }
3171 }
3172
3173 // Redeclaration adds code-seg attribute.
3174 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3175 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3176 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3177 Diag(New->getLocation(), diag::warn_mismatched_section)
3178 << 0 /*codeseg*/;
3179 Diag(Old->getLocation(), diag::note_previous_declaration);
3180 }
3181
3182 if (!Old->hasAttrs())
3183 return;
3184
3185 bool foundAny = New->hasAttrs();
3186
3187 // Ensure that any moving of objects within the allocated map is done before
3188 // we process them.
3189 if (!foundAny) New->setAttrs(AttrVec());
3190
3191 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3192 // Ignore deprecated/unavailable/availability attributes if requested.
3194 if (isa<DeprecatedAttr>(I) ||
3195 isa<UnavailableAttr>(I) ||
3196 isa<AvailabilityAttr>(I)) {
3197 switch (AMK) {
3198 case AMK_None:
3199 continue;
3200
3201 case AMK_Redeclaration:
3202 case AMK_Override:
3205 LocalAMK = AMK;
3206 break;
3207 }
3208 }
3209
3210 // Already handled.
3211 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3212 continue;
3213
3214 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3215 foundAny = true;
3216 }
3217
3218 if (mergeAlignedAttrs(*this, New, Old))
3219 foundAny = true;
3220
3221 if (!foundAny) New->dropAttrs();
3222}
3223
3224/// mergeParamDeclAttributes - Copy attributes from the old parameter
3225/// to the new one.
3227 const ParmVarDecl *oldDecl,
3228 Sema &S) {
3229 // C++11 [dcl.attr.depend]p2:
3230 // The first declaration of a function shall specify the
3231 // carries_dependency attribute for its declarator-id if any declaration
3232 // of the function specifies the carries_dependency attribute.
3233 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3234 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3235 S.Diag(CDA->getLocation(),
3236 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3237 // Find the first declaration of the parameter.
3238 // FIXME: Should we build redeclaration chains for function parameters?
3239 const FunctionDecl *FirstFD =
3240 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3241 const ParmVarDecl *FirstVD =
3242 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3243 S.Diag(FirstVD->getLocation(),
3244 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3245 }
3246
3247 // HLSL parameter declarations for inout and out must match between
3248 // declarations. In HLSL inout and out are ambiguous at the call site, but
3249 // have different calling behavior, so you cannot overload a method based on a
3250 // difference between inout and out annotations.
3251 if (S.getLangOpts().HLSL) {
3252 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>();
3253 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>();
3254 // We don't need to cover the case where one declaration doesn't have an
3255 // attribute. The only possible case there is if one declaration has an `in`
3256 // attribute and the other declaration has no attribute. This case is
3257 // allowed since parameters are `in` by default.
3258 if (NDAttr && ODAttr &&
3259 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) {
3260 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch)
3261 << NDAttr << newDecl;
3262 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as)
3263 << ODAttr;
3264 }
3265 }
3266
3267 if (!oldDecl->hasAttrs())
3268 return;
3269
3270 bool foundAny = newDecl->hasAttrs();
3271
3272 // Ensure that any moving of objects within the allocated map is
3273 // done before we process them.
3274 if (!foundAny) newDecl->setAttrs(AttrVec());
3275
3276 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3277 if (!DeclHasAttr(newDecl, I)) {
3278 InheritableAttr *newAttr =
3279 cast<InheritableParamAttr>(I->clone(S.Context));
3280 newAttr->setInherited(true);
3281 newDecl->addAttr(newAttr);
3282 foundAny = true;
3283 }
3284 }
3285
3286 if (!foundAny) newDecl->dropAttrs();
3287}
3288
3290 const ASTContext &Ctx) {
3291
3292 auto NoSizeInfo = [&Ctx](QualType Ty) {
3293 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3294 return true;
3295 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3296 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3297 return false;
3298 };
3299
3300 // `type[]` is equivalent to `type *` and `type[*]`.
3301 if (NoSizeInfo(Old) && NoSizeInfo(New))
3302 return true;
3303
3304 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3305 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3306 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3307 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3308 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3309 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3310 return false;
3311 return true;
3312 }
3313
3314 // Only compare size, ignore Size modifiers and CVR.
3315 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3316 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3317 Ctx.getAsConstantArrayType(New)->getSize();
3318 }
3319
3320 // Don't try to compare dependent sized array
3322 return true;
3323 }
3324
3325 return Old == New;
3326}
3327
3328static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3329 const ParmVarDecl *OldParam,
3330 Sema &S) {
3331 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3332 if (auto Newnullability = NewParam->getType()->getNullability()) {
3333 if (*Oldnullability != *Newnullability) {
3334 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3336 *Newnullability,
3338 != 0))
3340 *Oldnullability,
3342 != 0));
3343 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3344 }
3345 } else {
3346 QualType NewT = NewParam->getType();
3347 NewT = S.Context.getAttributedType(
3349 NewT, NewT);
3350 NewParam->setType(NewT);
3351 }
3352 }
3353 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3354 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3355 if (OldParamDT && NewParamDT &&
3356 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3357 QualType OldParamOT = OldParamDT->getOriginalType();
3358 QualType NewParamOT = NewParamDT->getOriginalType();
3359 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3360 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3361 << NewParam << NewParamOT;
3362 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3363 << OldParamOT;
3364 }
3365 }
3366}
3367
3368namespace {
3369
3370/// Used in MergeFunctionDecl to keep track of function parameters in
3371/// C.
3372struct GNUCompatibleParamWarning {
3373 ParmVarDecl *OldParm;
3374 ParmVarDecl *NewParm;
3375 QualType PromotedType;
3376};
3377
3378} // end anonymous namespace
3379
3380// Determine whether the previous declaration was a definition, implicit
3381// declaration, or a declaration.
3382template <typename T>
3383static std::pair<diag::kind, SourceLocation>
3384getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3385 diag::kind PrevDiag;
3386 SourceLocation OldLocation = Old->getLocation();
3387 if (Old->isThisDeclarationADefinition())
3388 PrevDiag = diag::note_previous_definition;
3389 else if (Old->isImplicit()) {
3390 PrevDiag = diag::note_previous_implicit_declaration;
3391 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3392 if (FD->getBuiltinID())
3393 PrevDiag = diag::note_previous_builtin_declaration;
3394 }
3395 if (OldLocation.isInvalid())
3396 OldLocation = New->getLocation();
3397 } else
3398 PrevDiag = diag::note_previous_declaration;
3399 return std::make_pair(PrevDiag, OldLocation);
3400}
3401
3402/// canRedefineFunction - checks if a function can be redefined. Currently,
3403/// only extern inline functions can be redefined, and even then only in
3404/// GNU89 mode.
3405static bool canRedefineFunction(const FunctionDecl *FD,
3406 const LangOptions& LangOpts) {
3407 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3408 !LangOpts.CPlusPlus &&
3409 FD->isInlineSpecified() &&
3410 FD->getStorageClass() == SC_Extern);
3411}
3412
3414 const AttributedType *AT = T->getAs<AttributedType>();
3415 while (AT && !AT->isCallingConv())
3416 AT = AT->getModifiedType()->getAs<AttributedType>();
3417 return AT;
3418}
3419
3420template <typename T>
3421static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3422 const DeclContext *DC = Old->getDeclContext();
3423 if (DC->isRecord())
3424 return false;
3425
3426 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3427 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3428 return true;
3429 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3430 return true;
3431 return false;
3432}
3433
3434template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3435static bool isExternC(VarTemplateDecl *) { return false; }
3436static bool isExternC(FunctionTemplateDecl *) { return false; }
3437
3438/// Check whether a redeclaration of an entity introduced by a
3439/// using-declaration is valid, given that we know it's not an overload
3440/// (nor a hidden tag declaration).
3441template<typename ExpectedDecl>
3443 ExpectedDecl *New) {
3444 // C++11 [basic.scope.declarative]p4:
3445 // Given a set of declarations in a single declarative region, each of
3446 // which specifies the same unqualified name,
3447 // -- they shall all refer to the same entity, or all refer to functions
3448 // and function templates; or
3449 // -- exactly one declaration shall declare a class name or enumeration
3450 // name that is not a typedef name and the other declarations shall all
3451 // refer to the same variable or enumerator, or all refer to functions
3452 // and function templates; in this case the class name or enumeration
3453 // name is hidden (3.3.10).
3454
3455 // C++11 [namespace.udecl]p14:
3456 // If a function declaration in namespace scope or block scope has the
3457 // same name and the same parameter-type-list as a function introduced
3458 // by a using-declaration, and the declarations do not declare the same
3459 // function, the program is ill-formed.
3460
3461 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3462 if (Old &&
3463 !Old->getDeclContext()->getRedeclContext()->Equals(
3464 New->getDeclContext()->getRedeclContext()) &&
3465 !(isExternC(Old) && isExternC(New)))
3466 Old = nullptr;
3467
3468 if (!Old) {
3469 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3470 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3471 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3472 return true;
3473 }
3474 return false;
3475}
3476
3478 const FunctionDecl *B) {
3479 assert(A->getNumParams() == B->getNumParams());
3480
3481 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3482 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3483 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3484 if (AttrA == AttrB)
3485 return true;
3486 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3487 AttrA->isDynamic() == AttrB->isDynamic();
3488 };
3489
3490 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3491}
3492
3493/// If necessary, adjust the semantic declaration context for a qualified
3494/// declaration to name the correct inline namespace within the qualifier.
3496 DeclaratorDecl *OldD) {
3497 // The only case where we need to update the DeclContext is when
3498 // redeclaration lookup for a qualified name finds a declaration
3499 // in an inline namespace within the context named by the qualifier:
3500 //
3501 // inline namespace N { int f(); }
3502 // int ::f(); // Sema DC needs adjusting from :: to N::.
3503 //
3504 // For unqualified declarations, the semantic context *can* change
3505 // along the redeclaration chain (for local extern declarations,
3506 // extern "C" declarations, and friend declarations in particular).
3507 if (!NewD->getQualifier())
3508 return;
3509
3510 // NewD is probably already in the right context.
3511 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3512 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3513 if (NamedDC->Equals(SemaDC))
3514 return;
3515
3516 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3517 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3518 "unexpected context for redeclaration");
3519
3520 auto *LexDC = NewD->getLexicalDeclContext();
3521 auto FixSemaDC = [=](NamedDecl *D) {
3522 if (!D)
3523 return;
3524 D->setDeclContext(SemaDC);
3525 D->setLexicalDeclContext(LexDC);
3526 };
3527
3528 FixSemaDC(NewD);
3529 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3530 FixSemaDC(FD->getDescribedFunctionTemplate());
3531 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3532 FixSemaDC(VD->getDescribedVarTemplate());
3533}
3534
3536 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3537 // Verify the old decl was also a function.
3538 FunctionDecl *Old = OldD->getAsFunction();
3539 if (!Old) {
3540 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3541 if (New->getFriendObjectKind()) {
3542 Diag(New->getLocation(), diag::err_using_decl_friend);
3543 Diag(Shadow->getTargetDecl()->getLocation(),
3544 diag::note_using_decl_target);
3545 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3546 << 0;
3547 return true;
3548 }
3549
3550 // Check whether the two declarations might declare the same function or
3551 // function template.
3552 if (FunctionTemplateDecl *NewTemplate =
3554 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3555 NewTemplate))
3556 return true;
3557 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3558 ->getAsFunction();
3559 } else {
3560 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3561 return true;
3562 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3563 }
3564 } else {
3565 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3566 << New->getDeclName();
3567 notePreviousDefinition(OldD, New->getLocation());
3568 return true;
3569 }
3570 }
3571
3572 // If the old declaration was found in an inline namespace and the new
3573 // declaration was qualified, update the DeclContext to match.
3575
3576 // If the old declaration is invalid, just give up here.
3577 if (Old->isInvalidDecl())
3578 return true;
3579
3580 // Disallow redeclaration of some builtins.
3581 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3582 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3583 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3584 << Old << Old->getType();
3585 return true;
3586 }
3587
3588 diag::kind PrevDiag;
3589 SourceLocation OldLocation;
3590 std::tie(PrevDiag, OldLocation) =
3592
3593 // Don't complain about this if we're in GNU89 mode and the old function
3594 // is an extern inline function.
3595 // Don't complain about specializations. They are not supposed to have
3596 // storage classes.
3597 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3598 New->getStorageClass() == SC_Static &&
3599 Old->hasExternalFormalLinkage() &&
3602 if (getLangOpts().MicrosoftExt) {
3603 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3604 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3605 } else {
3606 Diag(New->getLocation(), diag::err_static_non_static) << New;
3607 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3608 return true;
3609 }
3610 }
3611
3612 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3613 if (!Old->hasAttr<InternalLinkageAttr>()) {
3614 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3615 << ILA;
3616 Diag(Old->getLocation(), diag::note_previous_declaration);
3617 New->dropAttr<InternalLinkageAttr>();
3618 }
3619
3620 if (auto *EA = New->getAttr<ErrorAttr>()) {
3621 if (!Old->hasAttr<ErrorAttr>()) {
3622 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3623 Diag(Old->getLocation(), diag::note_previous_declaration);
3624 New->dropAttr<ErrorAttr>();
3625 }
3626 }
3627
3628 if (CheckRedeclarationInModule(New, Old))
3629 return true;
3630
3631 if (!getLangOpts().CPlusPlus) {
3632 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3633 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3634 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3635 << New << OldOvl;
3636
3637 // Try our best to find a decl that actually has the overloadable
3638 // attribute for the note. In most cases (e.g. programs with only one
3639 // broken declaration/definition), this won't matter.
3640 //
3641 // FIXME: We could do this if we juggled some extra state in
3642 // OverloadableAttr, rather than just removing it.
3643 const Decl *DiagOld = Old;
3644 if (OldOvl) {
3645 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3646 const auto *A = D->getAttr<OverloadableAttr>();
3647 return A && !A->isImplicit();
3648 });
3649 // If we've implicitly added *all* of the overloadable attrs to this
3650 // chain, emitting a "previous redecl" note is pointless.
3651 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3652 }
3653
3654 if (DiagOld)
3655 Diag(DiagOld->getLocation(),
3656 diag::note_attribute_overloadable_prev_overload)
3657 << OldOvl;
3658
3659 if (OldOvl)
3660 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3661 else
3662 New->dropAttr<OverloadableAttr>();
3663 }
3664 }
3665
3666 // It is not permitted to redeclare an SME function with different SME
3667 // attributes.
3668 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3669 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3670 << New->getType() << Old->getType();
3671 Diag(OldLocation, diag::note_previous_declaration);
3672 return true;
3673 }
3674
3675 // If a function is first declared with a calling convention, but is later
3676 // declared or defined without one, all following decls assume the calling
3677 // convention of the first.
3678 //
3679 // It's OK if a function is first declared without a calling convention,
3680 // but is later declared or defined with the default calling convention.
3681 //
3682 // To test if either decl has an explicit calling convention, we look for
3683 // AttributedType sugar nodes on the type as written. If they are missing or
3684 // were canonicalized away, we assume the calling convention was implicit.
3685 //
3686 // Note also that we DO NOT return at this point, because we still have
3687 // other tests to run.
3688 QualType OldQType = Context.getCanonicalType(Old->getType());
3689 QualType NewQType = Context.getCanonicalType(New->getType());
3690 const FunctionType *OldType = cast<FunctionType>(OldQType);
3691 const FunctionType *NewType = cast<FunctionType>(NewQType);
3692 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3693 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3694 bool RequiresAdjustment = false;
3695
3696 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3698 const FunctionType *FT =
3699 First->getType().getCanonicalType()->castAs<FunctionType>();
3701 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3702 if (!NewCCExplicit) {
3703 // Inherit the CC from the previous declaration if it was specified
3704 // there but not here.
3705 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3706 RequiresAdjustment = true;
3707 } else if (Old->getBuiltinID()) {
3708 // Builtin attribute isn't propagated to the new one yet at this point,
3709 // so we check if the old one is a builtin.
3710
3711 // Calling Conventions on a Builtin aren't really useful and setting a
3712 // default calling convention and cdecl'ing some builtin redeclarations is
3713 // common, so warn and ignore the calling convention on the redeclaration.
3714 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3715 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3717 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3718 RequiresAdjustment = true;
3719 } else {
3720 // Calling conventions aren't compatible, so complain.
3721 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3722 Diag(New->getLocation(), diag::err_cconv_change)
3723 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3724 << !FirstCCExplicit
3725 << (!FirstCCExplicit ? "" :
3727
3728 // Put the note on the first decl, since it is the one that matters.
3729 Diag(First->getLocation(), diag::note_previous_declaration);
3730 return true;
3731 }
3732 }
3733
3734 // FIXME: diagnose the other way around?
3735 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3736 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3737 RequiresAdjustment = true;
3738 }
3739
3740 // Merge regparm attribute.
3741 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3742 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3743 if (NewTypeInfo.getHasRegParm()) {
3744 Diag(New->getLocation(), diag::err_regparm_mismatch)
3745 << NewType->getRegParmType()
3746 << OldType->getRegParmType();
3747 Diag(OldLocation, diag::note_previous_declaration);
3748 return true;
3749 }
3750
3751 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3752 RequiresAdjustment = true;
3753 }
3754
3755 // Merge ns_returns_retained attribute.
3756 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3757 if (NewTypeInfo.getProducesResult()) {
3758 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3759 << "'ns_returns_retained'";
3760 Diag(OldLocation, diag::note_previous_declaration);
3761 return true;
3762 }
3763
3764 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3765 RequiresAdjustment = true;
3766 }
3767
3768 if (OldTypeInfo.getNoCallerSavedRegs() !=
3769 NewTypeInfo.getNoCallerSavedRegs()) {
3770 if (NewTypeInfo.getNoCallerSavedRegs()) {
3771 AnyX86NoCallerSavedRegistersAttr *Attr =
3772 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3773 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3774 Diag(OldLocation, diag::note_previous_declaration);
3775 return true;
3776 }
3777
3778 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3779 RequiresAdjustment = true;
3780 }
3781
3782 if (RequiresAdjustment) {
3785 New->setType(QualType(AdjustedType, 0));
3786 NewQType = Context.getCanonicalType(New->getType());
3787 }
3788
3789 // If this redeclaration makes the function inline, we may need to add it to
3790 // UndefinedButUsed.
3791 if (!Old->isInlined() && New->isInlined() &&
3792 !New->hasAttr<GNUInlineAttr>() &&
3793 !getLangOpts().GNUInline &&
3794 Old->isUsed(false) &&
3795 !Old->isDefined() && !New->isThisDeclarationADefinition())
3796 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3797 SourceLocation()));
3798
3799 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3800 // about it.
3801 if (New->hasAttr<GNUInlineAttr>() &&
3802 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3803 UndefinedButUsed.erase(Old->getCanonicalDecl());
3804 }
3805
3806 // If pass_object_size params don't match up perfectly, this isn't a valid
3807 // redeclaration.
3808 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3810 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3811 << New->getDeclName();
3812 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3813 return true;
3814 }
3815
3816 QualType OldQTypeForComparison = OldQType;
3818 const auto OldFX = Old->getFunctionEffects();
3819 const auto NewFX = New->getFunctionEffects();
3820 if (OldFX != NewFX) {
3821 const auto Diffs = FunctionEffectDifferences(OldFX, NewFX);
3822 for (const auto &Diff : Diffs) {
3823 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
3824 Diag(New->getLocation(),
3825 diag::warn_mismatched_func_effect_redeclaration)
3826 << Diff.effectName();
3827 Diag(Old->getLocation(), diag::note_previous_declaration);
3828 }
3829 }
3830 // Following a warning, we could skip merging effects from the previous
3831 // declaration, but that would trigger an additional "conflicting types"
3832 // error.
3833 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
3835 FunctionEffectSet MergedFX =
3836 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
3837 if (!MergeErrs.empty())
3839 Old->getLocation());
3840
3841 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
3842 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3843 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
3844 NewFPT->getParamTypes(), EPI);
3845
3846 New->setType(ModQT);
3847 NewQType = New->getType();
3848
3849 // Revise OldQTForComparison to include the merged effects,
3850 // so as not to fail due to differences later.
3851 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
3852 EPI = OldFPT->getExtProtoInfo();
3853 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
3854 OldQTypeForComparison = Context.getFunctionType(
3855 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
3856 }
3857 }
3858 }
3859 }
3860
3861 if (getLangOpts().CPlusPlus) {
3862 OldQType = Context.getCanonicalType(Old->getType());
3863 NewQType = Context.getCanonicalType(New->getType());
3864
3865 // Go back to the type source info to compare the declared return types,
3866 // per C++1y [dcl.type.auto]p13:
3867 // Redeclarations or specializations of a function or function template
3868 // with a declared return type that uses a placeholder type shall also
3869 // use that placeholder, not a deduced type.
3870 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3871 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3872 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3873 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3874 OldDeclaredReturnType)) {
3875 QualType ResQT;
3876 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3877 OldDeclaredReturnType->isObjCObjectPointerType())
3878 // FIXME: This does the wrong thing for a deduced return type.
3879 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3880 if (ResQT.isNull()) {
3881 if (New->isCXXClassMember() && New->isOutOfLine())
3882 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3883 << New << New->getReturnTypeSourceRange();
3884 else
3885 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3886 << New->getReturnTypeSourceRange();
3887 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3888 << Old->getReturnTypeSourceRange();
3889 return true;
3890 }
3891 else
3892 NewQType = ResQT;
3893 }
3894
3895 QualType OldReturnType = OldType->getReturnType();
3896 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3897 if (OldReturnType != NewReturnType) {
3898 // If this function has a deduced return type and has already been
3899 // defined, copy the deduced value from the old declaration.
3900 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3901 if (OldAT && OldAT->isDeduced()) {
3902 QualType DT = OldAT->getDeducedType();
3903 if (DT.isNull()) {
3905 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3906 } else {
3907 New->setType(SubstAutoType(New->getType(), DT));
3908 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3909 }
3910 }
3911 }
3912
3913 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3914 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3915 if (OldMethod && NewMethod) {
3916 // Preserve triviality.
3917 NewMethod->setTrivial(OldMethod->isTrivial());
3918
3919 // MSVC allows explicit template specialization at class scope:
3920 // 2 CXXMethodDecls referring to the same function will be injected.
3921 // We don't want a redeclaration error.
3922 bool IsClassScopeExplicitSpecialization =
3923 OldMethod->isFunctionTemplateSpecialization() &&
3925 bool isFriend = NewMethod->getFriendObjectKind();
3926
3927 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3928 !IsClassScopeExplicitSpecialization) {
3929 // -- Member function declarations with the same name and the
3930 // same parameter types cannot be overloaded if any of them
3931 // is a static member function declaration.
3932 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3933 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3934 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3935 return true;
3936 }
3937
3938 // C++ [class.mem]p1:
3939 // [...] A member shall not be declared twice in the
3940 // member-specification, except that a nested class or member
3941 // class template can be declared and then later defined.
3942 if (!inTemplateInstantiation()) {
3943 unsigned NewDiag;
3944 if (isa<CXXConstructorDecl>(OldMethod))
3945 NewDiag = diag::err_constructor_redeclared;
3946 else if (isa<CXXDestructorDecl>(NewMethod))
3947 NewDiag = diag::err_destructor_redeclared;
3948 else if (isa<CXXConversionDecl>(NewMethod))
3949 NewDiag = diag::err_conv_function_redeclared;
3950 else
3951 NewDiag = diag::err_member_redeclared;
3952
3953 Diag(New->getLocation(), NewDiag);
3954 } else {
3955 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3956 << New << New->getType();
3957 }
3958 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3959 return true;
3960
3961 // Complain if this is an explicit declaration of a special
3962 // member that was initially declared implicitly.
3963 //
3964 // As an exception, it's okay to befriend such methods in order
3965 // to permit the implicit constructor/destructor/operator calls.
3966 } else if (OldMethod->isImplicit()) {
3967 if (isFriend) {
3968 NewMethod->setImplicit();
3969 } else {
3970 Diag(NewMethod->getLocation(),
3971 diag::err_definition_of_implicitly_declared_member)
3972 << New << llvm::to_underlying(getSpecialMember(OldMethod));
3973 return true;
3974 }
3975 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3976 Diag(NewMethod->getLocation(),
3977 diag::err_definition_of_explicitly_defaulted_member)
3978 << llvm::to_underlying(getSpecialMember(OldMethod));
3979 return true;
3980 }
3981 }
3982
3983 // C++1z [over.load]p2
3984 // Certain function declarations cannot be overloaded:
3985 // -- Function declarations that differ only in the return type,
3986 // the exception specification, or both cannot be overloaded.
3987
3988 // Check the exception specifications match. This may recompute the type of
3989 // both Old and New if it resolved exception specifications, so grab the
3990 // types again after this. Because this updates the type, we do this before
3991 // any of the other checks below, which may update the "de facto" NewQType
3992 // but do not necessarily update the type of New.
3993 if (CheckEquivalentExceptionSpec(Old, New))
3994 return true;
3995
3996 // C++11 [dcl.attr.noreturn]p1:
3997 // The first declaration of a function shall specify the noreturn
3998 // attribute if any declaration of that function specifies the noreturn
3999 // attribute.
4000 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4001 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4002 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4003 << NRA;
4004 Diag(Old->getLocation(), diag::note_previous_declaration);
4005 }
4006
4007 // C++11 [dcl.attr.depend]p2:
4008 // The first declaration of a function shall specify the
4009 // carries_dependency attribute for its declarator-id if any declaration
4010 // of the function specifies the carries_dependency attribute.
4011 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4012 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4013 Diag(CDA->getLocation(),
4014 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4015 Diag(Old->getFirstDecl()->getLocation(),
4016 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4017 }
4018
4019 // (C++98 8.3.5p3):
4020 // All declarations for a function shall agree exactly in both the
4021 // return type and the parameter-type-list.
4022 // We also want to respect all the extended bits except noreturn.
4023
4024 // noreturn should now match unless the old type info didn't have it.
4025 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4026 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4027 const FunctionType *OldTypeForComparison
4028 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4029 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4030 assert(OldQTypeForComparison.isCanonical());
4031 }
4032
4033 if (haveIncompatibleLanguageLinkages(Old, New)) {
4034 // As a special case, retain the language linkage from previous
4035 // declarations of a friend function as an extension.
4036 //
4037 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4038 // and is useful because there's otherwise no way to specify language
4039 // linkage within class scope.
4040 //
4041 // Check cautiously as the friend object kind isn't yet complete.
4042 if (New->getFriendObjectKind() != Decl::FOK_None) {
4043 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4044 Diag(OldLocation, PrevDiag);
4045 } else {
4046 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4047 Diag(OldLocation, PrevDiag);
4048 return true;
4049 }
4050 }
4051
4052 // If the function types are compatible, merge the declarations. Ignore the
4053 // exception specifier because it was already checked above in
4054 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4055 // about incompatible types under -fms-compatibility.
4056 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4057 NewQType))
4058 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4059
4060 // If the types are imprecise (due to dependent constructs in friends or
4061 // local extern declarations), it's OK if they differ. We'll check again
4062 // during instantiation.
4063 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4064 return false;
4065
4066 // Fall through for conflicting redeclarations and redefinitions.
4067 }
4068
4069 // C: Function types need to be compatible, not identical. This handles
4070 // duplicate function decls like "void f(int); void f(enum X);" properly.
4071 if (!getLangOpts().CPlusPlus) {
4072 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4073 // type is specified by a function definition that contains a (possibly
4074 // empty) identifier list, both shall agree in the number of parameters
4075 // and the type of each parameter shall be compatible with the type that
4076 // results from the application of default argument promotions to the
4077 // type of the corresponding identifier. ...
4078 // This cannot be handled by ASTContext::typesAreCompatible() because that
4079 // doesn't know whether the function type is for a definition or not when
4080 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4081 // we need to cover here is that the number of arguments agree as the
4082 // default argument promotion rules were already checked by
4083 // ASTContext::typesAreCompatible().
4084 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4085 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4086 if (Old->hasInheritedPrototype())
4087 Old = Old->getCanonicalDecl();
4088 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4089 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4090 return true;
4091 }
4092
4093 // If we are merging two functions where only one of them has a prototype,
4094 // we may have enough information to decide to issue a diagnostic that the
4095 // function without a prototype will change behavior in C23. This handles
4096 // cases like:
4097 // void i(); void i(int j);
4098 // void i(int j); void i();
4099 // void i(); void i(int j) {}
4100 // See ActOnFinishFunctionBody() for other cases of the behavior change
4101 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4102 // type without a prototype.
4103 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4104 !New->isImplicit() && !Old->isImplicit()) {
4105 const FunctionDecl *WithProto, *WithoutProto;
4106 if (New->hasWrittenPrototype()) {
4107 WithProto = New;
4108 WithoutProto = Old;
4109 } else {
4110 WithProto = Old;
4111 WithoutProto = New;
4112 }
4113
4114 if (WithProto->getNumParams() != 0) {
4115 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4116 // The one without the prototype will be changing behavior in C23, so
4117 // warn about that one so long as it's a user-visible declaration.
4118 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4119 if (WithoutProto == New)
4120 IsWithoutProtoADef = NewDeclIsDefn;
4121 else
4122 IsWithProtoADef = NewDeclIsDefn;
4123 Diag(WithoutProto->getLocation(),
4124 diag::warn_non_prototype_changes_behavior)
4125 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4126 << (WithoutProto == Old) << IsWithProtoADef;
4127
4128 // The reason the one without the prototype will be changing behavior
4129 // is because of the one with the prototype, so note that so long as
4130 // it's a user-visible declaration. There is one exception to this:
4131 // when the new declaration is a definition without a prototype, the
4132 // old declaration with a prototype is not the cause of the issue,
4133 // and that does not need to be noted because the one with a
4134 // prototype will not change behavior in C23.
4135 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4136 !IsWithoutProtoADef)
4137 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4138 }
4139 }
4140 }
4141
4142 if (Context.typesAreCompatible(OldQType, NewQType)) {
4143 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4144 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4145 const FunctionProtoType *OldProto = nullptr;
4146 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4147 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4148 // The old declaration provided a function prototype, but the
4149 // new declaration does not. Merge in the prototype.
4150 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4151 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4152 OldProto->getParamTypes(),
4153 OldProto->getExtProtoInfo());
4154 New->setType(NewQType);
4156
4157 // Synthesize parameters with the same types.
4159 for (const auto &ParamType : OldProto->param_types()) {
4161 Context, New, SourceLocation(), SourceLocation(), nullptr,
4162 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4163 Param->setScopeInfo(0, Params.size());
4164 Param->setImplicit();
4165 Params.push_back(Param);
4166 }
4167
4168 New->setParams(Params);
4169 }
4170
4171 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4172 }
4173 }
4174
4175 // Check if the function types are compatible when pointer size address
4176 // spaces are ignored.
4177 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4178 return false;
4179
4180 // GNU C permits a K&R definition to follow a prototype declaration
4181 // if the declared types of the parameters in the K&R definition
4182 // match the types in the prototype declaration, even when the
4183 // promoted types of the parameters from the K&R definition differ
4184 // from the types in the prototype. GCC then keeps the types from
4185 // the prototype.
4186 //
4187 // If a variadic prototype is followed by a non-variadic K&R definition,
4188 // the K&R definition becomes variadic. This is sort of an edge case, but
4189 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4190 // C99 6.9.1p8.
4191 if (!getLangOpts().CPlusPlus &&
4192 Old->hasPrototype() && !New->hasPrototype() &&
4193 New->getType()->getAs<FunctionProtoType>() &&
4194 Old->getNumParams() == New->getNumParams()) {
4197 const FunctionProtoType *OldProto
4198 = Old->getType()->getAs<FunctionProtoType>();
4199 const FunctionProtoType *NewProto
4200 = New->getType()->getAs<FunctionProtoType>();
4201
4202 // Determine whether this is the GNU C extension.
4203 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4204 NewProto->getReturnType());
4205 bool LooseCompatible = !MergedReturn.isNull();
4206 for (unsigned Idx = 0, End = Old->getNumParams();
4207 LooseCompatible && Idx != End; ++Idx) {
4208 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4209 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4210 if (Context.typesAreCompatible(OldParm->getType(),
4211 NewProto->getParamType(Idx))) {
4212 ArgTypes.push_back(NewParm->getType());
4213 } else if (Context.typesAreCompatible(OldParm->getType(),
4214 NewParm->getType(),
4215 /*CompareUnqualified=*/true)) {
4216 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4217 NewProto->getParamType(Idx) };
4218 Warnings.push_back(Warn);
4219 ArgTypes.push_back(NewParm->getType());
4220 } else
4221 LooseCompatible = false;
4222 }
4223
4224 if (LooseCompatible) {
4225 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4226 Diag(Warnings[Warn].NewParm->getLocation(),
4227 diag::ext_param_promoted_not_compatible_with_prototype)
4228 << Warnings[Warn].PromotedType
4229 << Warnings[Warn].OldParm->getType();
4230 if (Warnings[Warn].OldParm->getLocation().isValid())
4231 Diag(Warnings[Warn].OldParm->getLocation(),
4232 diag::note_previous_declaration);
4233 }
4234
4235 if (MergeTypeWithOld)
4236 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4237 OldProto->getExtProtoInfo()));
4238 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4239 }
4240
4241 // Fall through to diagnose conflicting types.
4242 }
4243
4244 // A function that has already been declared has been redeclared or
4245 // defined with a different type; show an appropriate diagnostic.
4246
4247 // If the previous declaration was an implicitly-generated builtin
4248 // declaration, then at the very least we should use a specialized note.
4249 unsigned BuiltinID;
4250 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4251 // If it's actually a library-defined builtin function like 'malloc'
4252 // or 'printf', just warn about the incompatible redeclaration.
4254 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4255 Diag(OldLocation, diag::note_previous_builtin_declaration)
4256 << Old << Old->getType();
4257 return false;
4258 }
4259
4260 PrevDiag = diag::note_previous_builtin_declaration;
4261 }
4262
4263 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4264 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4265 return true;
4266}
4267
4269 Scope *S, bool MergeTypeWithOld) {
4270 // Merge the attributes
4271 mergeDeclAttributes(New, Old);
4272
4273 // Merge "pure" flag.
4274 if (Old->isPureVirtual())
4275 New->setIsPureVirtual();
4276
4277 // Merge "used" flag.
4278 if (Old->getMostRecentDecl()->isUsed(false))
4279 New->setIsUsed();
4280
4281 // Merge attributes from the parameters. These can mismatch with K&R
4282 // declarations.
4283 if (New->getNumParams() == Old->getNumParams())
4284 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4285 ParmVarDecl *NewParam = New->getParamDecl(i);
4286 ParmVarDecl *OldParam = Old->getParamDecl(i);
4287 mergeParamDeclAttributes(NewParam, OldParam, *this);
4288 mergeParamDeclTypes(NewParam, OldParam, *this);
4289 }
4290
4291 if (getLangOpts().CPlusPlus)
4292 return MergeCXXFunctionDecl(New, Old, S);
4293
4294 // Merge the function types so the we get the composite types for the return
4295 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4296 // was visible.
4297 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4298 if (!Merged.isNull() && MergeTypeWithOld)
4299 New->setType(Merged);
4300
4301 return false;
4302}
4303
4305 ObjCMethodDecl *oldMethod) {
4306 // Merge the attributes, including deprecated/unavailable
4307 AvailabilityMergeKind MergeKind =
4308 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4311 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4312 : AMK_Override;
4313
4314 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4315
4316 // Merge attributes from the parameters.
4318 oe = oldMethod->param_end();
4320 ni = newMethod->param_begin(), ne = newMethod->param_end();
4321 ni != ne && oi != oe; ++ni, ++oi)
4322 mergeParamDeclAttributes(*ni, *oi, *this);
4323
4324 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4325}
4326
4328 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4329
4331 ? diag::err_redefinition_different_type
4332 : diag::err_redeclaration_different_type)
4333 << New->getDeclName() << New->getType() << Old->getType();
4334
4335 diag::kind PrevDiag;
4336 SourceLocation OldLocation;
4337 std::tie(PrevDiag, OldLocation)
4339 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4340 New->setInvalidDecl();
4341}
4342
4344 bool MergeTypeWithOld) {
4345 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4346 return;
4347
4348 QualType MergedT;
4349 if (getLangOpts().CPlusPlus) {
4350 if (New->getType()->isUndeducedType()) {
4351 // We don't know what the new type is until the initializer is attached.
4352 return;
4353 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4354 // These could still be something that needs exception specs checked.
4355 return MergeVarDeclExceptionSpecs(New, Old);
4356 }
4357 // C++ [basic.link]p10:
4358 // [...] the types specified by all declarations referring to a given
4359 // object or function shall be identical, except that declarations for an
4360 // array object can specify array types that differ by the presence or
4361 // absence of a major array bound (8.3.4).
4362 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4363 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4364 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4365
4366 // We are merging a variable declaration New into Old. If it has an array
4367 // bound, and that bound differs from Old's bound, we should diagnose the
4368 // mismatch.
4369 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4370 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4371 PrevVD = PrevVD->getPreviousDecl()) {
4372 QualType PrevVDTy = PrevVD->getType();
4373 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4374 continue;
4375
4376 if (!Context.hasSameType(New->getType(), PrevVDTy))
4377 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4378 }
4379 }
4380
4381 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4382 if (Context.hasSameType(OldArray->getElementType(),
4383 NewArray->getElementType()))
4384 MergedT = New->getType();
4385 }
4386 // FIXME: Check visibility. New is hidden but has a complete type. If New
4387 // has no array bound, it should not inherit one from Old, if Old is not
4388 // visible.
4389 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4390 if (Context.hasSameType(OldArray->getElementType(),
4391 NewArray->getElementType()))
4392 MergedT = Old->getType();
4393 }
4394 }
4395 else if (New->getType()->isObjCObjectPointerType() &&
4396 Old->getType()->isObjCObjectPointerType()) {
4397 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4398 Old->getType());
4399 }
4400 } else {
4401 // C 6.2.7p2:
4402 // All declarations that refer to the same object or function shall have
4403 // compatible type.
4404 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4405 }
4406 if (MergedT.isNull()) {
4407 // It's OK if we couldn't merge types if either type is dependent, for a
4408 // block-scope variable. In other cases (static data members of class
4409 // templates, variable templates, ...), we require the types to be
4410 // equivalent.
4411 // FIXME: The C++ standard doesn't say anything about this.
4412 if ((New->getType()->isDependentType() ||
4413 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4414 // If the old type was dependent, we can't merge with it, so the new type
4415 // becomes dependent for now. We'll reproduce the original type when we
4416 // instantiate the TypeSourceInfo for the variable.
4417 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4419 return;
4420 }
4421 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4422 }
4423
4424 // Don't actually update the type on the new declaration if the old
4425 // declaration was an extern declaration in a different scope.
4426 if (MergeTypeWithOld)
4427 New->setType(MergedT);
4428}
4429
4430static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4432 // C11 6.2.7p4:
4433 // For an identifier with internal or external linkage declared
4434 // in a scope in which a prior declaration of that identifier is
4435 // visible, if the prior declaration specifies internal or
4436 // external linkage, the type of the identifier at the later
4437 // declaration becomes the composite type.
4438 //
4439 // If the variable isn't visible, we do not merge with its type.
4440 if (Previous.isShadowed())
4441 return false;
4442
4443 if (S.getLangOpts().CPlusPlus) {
4444 // C++11 [dcl.array]p3:
4445 // If there is a preceding declaration of the entity in the same
4446 // scope in which the bound was specified, an omitted array bound
4447 // is taken to be the same as in that earlier declaration.
4448 return NewVD->isPreviousDeclInSameBlockScope() ||
4451 } else {
4452 // If the old declaration was function-local, don't merge with its
4453 // type unless we're in the same function.
4454 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4455 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4456 }
4457}
4458
4460 // If the new decl is already invalid, don't do any other checking.
4461 if (New->isInvalidDecl())
4462 return;
4463
4464 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4465 return;
4466
4467 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4468
4469 // Verify the old decl was also a variable or variable template.
4470 VarDecl *Old = nullptr;
4471 VarTemplateDecl *OldTemplate = nullptr;
4472 if (Previous.isSingleResult()) {
4473 if (NewTemplate) {
4474 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4475 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4476
4477 if (auto *Shadow =
4478 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4479 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4480 return New->setInvalidDecl();
4481 } else {
4482 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4483
4484 if (auto *Shadow =
4485 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4486 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4487 return New->setInvalidDecl();
4488 }
4489 }
4490 if (!Old) {
4491 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4492 << New->getDeclName();
4493 notePreviousDefinition(Previous.getRepresentativeDecl(),
4494 New->getLocation());
4495 return New->setInvalidDecl();
4496 }
4497
4498 // If the old declaration was found in an inline namespace and the new
4499 // declaration was qualified, update the DeclContext to match.
4501
4502 // Ensure the template parameters are compatible.
4503 if (NewTemplate &&
4505 OldTemplate->getTemplateParameters(),
4506 /*Complain=*/true, TPL_TemplateMatch))
4507 return New->setInvalidDecl();
4508
4509 // C++ [class.mem]p1:
4510 // A member shall not be declared twice in the member-specification [...]
4511 //
4512 // Here, we need only consider static data members.
4513 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4514 Diag(New->getLocation(), diag::err_duplicate_member)
4515 << New->getIdentifier();
4516 Diag(Old->getLocation(), diag::note_previous_declaration);
4517 New->setInvalidDecl();
4518 }
4519
4520 mergeDeclAttributes(New, Old);
4521 // Warn if an already-defined variable is made a weak_import in a subsequent
4522 // declaration
4523 if (New->hasAttr<WeakImportAttr>())
4524 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4525 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4526 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4527 Diag(D->getLocation(), diag::note_previous_definition);
4528 // Remove weak_import attribute on new declaration.
4529 New->dropAttr<WeakImportAttr>();
4530 break;
4531 }
4532 }
4533
4534 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4535 if (!Old->hasAttr<InternalLinkageAttr>()) {
4536 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4537 << ILA;
4538 Diag(Old->getLocation(), diag::note_previous_declaration);
4539 New->dropAttr<InternalLinkageAttr>();
4540 }
4541
4542 // Merge the types.
4543 VarDecl *MostRecent = Old->getMostRecentDecl();
4544 if (MostRecent != Old) {
4545 MergeVarDeclTypes(New, MostRecent,
4546 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4547 if (New->isInvalidDecl())
4548 return;
4549 }
4550
4551 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4552 if (New->isInvalidDecl())
4553 return;
4554
4555 diag::kind PrevDiag;
4556 SourceLocation OldLocation;
4557 std::tie(PrevDiag, OldLocation) =
4559
4560 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4561 if (New->getStorageClass() == SC_Static &&
4562 !New->isStaticDataMember() &&
4563 Old->hasExternalFormalLinkage()) {
4564 if (getLangOpts().MicrosoftExt) {
4565 Diag(New->getLocation(), diag::ext_static_non_static)
4566 << New->getDeclName();
4567 Diag(OldLocation, PrevDiag);
4568 } else {
4569 Diag(New->getLocation(), diag::err_static_non_static)
4570 << New->getDeclName();
4571 Diag(OldLocation, PrevDiag);
4572 return New->setInvalidDecl();
4573 }
4574 }
4575 // C99 6.2.2p4:
4576 // For an identifier declared with the storage-class specifier
4577 // extern in a scope in which a prior declaration of that
4578 // identifier is visible,23) if the prior declaration specifies
4579 // internal or external linkage, the linkage of the identifier at
4580 // the later declaration is the same as the linkage specified at
4581 // the prior declaration. If no prior declaration is visible, or
4582 // if the prior declaration specifies no linkage, then the
4583 // identifier has external linkage.
4584 if (New->hasExternalStorage() && Old->hasLinkage())
4585 /* Okay */;
4586 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4587 !New->isStaticDataMember() &&
4589 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4590 Diag(OldLocation, PrevDiag);
4591 return New->setInvalidDecl();
4592 }
4593
4594 // Check if extern is followed by non-extern and vice-versa.
4595 if (New->hasExternalStorage() &&
4596 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4597 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4598 Diag(OldLocation, PrevDiag);
4599 return New->setInvalidDecl();
4600 }
4601 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4602 !New->hasExternalStorage()) {
4603 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4604 Diag(OldLocation, PrevDiag);
4605 return New->setInvalidDecl();
4606 }
4607
4608 if (CheckRedeclarationInModule(New, Old))
4609 return;
4610
4611 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4612
4613 // FIXME: The test for external storage here seems wrong? We still
4614 // need to check for mismatches.
4615 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4616 // Don't complain about out-of-line definitions of static members.
4617 !(Old->getLexicalDeclContext()->isRecord() &&
4618 !New->getLexicalDeclContext()->isRecord())) {
4619 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4620 Diag(OldLocation, PrevDiag);
4621 return New->setInvalidDecl();
4622 }
4623
4624 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4625 if (VarDecl *Def = Old->getDefinition()) {
4626 // C++1z [dcl.fcn.spec]p4:
4627 // If the definition of a variable appears in a translation unit before
4628 // its first declaration as inline, the program is ill-formed.
4629 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4630 Diag(Def->getLocation(), diag::note_previous_definition);
4631 }
4632 }
4633
4634 // If this redeclaration makes the variable inline, we may need to add it to
4635 // UndefinedButUsed.
4636 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4638 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4639 SourceLocation()));
4640
4641 if (New->getTLSKind() != Old->getTLSKind()) {
4642 if (!Old->getTLSKind()) {
4643 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4644 Diag(OldLocation, PrevDiag);
4645 } else if (!New->getTLSKind()) {
4646 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4647 Diag(OldLocation, PrevDiag);
4648 } else {
4649 // Do not allow redeclaration to change the variable between requiring
4650 // static and dynamic initialization.
4651 // FIXME: GCC allows this, but uses the TLS keyword on the first
4652 // declaration to determine the kind. Do we need to be compatible here?
4653 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4654 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4655 Diag(OldLocation, PrevDiag);
4656 }
4657 }
4658
4659 // C++ doesn't have tentative definitions, so go right ahead and check here.
4660 if (getLangOpts().CPlusPlus) {
4661 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4662 Old->getCanonicalDecl()->isConstexpr()) {
4663 // This definition won't be a definition any more once it's been merged.
4664 Diag(New->getLocation(),
4665 diag::warn_deprecated_redundant_constexpr_static_def);
4667 VarDecl *Def = Old->getDefinition();
4668 if (Def && checkVarDeclRedefinition(Def, New))
4669 return;
4670 }
4671 }
4672
4673 if (haveIncompatibleLanguageLinkages(Old, New)) {
4674 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4675 Diag(OldLocation, PrevDiag);
4676 New->setInvalidDecl();
4677 return;
4678 }
4679
4680 // Merge "used" flag.
4681 if (Old->getMostRecentDecl()->isUsed(false))
4682 New->setIsUsed();
4683
4684 // Keep a chain of previous declarations.
4685 New->setPreviousDecl(Old);
4686 if (NewTemplate)
4687 NewTemplate->setPreviousDecl(OldTemplate);
4688
4689 // Inherit access appropriately.
4690 New->setAccess(Old->getAccess());
4691 if (NewTemplate)
4692 NewTemplate->setAccess(New->getAccess());
4693
4694 if (Old->isInline())
4695 New->setImplicitlyInline();
4696}
4697
4699 SourceManager &SrcMgr = getSourceManager();
4700 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4701 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4702 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4703 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4704 auto &HSI = PP.getHeaderSearchInfo();
4705 StringRef HdrFilename =
4706 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4707
4708 auto noteFromModuleOrInclude = [&](Module *Mod,
4709 SourceLocation IncLoc) -> bool {
4710 // Redefinition errors with modules are common with non modular mapped
4711 // headers, example: a non-modular header H in module A that also gets
4712 // included directly in a TU. Pointing twice to the same header/definition
4713 // is confusing, try to get better diagnostics when modules is on.
4714 if (IncLoc.isValid()) {
4715 if (Mod) {
4716 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4717 << HdrFilename.str() << Mod->getFullModuleName();
4718 if (!Mod->DefinitionLoc.isInvalid())
4719 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4720 << Mod->getFullModuleName();
4721 } else {
4722 Diag(IncLoc, diag::note_redefinition_include_same_file)
4723 << HdrFilename.str();
4724 }
4725 return true;
4726 }
4727
4728 return false;
4729 };
4730
4731 // Is it the same file and same offset? Provide more information on why
4732 // this leads to a redefinition error.
4733 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4734 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4735 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4736 bool EmittedDiag =
4737 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4738 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4739
4740 // If the header has no guards, emit a note suggesting one.
4741 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4742 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4743
4744 if (EmittedDiag)
4745 return;
4746 }
4747
4748 // Redefinition coming from different files or couldn't do better above.
4749 if (Old->getLocation().isValid())
4750 Diag(Old->getLocation(), diag::note_previous_definition);
4751}
4752
4754 if (!hasVisibleDefinition(Old) &&
4755 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4756 isa<VarTemplateSpecializationDecl>(New) ||
4759 // The previous definition is hidden, and multiple definitions are
4760 // permitted (in separate TUs). Demote this to a declaration.
4762
4763 // Make the canonical definition visible.
4764 if (auto *OldTD = Old->getDescribedVarTemplate())
4767 return false;
4768 } else {
4769 Diag(New->getLocation(), diag::err_redefinition) << New;
4771 New->setInvalidDecl();
4772 return true;
4773 }
4774}
4775
4777 DeclSpec &DS,
4778 const ParsedAttributesView &DeclAttrs,
4779 RecordDecl *&AnonRecord) {
4781 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
4782}
4783
4784// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4785// disambiguate entities defined in different scopes.
4786// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4787// compatibility.
4788// We will pick our mangling number depending on which version of MSVC is being
4789// targeted.
4790static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4792 ? S->getMSCurManglingNumber()
4793 : S->getMSLastManglingNumber();
4794}
4795
4796void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4797 if (!Context.getLangOpts().CPlusPlus)
4798 return;
4799
4800 if (isa<CXXRecordDecl>(Tag->getParent())) {
4801 // If this tag is the direct child of a class, number it if
4802 // it is anonymous.
4803 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4804 return;
4806 Context.getManglingNumberContext(Tag->getParent());
4808 Tag, MCtx.getManglingNumber(
4809 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4810 return;
4811 }
4812
4813 // If this tag isn't a direct child of a class, number it if it is local.
4815 Decl *ManglingContextDecl;
4816 std::tie(MCtx, ManglingContextDecl) =
4817 getCurrentMangleNumberContext(Tag->getDeclContext());
4818 if (MCtx) {
4820 Tag, MCtx->getManglingNumber(
4821 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4822 }
4823}
4824
4825namespace {
4826struct NonCLikeKind {
4827 enum {
4828 None,
4829 BaseClass,
4830 DefaultMemberInit,
4831 Lambda,
4832 Friend,
4833 OtherMember,
4834 Invalid,
4835 } Kind = None;
4837
4838 explicit operator bool() { return Kind != None; }
4839};
4840}
4841
4842/// Determine whether a class is C-like, according to the rules of C++
4843/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4844static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4845 if (RD->isInvalidDecl())
4846 return {NonCLikeKind::Invalid, {}};
4847
4848 // C++ [dcl.typedef]p9: [P1766R1]
4849 // An unnamed class with a typedef name for linkage purposes shall not
4850 //
4851 // -- have any base classes
4852 if (RD->getNumBases())
4853 return {NonCLikeKind::BaseClass,
4855 RD->bases_end()[-1].getEndLoc())};
4856 bool Invalid = false;
4857 for (Decl *D : RD->decls()) {
4858 // Don't complain about things we already diagnosed.
4859 if (D->isInvalidDecl()) {
4860 Invalid = true;
4861 continue;
4862 }
4863
4864 // -- have any [...] default member initializers
4865 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4866 if (FD->hasInClassInitializer()) {
4867 auto *Init = FD->getInClassInitializer();
4868 return {NonCLikeKind::DefaultMemberInit,
4869 Init ? Init->getSourceRange() : D->getSourceRange()};
4870 }
4871 continue;
4872 }
4873
4874 // FIXME: We don't allow friend declarations. This violates the wording of
4875 // P1766, but not the intent.
4876 if (isa<FriendDecl>(D))
4877 return {NonCLikeKind::Friend, D->getSourceRange()};
4878
4879 // -- declare any members other than non-static data members, member
4880 // enumerations, or member classes,
4881 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4882 isa<EnumDecl>(D))
4883 continue;
4884 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4885 if (!MemberRD) {
4886 if (D->isImplicit())
4887 continue;
4888 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4889 }
4890
4891 // -- contain a lambda-expression,
4892 if (MemberRD->isLambda())
4893 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4894
4895 // and all member classes shall also satisfy these requirements
4896 // (recursively).
4897 if (MemberRD->isThisDeclarationADefinition()) {
4898 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4899 return Kind;
4900 }
4901 }
4902
4903 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4904}
4905
4907 TypedefNameDecl *NewTD) {
4908 if (TagFromDeclSpec->isInvalidDecl())
4909 return;
4910
4911 // Do nothing if the tag already has a name for linkage purposes.
4912 if (TagFromDeclSpec->hasNameForLinkage())
4913 return;
4914
4915 // A well-formed anonymous tag must always be a TagUseKind::Definition.
4916 assert(TagFromDeclSpec->isThisDeclarationADefinition());
4917
4918 // The type must match the tag exactly; no qualifiers allowed.
4920 Context.getTagDeclType(TagFromDeclSpec))) {
4921 if (getLangOpts().CPlusPlus)
4922 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4923 return;
4924 }
4925
4926 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4927 // An unnamed class with a typedef name for linkage purposes shall [be
4928 // C-like].
4929 //
4930 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4931 // shouldn't happen, but there are constructs that the language rule doesn't
4932 // disallow for which we can't reasonably avoid computing linkage early.
4933 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4934 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4935 : NonCLikeKind();
4936 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4937 if (NonCLike || ChangesLinkage) {
4938 if (NonCLike.Kind == NonCLikeKind::Invalid)
4939 return;
4940
4941 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4942 if (ChangesLinkage) {
4943 // If the linkage changes, we can't accept this as an extension.
4944 if (NonCLike.Kind == NonCLikeKind::None)
4945 DiagID = diag::err_typedef_changes_linkage;
4946 else
4947 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4948 }
4949
4950 SourceLocation FixitLoc =
4951 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4952 llvm::SmallString<40> TextToInsert;
4953 TextToInsert += ' ';
4954 TextToInsert += NewTD->getIdentifier()->getName();
4955
4956 Diag(FixitLoc, DiagID)
4957 << isa<TypeAliasDecl>(NewTD)
4958 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4959 if (NonCLike.Kind != NonCLikeKind::None) {
4960 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4961 << NonCLike.Kind - 1 << NonCLike.Range;
4962 }
4963 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4964 << NewTD << isa<TypeAliasDecl>(NewTD);
4965
4966 if (ChangesLinkage)
4967 return;
4968 }
4969
4970 // Otherwise, set this as the anon-decl typedef for the tag.
4971 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4972}
4973
4974static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
4976 switch (T) {
4978 return 0;
4980 return 1;
4982 return 2;
4984 return 3;
4985 case DeclSpec::TST_enum:
4986 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
4987 if (ED->isScopedUsingClassTag())
4988 return 5;
4989 if (ED->isScoped())
4990 return 6;
4991 }
4992 return 4;
4993 default:
4994 llvm_unreachable("unexpected type specifier");
4995 }
4996}
4997
4999 DeclSpec &DS,
5000 const ParsedAttributesView &DeclAttrs,
5001 MultiTemplateParamsArg TemplateParams,
5002 bool IsExplicitInstantiation,
5003 RecordDecl *&AnonRecord) {
5004 Decl *TagD = nullptr;
5005 TagDecl *Tag = nullptr;
5011 TagD = DS.getRepAsDecl();
5012
5013 if (!TagD) // We probably had an error
5014 return nullptr;
5015
5016 // Note that the above type specs guarantee that the
5017 // type rep is a Decl, whereas in many of the others
5018 // it's a Type.
5019 if (isa<TagDecl>(TagD))
5020 Tag = cast<TagDecl>(TagD);
5021 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5022 Tag = CTD->getTemplatedDecl();
5023 }
5024
5025 if (Tag) {
5026 handleTagNumbering(Tag, S);
5027 Tag->setFreeStanding();
5028 if (Tag->isInvalidDecl())
5029 return Tag;
5030 }
5031
5032 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5033 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5034 // or incomplete types shall not be restrict-qualified."
5035 if (TypeQuals & DeclSpec::TQ_restrict)
5037 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5038 << DS.getSourceRange();
5039 }
5040
5041 if (DS.isInlineSpecified())
5042 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5043 << getLangOpts().CPlusPlus17;
5044
5045 if (DS.hasConstexprSpecifier()) {
5046 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5047 // and definitions of functions and variables.
5048 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5049 // the declaration of a function or function template
5050 if (Tag)
5051 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5053 << static_cast<int>(DS.getConstexprSpecifier());
5054 else if (getLangOpts().C23)
5055 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5056 else
5057 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5058 << static_cast<int>(DS.getConstexprSpecifier());
5059 // Don't emit warnings after this error.
5060 return TagD;
5061 }
5062
5064
5065 if (DS.isFriendSpecified()) {
5066 // If we're dealing with a decl but not a TagDecl, assume that
5067 // whatever routines created it handled the friendship aspect.
5068 if (TagD && !Tag)
5069 return nullptr;
5070 return ActOnFriendTypeDecl(S, DS, TemplateParams);
5071 }
5072
5073 // Track whether this decl-specifier declares anything.
5074 bool DeclaresAnything = true;
5075
5076 // Handle anonymous struct definitions.
5077 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5078 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5080 if (getLangOpts().CPlusPlus ||
5081 Record->getDeclContext()->isRecord()) {
5082 // If CurContext is a DeclContext that can contain statements,
5083 // RecursiveASTVisitor won't visit the decls that
5084 // BuildAnonymousStructOrUnion() will put into CurContext.
5085 // Also store them here so that they can be part of the
5086 // DeclStmt that gets created in this case.
5087 // FIXME: Also return the IndirectFieldDecls created by
5088 // BuildAnonymousStructOr union, for the same reason?
5090 AnonRecord = Record;
5091 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5093 }
5094
5095 DeclaresAnything = false;
5096 }
5097 }
5098
5099 // C11 6.7.2.1p2:
5100 // A struct-declaration that does not declare an anonymous structure or
5101 // anonymous union shall contain a struct-declarator-list.
5102 //
5103 // This rule also existed in C89 and C99; the grammar for struct-declaration
5104 // did not permit a struct-declaration without a struct-declarator-list.
5107 // Check for Microsoft C extension: anonymous struct/union member.
5108 // Handle 2 kinds of anonymous struct/union:
5109 // struct STRUCT;
5110 // union UNION;
5111 // and
5112 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5113 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5114 if ((Tag && Tag->getDeclName()) ||
5116 RecordDecl *Record = nullptr;
5117 if (Tag)
5118 Record = dyn_cast<RecordDecl>(Tag);
5119 else if (const RecordType *RT =
5121 Record = RT->getDecl();
5122 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
5123 Record = UT->getDecl();
5124
5125 if (Record && getLangOpts().MicrosoftExt) {
5126 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5127 << Record->isUnion() << DS.getSourceRange();
5129 }
5130
5131 DeclaresAnything = false;
5132 }
5133 }
5134
5135 // Skip all the checks below if we have a type error.
5137 (TagD && TagD->isInvalidDecl()))
5138 return TagD;
5139
5140 if (getLangOpts().CPlusPlus &&
5142 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5143 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
5144 !Enum->getIdentifier() && !Enum->isInvalidDecl())
5145 DeclaresAnything = false;
5146
5147 if (!DS.isMissingDeclaratorOk()) {
5148 // Customize diagnostic for a typedef missing a name.
5150 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5151 << DS.getSourceRange();
5152 else
5153 DeclaresAnything = false;
5154 }
5155
5156 if (DS.isModulePrivateSpecified() &&
5157 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5158 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5159 << llvm::to_underlying(Tag->getTagKind())
5161
5163
5164 // C 6.7/2:
5165 // A declaration [...] shall declare at least a declarator [...], a tag,
5166 // or the members of an enumeration.
5167 // C++ [dcl.dcl]p3:
5168 // [If there are no declarators], and except for the declaration of an
5169 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5170 // names into the program, or shall redeclare a name introduced by a
5171 // previous declaration.
5172 if (!DeclaresAnything) {
5173 // In C, we allow this as a (popular) extension / bug. Don't bother
5174 // producing further diagnostics for redundant qualifiers after this.
5175 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5176 ? diag::err_no_declarators
5177 : diag::ext_no_declarators)
5178 << DS.getSourceRange();
5179 return TagD;
5180 }
5181
5182 // C++ [dcl.stc]p1:
5183 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5184 // init-declarator-list of the declaration shall not be empty.
5185 // C++ [dcl.fct.spec]p1:
5186 // If a cv-qualifier appears in a decl-specifier-seq, the
5187 // init-declarator-list of the declaration shall not be empty.
5188 //
5189 // Spurious qualifiers here appear to be valid in C.
5190 unsigned DiagID = diag::warn_standalone_specifier;
5191 if (getLangOpts().CPlusPlus)
5192 DiagID = diag::ext_standalone_specifier;
5193
5194 // Note that a linkage-specification sets a storage class, but
5195 // 'extern "C" struct foo;' is actually valid and not theoretically
5196 // useless.
5197 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5198 if (SCS == DeclSpec::SCS_mutable)
5199 // Since mutable is not a viable storage class specifier in C, there is
5200 // no reason to treat it as an extension. Instead, diagnose as an error.
5201 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5202 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5203 Diag(DS.getStorageClassSpecLoc(), DiagID)
5205 }
5206
5210 if (DS.getTypeQualifiers()) {
5212 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5214 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5215 // Restrict is covered above.
5217 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5219 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5220 }
5221
5222 // Warn about ignored type attributes, for example:
5223 // __attribute__((aligned)) struct A;
5224 // Attributes should be placed after tag to apply to type declaration.
5225 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5226 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5227 if (TypeSpecType == DeclSpec::TST_class ||
5228 TypeSpecType == DeclSpec::TST_struct ||
5229 TypeSpecType == DeclSpec::TST_interface ||
5230 TypeSpecType == DeclSpec::TST_union ||
5231 TypeSpecType == DeclSpec::TST_enum) {
5232
5233 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5234 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5235 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5236 DiagnosticId = diag::warn_attribute_ignored;
5237 else if (AL.isRegularKeywordAttribute())
5238 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5239 else
5240 DiagnosticId = diag::warn_declspec_attribute_ignored;
5241 Diag(AL.getLoc(), DiagnosticId)
5242 << AL << GetDiagnosticTypeSpecifierID(DS);
5243 };
5244
5245 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5246 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5247 }
5248 }
5249
5250 return TagD;
5251}
5252
5253/// We are trying to inject an anonymous member into the given scope;
5254/// check if there's an existing declaration that can't be overloaded.
5255///
5256/// \return true if this is a forbidden redeclaration
5257static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5258 DeclContext *Owner,
5259 DeclarationName Name,
5260 SourceLocation NameLoc, bool IsUnion,
5261 StorageClass SC) {
5262 LookupResult R(SemaRef, Name, NameLoc,
5265 RedeclarationKind::ForVisibleRedeclaration);
5266 if (!SemaRef.LookupName(R, S)) return false;
5267
5268 // Pick a representative declaration.
5270 assert(PrevDecl && "Expected a non-null Decl");
5271
5272 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5273 return false;
5274
5275 if (SC == StorageClass::SC_None &&
5276 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5277 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5278 if (!Owner->isRecord())
5279 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5280 return false;
5281 }
5282
5283 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5284 << IsUnion << Name;
5285 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5286
5287 return true;
5288}
5289
5291 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5293}
5294
5296 if (!getLangOpts().CPlusPlus)
5297 return;
5298
5299 // This function can be parsed before we have validated the
5300 // structure as an anonymous struct
5301 if (Record->isAnonymousStructOrUnion())
5302 return;
5303
5304 const NamedDecl *First = 0;
5305 for (const Decl *D : Record->decls()) {
5306 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5307 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5308 continue;
5309 if (!First)
5310 First = ND;
5311 else
5313 }
5314}
5315
5316/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5317/// anonymous struct or union AnonRecord into the owning context Owner
5318/// and scope S. This routine will be invoked just after we realize
5319/// that an unnamed union or struct is actually an anonymous union or
5320/// struct, e.g.,
5321///
5322/// @code
5323/// union {
5324/// int i;
5325/// float f;
5326/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5327/// // f into the surrounding scope.x
5328/// @endcode
5329///
5330/// This routine is recursive, injecting the names of nested anonymous
5331/// structs/unions into the owning context and scope as well.
5332static bool
5334 RecordDecl *AnonRecord, AccessSpecifier AS,
5335 StorageClass SC,
5336 SmallVectorImpl<NamedDecl *> &Chaining) {
5337 bool Invalid = false;
5338
5339 // Look every FieldDecl and IndirectFieldDecl with a name.
5340 for (auto *D : AnonRecord->decls()) {
5341 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5342 cast<NamedDecl>(D)->getDeclName()) {
5343 ValueDecl *VD = cast<ValueDecl>(D);
5344 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5345 VD->getLocation(), AnonRecord->isUnion(),
5346 SC)) {
5347 // C++ [class.union]p2:
5348 // The names of the members of an anonymous union shall be
5349 // distinct from the names of any other entity in the
5350 // scope in which the anonymous union is declared.
5351 Invalid = true;
5352 } else {
5353 // C++ [class.union]p2:
5354 // For the purpose of name lookup, after the anonymous union
5355 // definition, the members of the anonymous union are
5356 // considered to have been defined in the scope in which the
5357 // anonymous union is declared.
5358 unsigned OldChainingSize = Chaining.size();
5359 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5360 Chaining.append(IF->chain_begin(), IF->chain_end());
5361 else
5362 Chaining.push_back(VD);
5363
5364 assert(Chaining.size() >= 2);
5365 NamedDecl **NamedChain =
5366 new (SemaRef.Context)NamedDecl*[Chaining.size()];
5367 for (unsigned i = 0; i < Chaining.size(); i++)
5368 NamedChain[i] = Chaining[i];
5369
5371 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5372 VD->getType(), {NamedChain, Chaining.size()});
5373
5374 for (const auto *Attr : VD->attrs())
5375 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5376
5377 IndirectField->setAccess(AS);
5378 IndirectField->setImplicit();
5379 SemaRef.PushOnScopeChains(IndirectField, S);
5380
5381 // That includes picking up the appropriate access specifier.
5382 if (AS != AS_none) IndirectField->setAccess(AS);
5383
5384 Chaining.resize(OldChainingSize);
5385 }
5386 }
5387 }
5388
5389 return Invalid;
5390}
5391
5392/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5393/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5394/// illegal input values are mapped to SC_None.
5395static StorageClass
5397 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5398 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5399 "Parser allowed 'typedef' as storage class VarDecl.");
5400 switch (StorageClassSpec) {
5403 if (DS.isExternInLinkageSpec())
5404 return SC_None;
5405 return SC_Extern;
5406 case DeclSpec::SCS_static: return SC_Static;
5407 case DeclSpec::SCS_auto: return SC_Auto;
5410 // Illegal SCSs map to None: error reporting is up to the caller.
5411 case DeclSpec::SCS_mutable: // Fall through.
5412 case DeclSpec::SCS_typedef: return SC_None;
5413 }
5414 llvm_unreachable("unknown storage class specifier");
5415}
5416
5418 assert(Record->hasInClassInitializer());
5419
5420 for (const auto *I : Record->decls()) {
5421 const auto *FD = dyn_cast<FieldDecl>(I);
5422 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5423 FD = IFD->getAnonField();
5424 if (FD && FD->hasInClassInitializer())
5425 return FD->getLocation();
5426 }
5427
5428 llvm_unreachable("couldn't find in-class initializer");
5429}
5430
5432 SourceLocation DefaultInitLoc) {
5433 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5434 return;
5435
5436 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5437 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5438}
5439
5441 CXXRecordDecl *AnonUnion) {
5442 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5443 return;
5444
5446}
5447
5449 AccessSpecifier AS,
5451 const PrintingPolicy &Policy) {
5452 DeclContext *Owner = Record->getDeclContext();
5453
5454 // Diagnose whether this anonymous struct/union is an extension.
5455 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5456 Diag(Record->getLocation(), diag::ext_anonymous_union);
5457 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5458 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5459 else if (!Record->isUnion() && !getLangOpts().C11)
5460 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5461
5462 // C and C++ require different kinds of checks for anonymous
5463 // structs/unions.
5464 bool Invalid = false;
5465 if (getLangOpts().CPlusPlus) {
5466 const char *PrevSpec = nullptr;
5467 if (Record->isUnion()) {
5468 // C++ [class.union]p6:
5469 // C++17 [class.union.anon]p2:
5470 // Anonymous unions declared in a named namespace or in the
5471 // global namespace shall be declared static.
5472 unsigned DiagID;
5473 DeclContext *OwnerScope = Owner->getRedeclContext();
5475 (OwnerScope->isTranslationUnit() ||
5476 (OwnerScope->isNamespace() &&
5477 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5478 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5479 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5480
5481 // Recover by adding 'static'.
5483 PrevSpec, DiagID, Policy);
5484 }
5485 // C++ [class.union]p6:
5486 // A storage class is not allowed in a declaration of an
5487 // anonymous union in a class scope.
5489 isa<RecordDecl>(Owner)) {
5491 diag::err_anonymous_union_with_storage_spec)
5493
5494 // Recover by removing the storage specifier.
5497 PrevSpec, DiagID, Context.getPrintingPolicy());
5498 }
5499 }
5500
5501 // Ignore const/volatile/restrict qualifiers.
5502 if (DS.getTypeQualifiers()) {
5504 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5505 << Record->isUnion() << "const"
5509 diag::ext_anonymous_struct_union_qualified)
5510 << Record->isUnion() << "volatile"
5514 diag::ext_anonymous_struct_union_qualified)
5515 << Record->isUnion() << "restrict"
5519 diag::ext_anonymous_struct_union_qualified)
5520 << Record->isUnion() << "_Atomic"
5524 diag::ext_anonymous_struct_union_qualified)
5525 << Record->isUnion() << "__unaligned"
5527
5529 }
5530
5531 // C++ [class.union]p2:
5532 // The member-specification of an anonymous union shall only
5533 // define non-static data members. [Note: nested types and
5534 // functions cannot be declared within an anonymous union. ]
5535 for (auto *Mem : Record->decls()) {
5536 // Ignore invalid declarations; we already diagnosed them.
5537 if (Mem->isInvalidDecl())
5538 continue;
5539
5540 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5541 // C++ [class.union]p3:
5542 // An anonymous union shall not have private or protected
5543 // members (clause 11).
5544 assert(FD->getAccess() != AS_none);
5545 if (FD->getAccess() != AS_public) {
5546 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5547 << Record->isUnion() << (FD->getAccess() == AS_protected);
5548 Invalid = true;
5549 }
5550
5551 // C++ [class.union]p1
5552 // An object of a class with a non-trivial constructor, a non-trivial
5553 // copy constructor, a non-trivial destructor, or a non-trivial copy
5554 // assignment operator cannot be a member of a union, nor can an
5555 // array of such objects.
5556 if (CheckNontrivialField(FD))
5557 Invalid = true;
5558 } else if (Mem->isImplicit()) {
5559 // Any implicit members are fine.
5560 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5561 // This is a type that showed up in an
5562 // elaborated-type-specifier inside the anonymous struct or
5563 // union, but which actually declares a type outside of the
5564 // anonymous struct or union. It's okay.
5565 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5566 if (!MemRecord->isAnonymousStructOrUnion() &&
5567 MemRecord->getDeclName()) {
5568 // Visual C++ allows type definition in anonymous struct or union.
5569 if (getLangOpts().MicrosoftExt)
5570 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5571 << Record->isUnion();
5572 else {
5573 // This is a nested type declaration.
5574 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5575 << Record->isUnion();
5576 Invalid = true;
5577 }
5578 } else {
5579 // This is an anonymous type definition within another anonymous type.
5580 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5581 // not part of standard C++.
5582 Diag(MemRecord->getLocation(),
5583 diag::ext_anonymous_record_with_anonymous_type)
5584 << Record->isUnion();
5585 }
5586 } else if (isa<AccessSpecDecl>(Mem)) {
5587 // Any access specifier is fine.
5588 } else if (isa<StaticAssertDecl>(Mem)) {
5589 // In C++1z, static_assert declarations are also fine.
5590 } else {
5591 // We have something that isn't a non-static data
5592 // member. Complain about it.
5593 unsigned DK = diag::err_anonymous_record_bad_member;
5594 if (isa<TypeDecl>(Mem))
5595 DK = diag::err_anonymous_record_with_type;
5596 else if (isa<FunctionDecl>(Mem))
5597 DK = diag::err_anonymous_record_with_function;
5598 else if (isa<VarDecl>(Mem))
5599 DK = diag::err_anonymous_record_with_static;
5600
5601 // Visual C++ allows type definition in anonymous struct or union.
5602 if (getLangOpts().MicrosoftExt &&
5603 DK == diag::err_anonymous_record_with_type)
5604 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5605 << Record->isUnion();
5606 else {
5607 Diag(Mem->getLocation(), DK) << Record->isUnion();
5608 Invalid = true;
5609 }
5610 }
5611 }
5612
5613 // C++11 [class.union]p8 (DR1460):
5614 // At most one variant member of a union may have a
5615 // brace-or-equal-initializer.
5616 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5617 Owner->isRecord())
5618 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5619 cast<CXXRecordDecl>(Record));
5620 }
5621
5622 if (!Record->isUnion() && !Owner->isRecord()) {
5623 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5624 << getLangOpts().CPlusPlus;
5625 Invalid = true;
5626 }
5627
5628 // C++ [dcl.dcl]p3:
5629 // [If there are no declarators], and except for the declaration of an
5630 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5631 // names into the program
5632 // C++ [class.mem]p2:
5633 // each such member-declaration shall either declare at least one member
5634 // name of the class or declare at least one unnamed bit-field
5635 //
5636 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5637 if (getLangOpts().CPlusPlus && Record->field_empty())
5638 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5639
5640 // Mock up a declarator.
5644 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5645
5646 // Create a declaration for this anonymous struct/union.
5647 NamedDecl *Anon = nullptr;
5648 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5649 Anon = FieldDecl::Create(
5650 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5651 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5652 /*BitWidth=*/nullptr, /*Mutable=*/false,
5653 /*InitStyle=*/ICIS_NoInit);
5654 Anon->setAccess(AS);
5655 ProcessDeclAttributes(S, Anon, Dc);
5656
5657 if (getLangOpts().CPlusPlus)
5658 FieldCollector->Add(cast<FieldDecl>(Anon));
5659 } else {
5660 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5661 if (SCSpec == DeclSpec::SCS_mutable) {
5662 // mutable can only appear on non-static class members, so it's always
5663 // an error here
5664 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5665 Invalid = true;
5666 SC = SC_None;
5667 }
5668
5669 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5670 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5671 Context.getTypeDeclType(Record), TInfo, SC);
5672 if (Invalid)
5673 Anon->setInvalidDecl();
5674
5675 ProcessDeclAttributes(S, Anon, Dc);
5676
5677 // Default-initialize the implicit variable. This initialization will be
5678 // trivial in almost all cases, except if a union member has an in-class
5679 // initializer:
5680 // union { int n = 0; };
5682 }
5683 Anon->setImplicit();
5684
5685 // Mark this as an anonymous struct/union type.
5686 Record->setAnonymousStructOrUnion(true);
5687
5688 // Add the anonymous struct/union object to the current
5689 // context. We'll be referencing this object when we refer to one of
5690 // its members.
5691 Owner->addDecl(Anon);
5692
5693 // Inject the members of the anonymous struct/union into the owning
5694 // context and into the identifier resolver chain for name lookup
5695 // purposes.
5697 Chain.push_back(Anon);
5698
5699 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5700 Chain))
5701 Invalid = true;
5702
5703 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5704 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5706 Decl *ManglingContextDecl;
5707 std::tie(MCtx, ManglingContextDecl) =
5708 getCurrentMangleNumberContext(NewVD->getDeclContext());
5709 if (MCtx) {
5711 NewVD, MCtx->getManglingNumber(
5712 NewVD, getMSManglingNumber(getLangOpts(), S)));
5714 }
5715 }
5716 }
5717
5718 if (Invalid)
5719 Anon->setInvalidDecl();
5720
5721 return Anon;
5722}
5723
5725 RecordDecl *Record) {
5726 assert(Record && "expected a record!");
5727
5728 // Mock up a declarator.
5731 assert(TInfo && "couldn't build declarator info for anonymous struct");
5732
5733 auto *ParentDecl = cast<RecordDecl>(CurContext);
5735
5736 // Create a declaration for this anonymous struct.
5737 NamedDecl *Anon =
5738 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5739 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5740 /*BitWidth=*/nullptr, /*Mutable=*/false,
5741 /*InitStyle=*/ICIS_NoInit);
5742 Anon->setImplicit();
5743
5744 // Add the anonymous struct object to the current context.
5745 CurContext->addDecl(Anon);
5746
5747 // Inject the members of the anonymous struct into the current
5748 // context and into the identifier resolver chain for name lookup
5749 // purposes.
5751 Chain.push_back(Anon);
5752
5753 RecordDecl *RecordDef = Record->getDefinition();
5754 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5755 diag::err_field_incomplete_or_sizeless) ||
5757 *this, S, CurContext, RecordDef, AS_none,
5759 Anon->setInvalidDecl();
5760 ParentDecl->setInvalidDecl();
5761 }
5762
5763 return Anon;
5764}
5765
5767 return GetNameFromUnqualifiedId(D.getName());
5768}
5769
5772 DeclarationNameInfo NameInfo;
5773 NameInfo.setLoc(Name.StartLocation);
5774
5775 switch (Name.getKind()) {
5776
5779 NameInfo.setName(Name.Identifier);
5780 return NameInfo;
5781
5783 // C++ [temp.deduct.guide]p3:
5784 // The simple-template-id shall name a class template specialization.
5785 // The template-name shall be the same identifier as the template-name
5786 // of the simple-template-id.
5787 // These together intend to imply that the template-name shall name a
5788 // class template.
5789 // FIXME: template<typename T> struct X {};
5790 // template<typename T> using Y = X<T>;
5791 // Y(int) -> Y<int>;
5792 // satisfies these rules but does not name a class template.
5793 TemplateName TN = Name.TemplateName.get().get();
5794 auto *Template = TN.getAsTemplateDecl();
5795 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5796 Diag(Name.StartLocation,
5797 diag::err_deduction_guide_name_not_class_template)
5799 if (Template)
5800 NoteTemplateLocation(*Template);
5801 return DeclarationNameInfo();
5802 }
5803
5804 NameInfo.setName(
5806 return NameInfo;
5807 }
5808
5811 Name.OperatorFunctionId.Operator));
5813 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5814 return NameInfo;
5815
5818 Name.Identifier));
5819 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5820 return NameInfo;
5821
5823 TypeSourceInfo *TInfo;
5824 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5825 if (Ty.isNull())
5826 return DeclarationNameInfo();
5829 NameInfo.setNamedTypeInfo(TInfo);
5830 return NameInfo;
5831 }
5832
5834 TypeSourceInfo *TInfo;
5835 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5836 if (Ty.isNull())
5837 return DeclarationNameInfo();
5840 NameInfo.setNamedTypeInfo(TInfo);
5841 return NameInfo;
5842 }
5843
5845 // In well-formed code, we can only have a constructor
5846 // template-id that refers to the current context, so go there
5847 // to find the actual type being constructed.
5848 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5849 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5850 return DeclarationNameInfo();
5851
5852 // Determine the type of the class being constructed.
5853 QualType CurClassType = Context.getTypeDeclType(CurClass);
5854
5855 // FIXME: Check two things: that the template-id names the same type as
5856 // CurClassType, and that the template-id does not occur when the name
5857 // was qualified.
5858
5860 Context.getCanonicalType(CurClassType)));
5861 // FIXME: should we retrieve TypeSourceInfo?
5862 NameInfo.setNamedTypeInfo(nullptr);
5863 return NameInfo;
5864 }
5865
5867 TypeSourceInfo *TInfo;
5868 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5869 if (Ty.isNull())
5870 return DeclarationNameInfo();
5873 NameInfo.setNamedTypeInfo(TInfo);
5874 return NameInfo;
5875 }
5876
5878 TemplateName TName = Name.TemplateId->Template.get();
5879 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5880 return Context.getNameForTemplate(TName, TNameLoc);
5881 }
5882
5883 } // switch (Name.getKind())
5884
5885 llvm_unreachable("Unknown name kind");
5886}
5887
5889 do {
5890 if (Ty->isPointerType() || Ty->isReferenceType())
5891 Ty = Ty->getPointeeType();
5892 else if (Ty->isArrayType())
5894 else
5895 return Ty.withoutLocalFastQualifiers();
5896 } while (true);
5897}
5898
5899/// hasSimilarParameters - Determine whether the C++ functions Declaration
5900/// and Definition have "nearly" matching parameters. This heuristic is
5901/// used to improve diagnostics in the case where an out-of-line function
5902/// definition doesn't match any declaration within the class or namespace.
5903/// Also sets Params to the list of indices to the parameters that differ
5904/// between the declaration and the definition. If hasSimilarParameters
5905/// returns true and Params is empty, then all of the parameters match.
5909 SmallVectorImpl<unsigned> &Params) {
5910 Params.clear();
5911 if (Declaration->param_size() != Definition->param_size())
5912 return false;
5913 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5914 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5915 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5916
5917 // The parameter types are identical
5918 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5919 continue;
5920
5921 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5922 QualType DefParamBaseTy = getCoreType(DefParamTy);
5923 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5924 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5925
5926 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5927 (DeclTyName && DeclTyName == DefTyName))
5928 Params.push_back(Idx);
5929 else // The two parameters aren't even close
5930 return false;
5931 }
5932
5933 return true;
5934}
5935
5936/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
5937/// declarator needs to be rebuilt in the current instantiation.
5938/// Any bits of declarator which appear before the name are valid for
5939/// consideration here. That's specifically the type in the decl spec
5940/// and the base type in any member-pointer chunks.
5942 DeclarationName Name) {
5943 // The types we specifically need to rebuild are:
5944 // - typenames, typeofs, and decltypes
5945 // - types which will become injected class names
5946 // Of course, we also need to rebuild any type referencing such a
5947 // type. It's safest to just say "dependent", but we call out a
5948 // few cases here.
5949
5950 DeclSpec &DS = D.getMutableDeclSpec();
5951 switch (DS.getTypeSpecType()) {
5955#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
5956#include "clang/Basic/TransformTypeTraits.def"
5957 case DeclSpec::TST_atomic: {
5958 // Grab the type from the parser.
5959 TypeSourceInfo *TSI = nullptr;
5960 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5961 if (T.isNull() || !T->isInstantiationDependentType()) break;
5962
5963 // Make sure there's a type source info. This isn't really much
5964 // of a waste; most dependent types should have type source info
5965 // attached already.
5966 if (!TSI)
5968
5969 // Rebuild the type in the current instantiation.
5970 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5971 if (!TSI) return true;
5972
5973 // Store the new type back in the decl spec.
5974 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5975 DS.UpdateTypeRep(LocType);
5976 break;
5977 }
5978
5982 Expr *E = DS.getRepAsExpr();
5984 if (Result.isInvalid()) return true;
5985 DS.UpdateExprRep(Result.get());
5986 break;
5987 }
5988
5989 default:
5990 // Nothing to do for these decl specs.
5991 break;
5992 }
5993
5994 // It doesn't matter what order we do this in.
5995 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5996 DeclaratorChunk &Chunk = D.getTypeObject(I);
5997
5998 // The only type information in the declarator which can come
5999 // before the declaration name is the base type of a member
6000 // pointer.
6002 continue;
6003
6004 // Rebuild the scope specifier in-place.
6005 CXXScopeSpec &SS = Chunk.Mem.Scope();
6007 return true;
6008 }
6009
6010 return false;
6011}
6012
6013/// Returns true if the declaration is declared in a system header or from a
6014/// system macro.
6016 return SM.isInSystemHeader(D->getLocation()) ||
6017 SM.isInSystemMacro(D->getLocation());
6018}
6019
6021 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6022 // of system decl.
6023 if (D->getPreviousDecl() || D->isImplicit())
6024 return;
6025 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
6028 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6029 << D << static_cast<int>(Status);
6030 }
6031}
6032
6034 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
6035
6036 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6037 // declaration only if the `bind_to_declaration` extension is set.
6039 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6040 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6041 llvm::omp::TraitProperty::
6042 implementation_extension_bind_to_declaration))
6044 S, D, MultiTemplateParamsArg(), Bases);
6045
6047
6049 Dcl && Dcl->getDeclContext()->isFileContext())
6051
6052 if (!Bases.empty())
6054 Bases);
6055
6056 return Dcl;
6057}
6058
6060 DeclarationNameInfo NameInfo) {
6061 DeclarationName Name = NameInfo.getName();
6062
6063 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6064 while (Record && Record->isAnonymousStructOrUnion())
6065 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6066 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6067 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6068 return true;
6069 }
6070
6071 return false;
6072}
6073
6075 DeclarationName Name,
6077 TemplateIdAnnotation *TemplateId,
6078 bool IsMemberSpecialization) {
6079 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6080 "without nested-name-specifier");
6081 DeclContext *Cur = CurContext;
6082 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6083 Cur = Cur->getParent();
6084
6085 // If the user provided a superfluous scope specifier that refers back to the
6086 // class in which the entity is already declared, diagnose and ignore it.
6087 //
6088 // class X {
6089 // void X::f();
6090 // };
6091 //
6092 // Note, it was once ill-formed to give redundant qualification in all
6093 // contexts, but that rule was removed by DR482.
6094 if (Cur->Equals(DC)) {
6095 if (Cur->isRecord()) {
6096 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6097 : diag::err_member_extra_qualification)
6098 << Name << FixItHint::CreateRemoval(SS.getRange());
6099 SS.clear();
6100 } else {
6101 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6102 }
6103 return false;
6104 }
6105
6106 // Check whether the qualifying scope encloses the scope of the original
6107 // declaration. For a template-id, we perform the checks in
6108 // CheckTemplateSpecializationScope.
6109 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6110 if (Cur->isRecord())
6111 Diag(Loc, diag::err_member_qualification)
6112 << Name << SS.getRange();
6113 else if (isa<TranslationUnitDecl>(DC))
6114 Diag(Loc, diag::err_invalid_declarator_global_scope)
6115 << Name << SS.getRange();
6116 else if (isa<FunctionDecl>(Cur))
6117 Diag(Loc, diag::err_invalid_declarator_in_function)
6118 << Name << SS.getRange();
6119 else if (isa<BlockDecl>(Cur))
6120 Diag(Loc, diag::err_invalid_declarator_in_block)
6121 << Name << SS.getRange();
6122 else if (isa<ExportDecl>(Cur)) {
6123 if (!isa<NamespaceDecl>(DC))
6124 Diag(Loc, diag::err_export_non_namespace_scope_name)
6125 << Name << SS.getRange();
6126 else
6127 // The cases that DC is not NamespaceDecl should be handled in
6128 // CheckRedeclarationExported.
6129 return false;
6130 } else
6131 Diag(Loc, diag::err_invalid_declarator_scope)
6132 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6133
6134 return true;
6135 }
6136
6137 if (Cur->isRecord()) {
6138 // Cannot qualify members within a class.
6139 Diag(Loc, diag::err_member_qualification)
6140 << Name << SS.getRange();
6141 SS.clear();
6142
6143 // C++ constructors and destructors with incorrect scopes can break
6144 // our AST invariants by having the wrong underlying types. If
6145 // that's the case, then drop this declaration entirely.
6146 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
6147 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
6148 !Context.hasSameType(Name.getCXXNameType(),
6149 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
6150 return true;
6151
6152 return false;
6153 }
6154
6155 // C++23 [temp.names]p5:
6156 // The keyword template shall not appear immediately after a declarative
6157 // nested-name-specifier.
6158 //
6159 // First check the template-id (if any), and then check each component of the
6160 // nested-name-specifier in reverse order.
6161 //
6162 // FIXME: nested-name-specifiers in friend declarations are declarative,
6163 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6164 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6165 Diag(Loc, diag::ext_template_after_declarative_nns)
6167
6169 do {
6170 if (SpecLoc.getNestedNameSpecifier()->getKind() ==
6172 Diag(Loc, diag::ext_template_after_declarative_nns)
6174 SpecLoc.getTypeLoc().getTemplateKeywordLoc());
6175
6176 if (const Type *T = SpecLoc.getNestedNameSpecifier()->getAsType()) {
6177 if (const auto *TST = T->getAsAdjusted<TemplateSpecializationType>()) {
6178 // C++23 [expr.prim.id.qual]p3:
6179 // [...] If a nested-name-specifier N is declarative and has a
6180 // simple-template-id with a template argument list A that involves a
6181 // template parameter, let T be the template nominated by N without A.
6182 // T shall be a class template.
6183 if (TST->isDependentType() && TST->isTypeAlias())
6184 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6185 << SpecLoc.getLocalSourceRange();
6186 } else if (T->isDecltypeType() || T->getAsAdjusted<PackIndexingType>()) {
6187 // C++23 [expr.prim.id.qual]p2:
6188 // [...] A declarative nested-name-specifier shall not have a
6189 // computed-type-specifier.
6190 //
6191 // CWG2858 changed this from 'decltype-specifier' to
6192 // 'computed-type-specifier'.
6193 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6194 << T->isDecltypeType() << SpecLoc.getTypeLoc().getSourceRange();
6195 }
6196 }
6197 } while ((SpecLoc = SpecLoc.getPrefix()));
6198
6199 return false;
6200}
6201
6203 MultiTemplateParamsArg TemplateParamLists) {
6204 // TODO: consider using NameInfo for diagnostic.
6206 DeclarationName Name = NameInfo.getName();
6207
6208 // All of these full declarators require an identifier. If it doesn't have
6209 // one, the ParsedFreeStandingDeclSpec action should be used.
6210 if (D.isDecompositionDeclarator()) {
6211 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6212 } else if (!Name) {
6213 if (!D.isInvalidType()) // Reject this if we think it is valid.
6214 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6215 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
6216 return nullptr;
6218 return nullptr;
6219
6220 DeclContext *DC = CurContext;
6221 if (D.getCXXScopeSpec().isInvalid())
6222 D.setInvalidType();
6223 else if (D.getCXXScopeSpec().isSet()) {
6224 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
6226 return nullptr;
6227
6228 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6229 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6230 if (!DC || isa<EnumDecl>(DC)) {
6231 // If we could not compute the declaration context, it's because the
6232 // declaration context is dependent but does not refer to a class,
6233 // class template, or class template partial specialization. Complain
6234 // and return early, to avoid the coming semantic disaster.
6235 Diag(D.getIdentifierLoc(),
6236 diag::err_template_qualified_declarator_no_match)
6237 << D.getCXXScopeSpec().getScopeRep()
6238 << D.getCXXScopeSpec().getRange();
6239 return nullptr;
6240 }
6241 bool IsDependentContext = DC->isDependentContext();
6242
6243 if (!IsDependentContext &&
6244 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
6245 return nullptr;
6246
6247 // If a class is incomplete, do not parse entities inside it.
6248 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
6249 Diag(D.getIdentifierLoc(),
6250 diag::err_member_def_undefined_record)
6251 << Name << DC << D.getCXXScopeSpec().getRange();
6252 return nullptr;
6253 }
6254 if (!D.getDeclSpec().isFriendSpecified()) {
6255 TemplateIdAnnotation *TemplateId =
6257 ? D.getName().TemplateId
6258 : nullptr;
6259 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, Name,
6260 D.getIdentifierLoc(), TemplateId,
6261 /*IsMemberSpecialization=*/false)) {
6262 if (DC->isRecord())
6263 return nullptr;
6264
6265 D.setInvalidType();
6266 }
6267 }
6268
6269 // Check whether we need to rebuild the type of the given
6270 // declaration in the current instantiation.
6271 if (EnteringContext && IsDependentContext &&
6272 TemplateParamLists.size() != 0) {
6273 ContextRAII SavedContext(*this, DC);
6275 D.setInvalidType();
6276 }
6277 }
6278
6280 QualType R = TInfo->getType();
6281
6282 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6284 D.setInvalidType();
6285
6286 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6288
6289 // See if this is a redefinition of a variable in the same scope.
6290 if (!D.getCXXScopeSpec().isSet()) {
6291 bool IsLinkageLookup = false;
6292 bool CreateBuiltins = false;
6293
6294 // If the declaration we're planning to build will be a function
6295 // or object with linkage, then look for another declaration with
6296 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6297 //
6298 // If the declaration we're planning to build will be declared with
6299 // external linkage in the translation unit, create any builtin with
6300 // the same name.
6301 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
6302 /* Do nothing*/;
6303 else if (CurContext->isFunctionOrMethod() &&
6304 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
6305 R->isFunctionType())) {
6306 IsLinkageLookup = true;
6307 CreateBuiltins =
6310 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
6311 CreateBuiltins = true;
6312
6313 if (IsLinkageLookup) {
6315 Previous.setRedeclarationKind(
6316 RedeclarationKind::ForExternalRedeclaration);
6317 }
6318
6319 LookupName(Previous, S, CreateBuiltins);
6320 } else { // Something like "int foo::x;"
6322
6323 // C++ [dcl.meaning]p1:
6324 // When the declarator-id is qualified, the declaration shall refer to a
6325 // previously declared member of the class or namespace to which the
6326 // qualifier refers (or, in the case of a namespace, of an element of the
6327 // inline namespace set of that namespace (7.3.1)) or to a specialization
6328 // thereof; [...]
6329 //
6330 // Note that we already checked the context above, and that we do not have
6331 // enough information to make sure that Previous contains the declaration
6332 // we want to match. For example, given:
6333 //
6334 // class X {
6335 // void f();
6336 // void f(float);
6337 // };
6338 //
6339 // void X::f(int) { } // ill-formed
6340 //
6341 // In this case, Previous will point to the overload set
6342 // containing the two f's declared in X, but neither of them
6343 // matches.
6344
6346 }
6347
6348 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6349 TPD && TPD->isTemplateParameter()) {
6350 // Older versions of clang allowed the names of function/variable templates
6351 // to shadow the names of their template parameters. For the compatibility
6352 // purposes we detect such cases and issue a default-to-error warning that
6353 // can be disabled with -Wno-strict-primary-template-shadow.
6354 if (!D.isInvalidType()) {
6355 bool AllowForCompatibility = false;
6356 if (Scope *DeclParent = S->getDeclParent();
6357 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6358 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6359 TemplateParamParent->isDeclScope(TPD);
6360 }
6361 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), TPD,
6362 AllowForCompatibility);
6363 }
6364
6365 // Just pretend that we didn't see the previous declaration.
6366 Previous.clear();
6367 }
6368
6369 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6370 // Forget that the previous declaration is the injected-class-name.
6371 Previous.clear();
6372
6373 // In C++, the previous declaration we find might be a tag type
6374 // (class or enum). In this case, the new declaration will hide the
6375 // tag type. Note that this applies to functions, function templates, and
6376 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6377 if (Previous.isSingleTagDecl() &&
6378 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6379 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6380 Previous.clear();
6381
6382 // Check that there are no default arguments other than in the parameters
6383 // of a function declaration (C++ only).
6384 if (getLangOpts().CPlusPlus)
6386
6387 /// Get the innermost enclosing declaration scope.
6388 S = S->getDeclParent();
6389
6390 NamedDecl *New;
6391
6392 bool AddToScope = true;
6393 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6394 if (TemplateParamLists.size()) {
6395 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6396 return nullptr;
6397 }
6398
6399 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6400 } else if (R->isFunctionType()) {
6401 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6402 TemplateParamLists,
6403 AddToScope);
6404 } else {
6405 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6406 AddToScope);
6407 }
6408
6409 if (!New)
6410 return nullptr;
6411
6412 // If this has an identifier and is not a function template specialization,
6413 // add it to the scope stack.
6414 if (New->getDeclName() && AddToScope)
6415 PushOnScopeChains(New, S);
6416
6417 if (OpenMP().isInOpenMPDeclareTargetContext())
6419
6420 return New;
6421}
6422
6423/// Helper method to turn variable array types into constant array
6424/// types in certain situations which would otherwise be errors (for
6425/// GCC compatibility).
6427 ASTContext &Context,
6428 bool &SizeIsNegative,
6429 llvm::APSInt &Oversized) {
6430 // This method tries to turn a variable array into a constant
6431 // array even when the size isn't an ICE. This is necessary
6432 // for compatibility with code that depends on gcc's buggy
6433 // constant expression folding, like struct {char x[(int)(char*)2];}
6434 SizeIsNegative = false;
6435 Oversized = 0;
6436
6437 if (T->isDependentType())
6438 return QualType();
6439
6441 const Type *Ty = Qs.strip(T);
6442
6443 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6444 QualType Pointee = PTy->getPointeeType();
6445 QualType FixedType =
6446 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6447 Oversized);
6448 if (FixedType.isNull()) return FixedType;
6449 FixedType = Context.getPointerType(FixedType);
6450 return Qs.apply(Context, FixedType);
6451 }
6452 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6453 QualType Inner = PTy->getInnerType();
6454 QualType FixedType =
6455 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6456 Oversized);
6457 if (FixedType.isNull()) return FixedType;
6458 FixedType = Context.getParenType(FixedType);
6459 return Qs.apply(Context, FixedType);
6460 }
6461
6462 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6463 if (!VLATy)
6464 return QualType();
6465
6466 QualType ElemTy = VLATy->getElementType();
6467 if (ElemTy->isVariablyModifiedType()) {
6468 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6469 SizeIsNegative, Oversized);
6470 if (ElemTy.isNull())
6471 return QualType();
6472 }
6473
6475 if (!VLATy->getSizeExpr() ||
6476 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6477 return QualType();
6478
6479 llvm::APSInt Res = Result.Val.getInt();
6480
6481 // Check whether the array size is negative.
6482 if (Res.isSigned() && Res.isNegative()) {
6483 SizeIsNegative = true;
6484 return QualType();
6485 }
6486
6487 // Check whether the array is too large to be addressed.
6488 unsigned ActiveSizeBits =
6489 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6490 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6491 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6492 : Res.getActiveBits();
6493 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6494 Oversized = Res;
6495 return QualType();
6496 }
6497
6498 QualType FoldedArrayType = Context.getConstantArrayType(
6499 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6500 return Qs.apply(Context, FoldedArrayType);
6501}
6502
6503static void
6505 SrcTL = SrcTL.getUnqualifiedLoc();
6506 DstTL = DstTL.getUnqualifiedLoc();
6507 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6508 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6509 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6510 DstPTL.getPointeeLoc());
6511 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6512 return;
6513 }
6514 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6515 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6516 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6517 DstPTL.getInnerLoc());
6518 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6519 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6520 return;
6521 }
6522 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6523 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6524 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6525 TypeLoc DstElemTL = DstATL.getElementLoc();
6526 if (VariableArrayTypeLoc SrcElemATL =
6527 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6528 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6529 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6530 } else {
6531 DstElemTL.initializeFullCopy(SrcElemTL);
6532 }
6533 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6534 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6535 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6536}
6537
6538/// Helper method to turn variable array types into constant array
6539/// types in certain situations which would otherwise be errors (for
6540/// GCC compatibility).
6541static TypeSourceInfo*
6543 ASTContext &Context,
6544 bool &SizeIsNegative,
6545 llvm::APSInt &Oversized) {
6546 QualType FixedTy
6547 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6548 SizeIsNegative, Oversized);
6549 if (FixedTy.isNull())
6550 return nullptr;
6551 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6553 FixedTInfo->getTypeLoc());
6554 return FixedTInfo;
6555}
6556
6559 unsigned FailedFoldDiagID) {
6560 bool SizeIsNegative;
6561 llvm::APSInt Oversized;
6563 TInfo, Context, SizeIsNegative, Oversized);
6564 if (FixedTInfo) {
6565 Diag(Loc, diag::ext_vla_folded_to_constant);
6566 TInfo = FixedTInfo;
6567 T = FixedTInfo->getType();
6568 return true;
6569 }
6570
6571 if (SizeIsNegative)
6572 Diag(Loc, diag::err_typecheck_negative_array_size);
6573 else if (Oversized.getBoolValue())
6574 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6575 else if (FailedFoldDiagID)
6576 Diag(Loc, FailedFoldDiagID);
6577 return false;
6578}
6579
6580void
6582 if (!getLangOpts().CPlusPlus &&
6584 // Don't need to track declarations in the TU in C.
6585 return;
6586
6587 // Note that we have a locally-scoped external with this name.
6589}
6590
6592 // FIXME: We can have multiple results via __attribute__((overloadable)).
6594 return Result.empty() ? nullptr : *Result.begin();
6595}
6596
6598 // FIXME: We should probably indicate the identifier in question to avoid
6599 // confusion for constructs like "virtual int a(), b;"
6600 if (DS.isVirtualSpecified())
6602 diag::err_virtual_non_function);
6603
6604 if (DS.hasExplicitSpecifier())
6606 diag::err_explicit_non_function);
6607
6608 if (DS.isNoreturnSpecified())
6610 diag::err_noreturn_non_function);
6611}
6612
6613NamedDecl*
6616 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6617 if (D.getCXXScopeSpec().isSet()) {
6618 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6619 << D.getCXXScopeSpec().getRange();
6620 D.setInvalidType();
6621 // Pretend we didn't see the scope specifier.
6622 DC = CurContext;
6623 Previous.clear();
6624 }
6625
6626 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6627
6628 if (D.getDeclSpec().isInlineSpecified())
6629 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6630 << getLangOpts().CPlusPlus17;
6631 if (D.getDeclSpec().hasConstexprSpecifier())
6632 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6633 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6634
6635 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
6637 Diag(D.getName().StartLocation,
6638 diag::err_deduction_guide_invalid_specifier)
6639 << "typedef";
6640 else
6641 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6642 << D.getName().getSourceRange();
6643 return nullptr;
6644 }
6645
6646 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6647 if (!NewTD) return nullptr;
6648
6649 // Handle attributes prior to checking for duplicates in MergeVarDecl
6650 ProcessDeclAttributes(S, NewTD, D);
6651
6653
6654 bool Redeclaration = D.isRedeclaration();
6655 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6656 D.setRedeclaration(Redeclaration);
6657 return ND;
6658}
6659
6660void
6662 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6663 // then it shall have block scope.
6664 // Note that variably modified types must be fixed before merging the decl so
6665 // that redeclarations will match.
6666 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6667 QualType T = TInfo->getType();
6668 if (T->isVariablyModifiedType()) {
6670
6671 if (S->getFnParent() == nullptr) {
6672 bool SizeIsNegative;
6673 llvm::APSInt Oversized;
6674 TypeSourceInfo *FixedTInfo =
6676 SizeIsNegative,
6677 Oversized);
6678 if (FixedTInfo) {
6679 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6680 NewTD->setTypeSourceInfo(FixedTInfo);
6681 } else {
6682 if (SizeIsNegative)
6683 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6684 else if (T->isVariableArrayType())
6685 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6686 else if (Oversized.getBoolValue())
6687 Diag(NewTD->getLocation(), diag::err_array_too_large)
6688 << toString(Oversized, 10);
6689 else
6690 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6691 NewTD->setInvalidDecl();
6692 }
6693 }
6694 }
6695}
6696
6697NamedDecl*
6699 LookupResult &Previous, bool &Redeclaration) {
6700
6701 // Find the shadowed declaration before filtering for scope.
6702 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6703
6704 // Merge the decl with the existing one if appropriate. If the decl is
6705 // in an outer scope, it isn't the same thing.
6706 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6707 /*AllowInlineNamespace*/false);
6709 if (!Previous.empty()) {
6710 Redeclaration = true;
6711 MergeTypedefNameDecl(S, NewTD, Previous);
6712 } else {
6714 }
6715
6716 if (ShadowedDecl && !Redeclaration)
6717 CheckShadow(NewTD, ShadowedDecl, Previous);
6718
6719 // If this is the C FILE type, notify the AST context.
6720 if (IdentifierInfo *II = NewTD->getIdentifier())
6721 if (!NewTD->isInvalidDecl() &&
6723 switch (II->getNotableIdentifierID()) {
6724 case tok::NotableIdentifierKind::FILE:
6725 Context.setFILEDecl(NewTD);
6726 break;
6727 case tok::NotableIdentifierKind::jmp_buf:
6728 Context.setjmp_bufDecl(NewTD);
6729 break;
6730 case tok::NotableIdentifierKind::sigjmp_buf:
6732 break;
6733 case tok::NotableIdentifierKind::ucontext_t:
6735 break;
6736 case tok::NotableIdentifierKind::float_t:
6737 case tok::NotableIdentifierKind::double_t:
6738 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6739 break;
6740 default:
6741 break;
6742 }
6743 }
6744
6745 return NewTD;
6746}
6747
6748/// Determines whether the given declaration is an out-of-scope
6749/// previous declaration.
6750///
6751/// This routine should be invoked when name lookup has found a
6752/// previous declaration (PrevDecl) that is not in the scope where a
6753/// new declaration by the same name is being introduced. If the new
6754/// declaration occurs in a local scope, previous declarations with
6755/// linkage may still be considered previous declarations (C99
6756/// 6.2.2p4-5, C++ [basic.link]p6).
6757///
6758/// \param PrevDecl the previous declaration found by name
6759/// lookup
6760///
6761/// \param DC the context in which the new declaration is being
6762/// declared.
6763///
6764/// \returns true if PrevDecl is an out-of-scope previous declaration
6765/// for a new delcaration with the same name.
6766static bool
6768 ASTContext &Context) {
6769 if (!PrevDecl)
6770 return false;
6771
6772 if (!PrevDecl->hasLinkage())
6773 return false;
6774
6775 if (Context.getLangOpts().CPlusPlus) {
6776 // C++ [basic.link]p6:
6777 // If there is a visible declaration of an entity with linkage
6778 // having the same name and type, ignoring entities declared
6779 // outside the innermost enclosing namespace scope, the block
6780 // scope declaration declares that same entity and receives the
6781 // linkage of the previous declaration.
6782 DeclContext *OuterContext = DC->getRedeclContext();
6783 if (!OuterContext->isFunctionOrMethod())
6784 // This rule only applies to block-scope declarations.
6785 return false;
6786
6787 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6788 if (PrevOuterContext->isRecord())
6789 // We found a member function: ignore it.
6790 return false;
6791
6792 // Find the innermost enclosing namespace for the new and
6793 // previous declarations.
6794 OuterContext = OuterContext->getEnclosingNamespaceContext();
6795 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6796
6797 // The previous declaration is in a different namespace, so it
6798 // isn't the same function.
6799 if (!OuterContext->Equals(PrevOuterContext))
6800 return false;
6801 }
6802
6803 return true;
6804}
6805
6807 CXXScopeSpec &SS = D.getCXXScopeSpec();
6808 if (!SS.isSet()) return;
6810}
6811
6813 if (Decl->getType().hasAddressSpace())
6814 return;
6815 if (Decl->getType()->isDependentType())
6816 return;
6817 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6818 QualType Type = Var->getType();
6819 if (Type->isSamplerT() || Type->isVoidType())
6820 return;
6822 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6823 // __opencl_c_program_scope_global_variables feature, the address space
6824 // for a variable at program scope or a static or extern variable inside
6825 // a function are inferred to be __global.
6826 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6827 Var->hasGlobalStorage())
6828 ImplAS = LangAS::opencl_global;
6829 // If the original type from a decayed type is an array type and that array
6830 // type has no address space yet, deduce it now.
6831 if (auto DT = dyn_cast<DecayedType>(Type)) {
6832 auto OrigTy = DT->getOriginalType();
6833 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6834 // Add the address space to the original array type and then propagate
6835 // that to the element type through `getAsArrayType`.
6836 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6837 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6838 // Re-generate the decayed type.
6839 Type = Context.getDecayedType(OrigTy);
6840 }
6841 }
6843 // Apply any qualifiers (including address space) from the array type to
6844 // the element type. This implements C99 6.7.3p8: "If the specification of
6845 // an array type includes any type qualifiers, the element type is so
6846 // qualified, not the array type."
6847 if (Type->isArrayType())
6849 Decl->setType(Type);
6850 }
6851}
6852
6854 // Ensure that an auto decl is deduced otherwise the checks below might cache
6855 // the wrong linkage.
6856 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6857
6858 // 'weak' only applies to declarations with external linkage.
6859 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6860 if (!ND.isExternallyVisible()) {
6861 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6862 ND.dropAttr<WeakAttr>();
6863 }
6864 }
6865 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6866 if (ND.isExternallyVisible()) {
6867 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6868 ND.dropAttrs<WeakRefAttr, AliasAttr>();
6869 }
6870 }
6871
6872 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6873 if (VD->hasInit()) {
6874 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6875 assert(VD->isThisDeclarationADefinition() &&
6876 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6877 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6878 VD->dropAttr<AliasAttr>();
6879 }
6880 }
6881 }
6882
6883 // 'selectany' only applies to externally visible variable declarations.
6884 // It does not apply to functions.
6885 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6886 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6887 S.Diag(Attr->getLocation(),
6888 diag::err_attribute_selectany_non_extern_data);
6889 ND.dropAttr<SelectAnyAttr>();
6890 }
6891 }
6892
6893 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6894 auto *VD = dyn_cast<VarDecl>(&ND);
6895 bool IsAnonymousNS = false;
6896 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6897 if (VD) {
6898 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6899 while (NS && !IsAnonymousNS) {
6900 IsAnonymousNS = NS->isAnonymousNamespace();
6901 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6902 }
6903 }
6904 // dll attributes require external linkage. Static locals may have external
6905 // linkage but still cannot be explicitly imported or exported.
6906 // In Microsoft mode, a variable defined in anonymous namespace must have
6907 // external linkage in order to be exported.
6908 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6909 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6910 (!AnonNSInMicrosoftMode &&
6911 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6912 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6913 << &ND << Attr;
6914 ND.setInvalidDecl();
6915 }
6916 }
6917
6918 // Check the attributes on the function type, if any.
6919 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6920 // Don't declare this variable in the second operand of the for-statement;
6921 // GCC miscompiles that by ending its lifetime before evaluating the
6922 // third operand. See gcc.gnu.org/PR86769.
6924 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6925 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6926 TL = ATL.getModifiedLoc()) {
6927 // The [[lifetimebound]] attribute can be applied to the implicit object
6928 // parameter of a non-static member function (other than a ctor or dtor)
6929 // by applying it to the function type.
6930 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6931 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6932 if (!MD || MD->isStatic()) {
6933 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6934 << !MD << A->getRange();
6935 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6936 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6937 << isa<CXXDestructorDecl>(MD) << A->getRange();
6938 }
6939 }
6940 }
6941 }
6942}
6943
6945 NamedDecl *NewDecl,
6946 bool IsSpecialization,
6947 bool IsDefinition) {
6948 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6949 return;
6950
6951 bool IsTemplate = false;
6952 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6953 OldDecl = OldTD->getTemplatedDecl();
6954 IsTemplate = true;
6955 if (!IsSpecialization)
6956 IsDefinition = false;
6957 }
6958 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6959 NewDecl = NewTD->getTemplatedDecl();
6960 IsTemplate = true;
6961 }
6962
6963 if (!OldDecl || !NewDecl)
6964 return;
6965
6966 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6967 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6968 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6969 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6970
6971 // dllimport and dllexport are inheritable attributes so we have to exclude
6972 // inherited attribute instances.
6973 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6974 (NewExportAttr && !NewExportAttr->isInherited());
6975
6976 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6977 // the only exception being explicit specializations.
6978 // Implicitly generated declarations are also excluded for now because there
6979 // is no other way to switch these to use dllimport or dllexport.
6980 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6981
6982 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6983 // Allow with a warning for free functions and global variables.
6984 bool JustWarn = false;
6985 if (!OldDecl->isCXXClassMember()) {
6986 auto *VD = dyn_cast<VarDecl>(OldDecl);
6987 if (VD && !VD->getDescribedVarTemplate())
6988 JustWarn = true;
6989 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6990 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6991 JustWarn = true;
6992 }
6993
6994 // We cannot change a declaration that's been used because IR has already
6995 // been emitted. Dllimported functions will still work though (modulo
6996 // address equality) as they can use the thunk.
6997 if (OldDecl->isUsed())
6998 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6999 JustWarn = false;
7000
7001 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7002 : diag::err_attribute_dll_redeclaration;
7003 S.Diag(NewDecl->getLocation(), DiagID)
7004 << NewDecl
7005 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7006 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7007 if (!JustWarn) {
7008 NewDecl->setInvalidDecl();
7009 return;
7010 }
7011 }
7012
7013 // A redeclaration is not allowed to drop a dllimport attribute, the only
7014 // exceptions being inline function definitions (except for function
7015 // templates), local extern declarations, qualified friend declarations or
7016 // special MSVC extension: in the last case, the declaration is treated as if
7017 // it were marked dllexport.
7018 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7019 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7020 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7021 // Ignore static data because out-of-line definitions are diagnosed
7022 // separately.
7023 IsStaticDataMember = VD->isStaticDataMember();
7024 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7026 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7027 IsInline = FD->isInlined();
7028 IsQualifiedFriend = FD->getQualifier() &&
7029 FD->getFriendObjectKind() == Decl::FOK_Declared;
7030 }
7031
7032 if (OldImportAttr && !HasNewAttr &&
7033 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7034 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7035 if (IsMicrosoftABI && IsDefinition) {
7036 if (IsSpecialization) {
7037 S.Diag(
7038 NewDecl->getLocation(),
7039 diag::err_attribute_dllimport_function_specialization_definition);
7040 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7041 NewDecl->dropAttr<DLLImportAttr>();
7042 } else {
7043 S.Diag(NewDecl->getLocation(),
7044 diag::warn_redeclaration_without_import_attribute)
7045 << NewDecl;
7046 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7047 NewDecl->dropAttr<DLLImportAttr>();
7048 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7049 S.Context, NewImportAttr->getRange()));
7050 }
7051 } else if (IsMicrosoftABI && IsSpecialization) {
7052 assert(!IsDefinition);
7053 // MSVC allows this. Keep the inherited attribute.
7054 } else {
7055 S.Diag(NewDecl->getLocation(),
7056 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7057 << NewDecl << OldImportAttr;
7058 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7059 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7060 OldDecl->dropAttr<DLLImportAttr>();
7061 NewDecl->dropAttr<DLLImportAttr>();
7062 }
7063 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7064 // In MinGW, seeing a function declared inline drops the dllimport
7065 // attribute.
7066 OldDecl->dropAttr<DLLImportAttr>();
7067 NewDecl->dropAttr<DLLImportAttr>();
7068 S.Diag(NewDecl->getLocation(),
7069 diag::warn_dllimport_dropped_from_inline_function)
7070 << NewDecl << OldImportAttr;
7071 }
7072
7073 // A specialization of a class template member function is processed here
7074 // since it's a redeclaration. If the parent class is dllexport, the
7075 // specialization inherits that attribute. This doesn't happen automatically
7076 // since the parent class isn't instantiated until later.
7077 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7078 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7079 !NewImportAttr && !NewExportAttr) {
7080 if (const DLLExportAttr *ParentExportAttr =
7081 MD->getParent()->getAttr<DLLExportAttr>()) {
7082 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7083 NewAttr->setInherited(true);
7084 NewDecl->addAttr(NewAttr);
7085 }
7086 }
7087 }
7088}
7089
7090/// Given that we are within the definition of the given function,
7091/// will that definition behave like C99's 'inline', where the
7092/// definition is discarded except for optimization purposes?
7094 // Try to avoid calling GetGVALinkageForFunction.
7095
7096 // All cases of this require the 'inline' keyword.
7097 if (!FD->isInlined()) return false;
7098
7099 // This is only possible in C++ with the gnu_inline attribute.
7100 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7101 return false;
7102
7103 // Okay, go ahead and call the relatively-more-expensive function.
7105}
7106
7107/// Determine whether a variable is extern "C" prior to attaching
7108/// an initializer. We can't just call isExternC() here, because that
7109/// will also compute and cache whether the declaration is externally
7110/// visible, which might change when we attach the initializer.
7111///
7112/// This can only be used if the declaration is known to not be a
7113/// redeclaration of an internal linkage declaration.
7114///
7115/// For instance:
7116///
7117/// auto x = []{};
7118///
7119/// Attaching the initializer here makes this declaration not externally
7120/// visible, because its type has internal linkage.
7121///
7122/// FIXME: This is a hack.
7123template<typename T>
7124static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7125 if (S.getLangOpts().CPlusPlus) {
7126 // In C++, the overloadable attribute negates the effects of extern "C".
7127 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7128 return false;
7129
7130 // So do CUDA's host/device attributes.
7131 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7132 D->template hasAttr<CUDAHostAttr>()))
7133 return false;
7134 }
7135 return D->isExternC();
7136}
7137
7138static bool shouldConsiderLinkage(const VarDecl *VD) {
7139 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7140 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
7141 isa<OMPDeclareMapperDecl>(DC))
7142 return VD->hasExternalStorage();
7143 if (DC->isFileContext())
7144 return true;
7145 if (DC->isRecord())
7146 return false;
7147 if (DC->getDeclKind() == Decl::HLSLBuffer)
7148 return false;
7149
7150 if (isa<RequiresExprBodyDecl>(DC))
7151 return false;
7152 llvm_unreachable("Unexpected context");
7153}
7154
7155static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7156 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7157 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7158 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
7159 return true;
7160 if (DC->isRecord())
7161 return false;
7162 llvm_unreachable("Unexpected context");
7163}
7164
7165static bool hasParsedAttr(Scope *S, const Declarator &PD,
7166 ParsedAttr::Kind Kind) {
7167 // Check decl attributes on the DeclSpec.
7168 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7169 return true;
7170
7171 // Walk the declarator structure, checking decl attributes that were in a type
7172 // position to the decl itself.
7173 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7174 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7175 return true;
7176 }
7177
7178 // Finally, check attributes on the decl itself.
7179 return PD.getAttributes().hasAttribute(Kind) ||
7181}
7182
7184 if (!DC->isFunctionOrMethod())
7185 return false;
7186
7187 // If this is a local extern function or variable declared within a function
7188 // template, don't add it into the enclosing namespace scope until it is
7189 // instantiated; it might have a dependent type right now.
7190 if (DC->isDependentContext())
7191 return true;
7192
7193 // C++11 [basic.link]p7:
7194 // When a block scope declaration of an entity with linkage is not found to
7195 // refer to some other declaration, then that entity is a member of the
7196 // innermost enclosing namespace.
7197 //
7198 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7199 // semantically-enclosing namespace, not a lexically-enclosing one.
7200 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7201 DC = DC->getParent();
7202 return true;
7203}
7204
7205/// Returns true if given declaration has external C language linkage.
7206static bool isDeclExternC(const Decl *D) {
7207 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7208 return FD->isExternC();
7209 if (const auto *VD = dyn_cast<VarDecl>(D))
7210 return VD->isExternC();
7211
7212 llvm_unreachable("Unknown type of decl!");
7213}
7214
7215/// Returns true if there hasn't been any invalid type diagnosed.
7216static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7217 DeclContext *DC = NewVD->getDeclContext();
7218 QualType R = NewVD->getType();
7219
7220 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7221 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7222 // argument.
7223 if (R->isImageType() || R->isPipeType()) {
7224 Se.Diag(NewVD->getLocation(),
7225 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7226 << R;
7227 NewVD->setInvalidDecl();
7228 return false;
7229 }
7230
7231 // OpenCL v1.2 s6.9.r:
7232 // The event type cannot be used to declare a program scope variable.
7233 // OpenCL v2.0 s6.9.q:
7234 // The clk_event_t and reserve_id_t types cannot be declared in program
7235 // scope.
7236 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7237 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7238 Se.Diag(NewVD->getLocation(),
7239 diag::err_invalid_type_for_program_scope_var)
7240 << R;
7241 NewVD->setInvalidDecl();
7242 return false;
7243 }
7244 }
7245
7246 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7247 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7248 Se.getLangOpts())) {
7249 QualType NR = R.getCanonicalType();
7250 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7251 NR->isReferenceType()) {
7254 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7255 << NR->isReferenceType();
7256 NewVD->setInvalidDecl();
7257 return false;
7258 }
7259 NR = NR->getPointeeType();
7260 }
7261 }
7262
7263 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7264 Se.getLangOpts())) {
7265 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7266 // half array type (unless the cl_khr_fp16 extension is enabled).
7267 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7268 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7269 NewVD->setInvalidDecl();
7270 return false;
7271 }
7272 }
7273
7274 // OpenCL v1.2 s6.9.r:
7275 // The event type cannot be used with the __local, __constant and __global
7276 // address space qualifiers.
7277 if (R->isEventT()) {
7279 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7280 NewVD->setInvalidDecl();
7281 return false;
7282 }
7283 }
7284
7285 if (R->isSamplerT()) {
7286 // OpenCL v1.2 s6.9.b p4:
7287 // The sampler type cannot be used with the __local and __global address
7288 // space qualifiers.
7291 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7292 NewVD->setInvalidDecl();
7293 }
7294
7295 // OpenCL v1.2 s6.12.14.1:
7296 // A global sampler must be declared with either the constant address
7297 // space qualifier or with the const qualifier.
7298 if (DC->isTranslationUnit() &&
7300 R.isConstQualified())) {
7301 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7302 NewVD->setInvalidDecl();
7303 }
7304 if (NewVD->isInvalidDecl())
7305 return false;
7306 }
7307
7308 return true;
7309}
7310
7311template <typename AttrTy>
7312static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7313 const TypedefNameDecl *TND = TT->getDecl();
7314 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7315 AttrTy *Clone = Attribute->clone(S.Context);
7316 Clone->setInherited(true);
7317 D->addAttr(Clone);
7318 }
7319}
7320
7321// This function emits warning and a corresponding note based on the
7322// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7323// declarations of an annotated type must be const qualified.
7325 QualType VarType = VD->getType().getCanonicalType();
7326
7327 // Ignore local declarations (for now) and those with const qualification.
7328 // TODO: Local variables should not be allowed if their type declaration has
7329 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7330 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7331 return;
7332
7333 if (VarType->isArrayType()) {
7334 // Retrieve element type for array declarations.
7335 VarType = S.getASTContext().getBaseElementType(VarType);
7336 }
7337
7338 const RecordDecl *RD = VarType->getAsRecordDecl();
7339
7340 // Check if the record declaration is present and if it has any attributes.
7341 if (RD == nullptr)
7342 return;
7343
7344 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7345 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7346 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7347 return;
7348 }
7349}
7350
7352 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7353 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7354 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7355 QualType R = TInfo->getType();
7357
7358 IdentifierInfo *II = Name.getAsIdentifierInfo();
7359 bool IsPlaceholderVariable = false;
7360
7361 if (D.isDecompositionDeclarator()) {
7362 // Take the name of the first declarator as our name for diagnostic
7363 // purposes.
7364 auto &Decomp = D.getDecompositionDeclarator();
7365 if (!Decomp.bindings().empty()) {
7366 II = Decomp.bindings()[0].Name;
7367 Name = II;
7368 }
7369 } else if (!II) {
7370 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7371 return nullptr;
7372 }
7373
7374
7375 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
7377
7378 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7379 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7380 IsPlaceholderVariable = true;
7381 if (!Previous.empty()) {
7382 NamedDecl *PrevDecl = *Previous.begin();
7383 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7384 DC->getRedeclContext());
7385 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false))
7386 DiagPlaceholderVariableDefinition(D.getIdentifierLoc());
7387 }
7388 }
7389
7390 // dllimport globals without explicit storage class are treated as extern. We
7391 // have to change the storage class this early to get the right DeclContext.
7392 if (SC == SC_None && !DC->isRecord() &&
7393 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7394 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7395 SC = SC_Extern;
7396
7397 DeclContext *OriginalDC = DC;
7398 bool IsLocalExternDecl = SC == SC_Extern &&
7400
7401 if (SCSpec == DeclSpec::SCS_mutable) {
7402 // mutable can only appear on non-static class members, so it's always
7403 // an error here
7404 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7405 D.setInvalidType();
7406 SC = SC_None;
7407 }
7408
7409 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7410 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7411 D.getDeclSpec().getStorageClassSpecLoc())) {
7412 // In C++11, the 'register' storage class specifier is deprecated.
7413 // Suppress the warning in system macros, it's used in macros in some
7414 // popular C system headers, such as in glibc's htonl() macro.
7415 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7416 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7417 : diag::warn_deprecated_register)
7418 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7419 }
7420
7421 DiagnoseFunctionSpecifiers(D.getDeclSpec());
7422
7423 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7424 // C99 6.9p2: The storage-class specifiers auto and register shall not
7425 // appear in the declaration specifiers in an external declaration.
7426 // Global Register+Asm is a GNU extension we support.
7427 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7428 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7429 D.setInvalidType();
7430 }
7431 }
7432
7433 // If this variable has a VLA type and an initializer, try to
7434 // fold to a constant-sized type. This is otherwise invalid.
7435 if (D.hasInitializer() && R->isVariableArrayType())
7436 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7437 /*DiagID=*/0);
7438
7439 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7440 const AutoType *AT = TL.getTypePtr();
7441 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7442 }
7443
7444 bool IsMemberSpecialization = false;
7445 bool IsVariableTemplateSpecialization = false;
7446 bool IsPartialSpecialization = false;
7447 bool IsVariableTemplate = false;
7448 VarDecl *NewVD = nullptr;
7449 VarTemplateDecl *NewTemplate = nullptr;
7450 TemplateParameterList *TemplateParams = nullptr;
7451 if (!getLangOpts().CPlusPlus) {
7452 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7453 II, R, TInfo, SC);
7454
7455 if (R->getContainedDeducedType())
7456 ParsingInitForAutoVars.insert(NewVD);
7457
7458 if (D.isInvalidType())
7459 NewVD->setInvalidDecl();
7460
7462 NewVD->hasLocalStorage())
7463 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7465 } else {
7466 bool Invalid = false;
7467 // Match up the template parameter lists with the scope specifier, then
7468 // determine whether we have a template or a template specialization.
7470 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7471 D.getCXXScopeSpec(),
7473 ? D.getName().TemplateId
7474 : nullptr,
7475 TemplateParamLists,
7476 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7477
7478 if (TemplateParams) {
7479 if (!TemplateParams->size() &&
7481 // There is an extraneous 'template<>' for this variable. Complain
7482 // about it, but allow the declaration of the variable.
7483 Diag(TemplateParams->getTemplateLoc(),
7484 diag::err_template_variable_noparams)
7485 << II
7486 << SourceRange(TemplateParams->getTemplateLoc(),
7487 TemplateParams->getRAngleLoc());
7488 TemplateParams = nullptr;
7489 } else {
7490 // Check that we can declare a template here.
7491 if (CheckTemplateDeclScope(S, TemplateParams))
7492 return nullptr;
7493
7494 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7495 // This is an explicit specialization or a partial specialization.
7496 IsVariableTemplateSpecialization = true;
7497 IsPartialSpecialization = TemplateParams->size() > 0;
7498 } else { // if (TemplateParams->size() > 0)
7499 // This is a template declaration.
7500 IsVariableTemplate = true;
7501
7502 // Only C++1y supports variable templates (N3651).
7503 Diag(D.getIdentifierLoc(),
7505 ? diag::warn_cxx11_compat_variable_template
7506 : diag::ext_variable_template);
7507 }
7508 }
7509 } else {
7510 // Check that we can declare a member specialization here.
7511 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7512 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7513 return nullptr;
7514 assert((Invalid ||
7515 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
7516 "should have a 'template<>' for this decl");
7517 }
7518
7519 bool IsExplicitSpecialization =
7520 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7521
7522 // C++ [temp.expl.spec]p2:
7523 // The declaration in an explicit-specialization shall not be an
7524 // export-declaration. An explicit specialization shall not use a
7525 // storage-class-specifier other than thread_local.
7526 //
7527 // We use the storage-class-specifier from DeclSpec because we may have
7528 // added implicit 'extern' for declarations with __declspec(dllimport)!
7529 if (SCSpec != DeclSpec::SCS_unspecified &&
7530 (IsExplicitSpecialization || IsMemberSpecialization)) {
7531 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7532 diag::ext_explicit_specialization_storage_class)
7533 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7534 }
7535
7536 if (CurContext->isRecord()) {
7537 if (SC == SC_Static) {
7538 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7539 // Walk up the enclosing DeclContexts to check for any that are
7540 // incompatible with static data members.
7541 const DeclContext *FunctionOrMethod = nullptr;
7542 const CXXRecordDecl *AnonStruct = nullptr;
7543 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7544 if (Ctxt->isFunctionOrMethod()) {
7545 FunctionOrMethod = Ctxt;
7546 break;
7547 }
7548 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7549 if (ParentDecl && !ParentDecl->getDeclName()) {
7550 AnonStruct = ParentDecl;
7551 break;
7552 }
7553 }
7554 if (FunctionOrMethod) {
7555 // C++ [class.static.data]p5: A local class shall not have static
7556 // data members.
7557 Diag(D.getIdentifierLoc(),
7558 diag::err_static_data_member_not_allowed_in_local_class)
7559 << Name << RD->getDeclName()
7560 << llvm::to_underlying(RD->getTagKind());
7561 } else if (AnonStruct) {
7562 // C++ [class.static.data]p4: Unnamed classes and classes contained
7563 // directly or indirectly within unnamed classes shall not contain
7564 // static data members.
7565 Diag(D.getIdentifierLoc(),
7566 diag::err_static_data_member_not_allowed_in_anon_struct)
7567 << Name << llvm::to_underlying(AnonStruct->getTagKind());
7568 Invalid = true;
7569 } else if (RD->isUnion()) {
7570 // C++98 [class.union]p1: If a union contains a static data member,
7571 // the program is ill-formed. C++11 drops this restriction.
7572 Diag(D.getIdentifierLoc(),
7574 ? diag::warn_cxx98_compat_static_data_member_in_union
7575 : diag::ext_static_data_member_in_union)
7576 << Name;
7577 }
7578 }
7579 } else if (IsVariableTemplate || IsPartialSpecialization) {
7580 // There is no such thing as a member field template.
7581 Diag(D.getIdentifierLoc(), diag::err_template_member)
7582 << II << TemplateParams->getSourceRange();
7583 // Recover by pretending this is a static data member template.
7584 SC = SC_Static;
7585 }
7586 } else if (DC->isRecord()) {
7587 // This is an out-of-line definition of a static data member.
7588 switch (SC) {
7589 case SC_None:
7590 break;
7591 case SC_Static:
7592 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7593 diag::err_static_out_of_line)
7595 D.getDeclSpec().getStorageClassSpecLoc());
7596 break;
7597 case SC_Auto:
7598 case SC_Register:
7599 case SC_Extern:
7600 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7601 // to names of variables declared in a block or to function parameters.
7602 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7603 // of class members
7604
7605 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7606 diag::err_storage_class_for_static_member)
7608 D.getDeclSpec().getStorageClassSpecLoc());
7609 break;
7610 case SC_PrivateExtern:
7611 llvm_unreachable("C storage class in c++!");
7612 }
7613 }
7614
7615 if (IsVariableTemplateSpecialization) {
7616 SourceLocation TemplateKWLoc =
7617 TemplateParamLists.size() > 0
7618 ? TemplateParamLists[0]->getTemplateLoc()
7619 : SourceLocation();
7621 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
7623 if (Res.isInvalid())
7624 return nullptr;
7625 NewVD = cast<VarDecl>(Res.get());
7626 AddToScope = false;
7627 } else if (D.isDecompositionDeclarator()) {
7629 D.getIdentifierLoc(), R, TInfo, SC,
7630 Bindings);
7631 } else
7632 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7633 D.getIdentifierLoc(), II, R, TInfo, SC);
7634
7635 // If this is supposed to be a variable template, create it as such.
7636 if (IsVariableTemplate) {
7637 NewTemplate =
7638 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7639 TemplateParams, NewVD);
7640 NewVD->setDescribedVarTemplate(NewTemplate);
7641 }
7642
7643 // If this decl has an auto type in need of deduction, make a note of the
7644 // Decl so we can diagnose uses of it in its own initializer.
7645 if (R->getContainedDeducedType())
7646 ParsingInitForAutoVars.insert(NewVD);
7647
7648 if (D.isInvalidType() || Invalid) {
7649 NewVD->setInvalidDecl();
7650 if (NewTemplate)
7651 NewTemplate->setInvalidDecl();
7652 }
7653
7654 SetNestedNameSpecifier(*this, NewVD, D);
7655
7656 // If we have any template parameter lists that don't directly belong to
7657 // the variable (matching the scope specifier), store them.
7658 // An explicit variable template specialization does not own any template
7659 // parameter lists.
7660 unsigned VDTemplateParamLists =
7661 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
7662 if (TemplateParamLists.size() > VDTemplateParamLists)
7664 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7665 }
7666
7667 if (D.getDeclSpec().isInlineSpecified()) {
7668 if (!getLangOpts().CPlusPlus) {
7669 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7670 << 0;
7671 } else if (CurContext->isFunctionOrMethod()) {
7672 // 'inline' is not allowed on block scope variable declaration.
7673 Diag(D.getDeclSpec().getInlineSpecLoc(),
7674 diag::err_inline_declaration_block_scope) << Name
7675 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7676 } else {
7677 Diag(D.getDeclSpec().getInlineSpecLoc(),
7678 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7679 : diag::ext_inline_variable);
7680 NewVD->setInlineSpecified();
7681 }
7682 }
7683
7684 // Set the lexical context. If the declarator has a C++ scope specifier, the
7685 // lexical context will be different from the semantic context.
7687 if (NewTemplate)
7688 NewTemplate->setLexicalDeclContext(CurContext);
7689
7690 if (IsLocalExternDecl) {
7691 if (D.isDecompositionDeclarator())
7692 for (auto *B : Bindings)
7693 B->setLocalExternDecl();
7694 else
7695 NewVD->setLocalExternDecl();
7696 }
7697
7698 bool EmitTLSUnsupportedError = false;
7699 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7700 // C++11 [dcl.stc]p4:
7701 // When thread_local is applied to a variable of block scope the
7702 // storage-class-specifier static is implied if it does not appear
7703 // explicitly.
7704 // Core issue: 'static' is not implied if the variable is declared
7705 // 'extern'.
7706 if (NewVD->hasLocalStorage() &&
7707 (SCSpec != DeclSpec::SCS_unspecified ||
7709 !DC->isFunctionOrMethod()))
7710 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7711 diag::err_thread_non_global)
7713 else if (!Context.getTargetInfo().isTLSSupported()) {
7714 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7715 getLangOpts().SYCLIsDevice) {
7716 // Postpone error emission until we've collected attributes required to
7717 // figure out whether it's a host or device variable and whether the
7718 // error should be ignored.
7719 EmitTLSUnsupportedError = true;
7720 // We still need to mark the variable as TLS so it shows up in AST with
7721 // proper storage class for other tools to use even if we're not going
7722 // to emit any code for it.
7723 NewVD->setTSCSpec(TSCS);
7724 } else
7725 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7726 diag::err_thread_unsupported);
7727 } else
7728 NewVD->setTSCSpec(TSCS);
7729 }
7730
7731 switch (D.getDeclSpec().getConstexprSpecifier()) {
7733 break;
7734
7736 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7737 diag::err_constexpr_wrong_decl_kind)
7738 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7739 [[fallthrough]];
7740
7742 NewVD->setConstexpr(true);
7743 // C++1z [dcl.spec.constexpr]p1:
7744 // A static data member declared with the constexpr specifier is
7745 // implicitly an inline variable.
7746 if (NewVD->isStaticDataMember() &&
7747 (getLangOpts().CPlusPlus17 ||
7749 NewVD->setImplicitlyInline();
7750 break;
7751
7753 if (!NewVD->hasGlobalStorage())
7754 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7755 diag::err_constinit_local_variable);
7756 else
7757 NewVD->addAttr(
7758 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
7759 ConstInitAttr::Keyword_constinit));
7760 break;
7761 }
7762
7763 // C99 6.7.4p3
7764 // An inline definition of a function with external linkage shall
7765 // not contain a definition of a modifiable object with static or
7766 // thread storage duration...
7767 // We only apply this when the function is required to be defined
7768 // elsewhere, i.e. when the function is not 'extern inline'. Note
7769 // that a local variable with thread storage duration still has to
7770 // be marked 'static'. Also note that it's possible to get these
7771 // semantics in C++ using __attribute__((gnu_inline)).
7772 if (SC == SC_Static && S->getFnParent() != nullptr &&
7773 !NewVD->getType().isConstQualified()) {
7775 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7776 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7777 diag::warn_static_local_in_extern_inline);
7779 }
7780 }
7781
7782 if (D.getDeclSpec().isModulePrivateSpecified()) {
7783 if (IsVariableTemplateSpecialization)
7784 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7785 << (IsPartialSpecialization ? 1 : 0)
7787 D.getDeclSpec().getModulePrivateSpecLoc());
7788 else if (IsMemberSpecialization)
7789 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7790 << 2
7791 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7792 else if (NewVD->hasLocalStorage())
7793 Diag(NewVD->getLocation(), diag::err_module_private_local)
7794 << 0 << NewVD
7795 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7797 D.getDeclSpec().getModulePrivateSpecLoc());
7798 else {
7799 NewVD->setModulePrivate();
7800 if (NewTemplate)
7801 NewTemplate->setModulePrivate();
7802 for (auto *B : Bindings)
7803 B->setModulePrivate();
7804 }
7805 }
7806
7807 if (getLangOpts().OpenCL) {
7809
7810 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7811 if (TSC != TSCS_unspecified) {
7812 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7813 diag::err_opencl_unknown_type_specifier)
7815 << DeclSpec::getSpecifierName(TSC) << 1;
7816 NewVD->setInvalidDecl();
7817 }
7818 }
7819
7820 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
7821 // address space if the table has local storage (semantic checks elsewhere
7822 // will produce an error anyway).
7823 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
7824 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
7825 !NewVD->hasLocalStorage()) {
7828 NewVD->setType(Type);
7829 }
7830 }
7831
7832 // Handle attributes prior to checking for duplicates in MergeVarDecl
7833 ProcessDeclAttributes(S, NewVD, D);
7834
7835 // FIXME: This is probably the wrong location to be doing this and we should
7836 // probably be doing this for more attributes (especially for function
7837 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7838 // the code to copy attributes would be generated by TableGen.
7839 if (R->isFunctionPointerType())
7840 if (const auto *TT = R->getAs<TypedefType>())
7841 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7842
7843 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice ||
7844 getLangOpts().SYCLIsDevice) {
7845 if (EmitTLSUnsupportedError &&
7847 (getLangOpts().OpenMPIsTargetDevice &&
7848 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7849 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7850 diag::err_thread_unsupported);
7851
7852 if (EmitTLSUnsupportedError &&
7853 (LangOpts.SYCLIsDevice ||
7854 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
7855 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7856 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7857 // storage [duration]."
7858 if (SC == SC_None && S->getFnParent() != nullptr &&
7859 (NewVD->hasAttr<CUDASharedAttr>() ||
7860 NewVD->hasAttr<CUDAConstantAttr>())) {
7861 NewVD->setStorageClass(SC_Static);
7862 }
7863 }
7864
7865 // Ensure that dllimport globals without explicit storage class are treated as
7866 // extern. The storage class is set above using parsed attributes. Now we can
7867 // check the VarDecl itself.
7868 assert(!NewVD->hasAttr<DLLImportAttr>() ||
7869 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7870 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7871
7872 // In auto-retain/release, infer strong retension for variables of
7873 // retainable type.
7874 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
7875 NewVD->setInvalidDecl();
7876
7877 // Handle GNU asm-label extension (encoded as an attribute).
7878 if (Expr *E = (Expr*)D.getAsmLabel()) {
7879 // The parser guarantees this is a string.
7880 StringLiteral *SE = cast<StringLiteral>(E);
7881 StringRef Label = SE->getString();
7882 if (S->getFnParent() != nullptr) {
7883 switch (SC) {
7884 case SC_None:
7885 case SC_Auto:
7886 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7887 break;
7888 case SC_Register:
7889 // Local Named register
7892 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7893 break;
7894 case SC_Static:
7895 case SC_Extern:
7896 case SC_PrivateExtern:
7897 break;
7898 }
7899 } else if (SC == SC_Register) {
7900 // Global Named register
7901 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7902 const auto &TI = Context.getTargetInfo();
7903 bool HasSizeMismatch;
7904
7905 if (!TI.isValidGCCRegisterName(Label))
7906 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7907 else if (!TI.validateGlobalRegisterVariable(Label,
7909 HasSizeMismatch))
7910 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7911 else if (HasSizeMismatch)
7912 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7913 }
7914
7915 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7916 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7917 NewVD->setInvalidDecl(true);
7918 }
7919 }
7920
7921 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7922 /*IsLiteralLabel=*/true,
7923 SE->getStrTokenLoc(0)));
7924 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7925 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7927 if (I != ExtnameUndeclaredIdentifiers.end()) {
7928 if (isDeclExternC(NewVD)) {
7929 NewVD->addAttr(I->second);
7931 } else
7932 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7933 << /*Variable*/1 << NewVD;
7934 }
7935 }
7936
7937 // Find the shadowed declaration before filtering for scope.
7938 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7940 : nullptr;
7941
7942 // Don't consider existing declarations that are in a different
7943 // scope and are out-of-semantic-context declarations (if the new
7944 // declaration has linkage).
7946 D.getCXXScopeSpec().isNotEmpty() ||
7947 IsMemberSpecialization ||
7948 IsVariableTemplateSpecialization);
7949
7950 // Check whether the previous declaration is in the same block scope. This
7951 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7952 if (getLangOpts().CPlusPlus &&
7953 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7955 Previous.isSingleResult() && !Previous.isShadowed() &&
7956 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7957
7958 if (!getLangOpts().CPlusPlus) {
7959 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7960 } else {
7961 // If this is an explicit specialization of a static data member, check it.
7962 if (IsMemberSpecialization && !IsVariableTemplateSpecialization &&
7964 NewVD->setInvalidDecl();
7965
7966 // Merge the decl with the existing one if appropriate.
7967 if (!Previous.empty()) {
7968 if (Previous.isSingleResult() &&
7969 isa<FieldDecl>(Previous.getFoundDecl()) &&
7970 D.getCXXScopeSpec().isSet()) {
7971 // The user tried to define a non-static data member
7972 // out-of-line (C++ [dcl.meaning]p1).
7973 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7974 << D.getCXXScopeSpec().getRange();
7975 Previous.clear();
7976 NewVD->setInvalidDecl();
7977 }
7978 } else if (D.getCXXScopeSpec().isSet() &&
7979 !IsVariableTemplateSpecialization) {
7980 // No previous declaration in the qualifying scope.
7981 Diag(D.getIdentifierLoc(), diag::err_no_member)
7982 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7983 << D.getCXXScopeSpec().getRange();
7984 NewVD->setInvalidDecl();
7985 }
7986
7987 if (!IsPlaceholderVariable)
7988 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7989
7990 // CheckVariableDeclaration will set NewVD as invalid if something is in
7991 // error like WebAssembly tables being declared as arrays with a non-zero
7992 // size, but then parsing continues and emits further errors on that line.
7993 // To avoid that we check here if it happened and return nullptr.
7994 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
7995 return nullptr;
7996
7997 if (NewTemplate) {
7998 VarTemplateDecl *PrevVarTemplate =
7999 NewVD->getPreviousDecl()
8001 : nullptr;
8002
8003 // Check the template parameter list of this declaration, possibly
8004 // merging in the template parameter list from the previous variable
8005 // template declaration.
8007 TemplateParams,
8008 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8009 : nullptr,
8010 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8011 DC->isDependentContext())
8013 : TPC_VarTemplate))
8014 NewVD->setInvalidDecl();
8015
8016 // If we are providing an explicit specialization of a static variable
8017 // template, make a note of that.
8018 if (PrevVarTemplate &&
8019 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8020 PrevVarTemplate->setMemberSpecialization();
8021 }
8022 }
8023
8024 // Diagnose shadowed variables iff this isn't a redeclaration.
8025 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8026 CheckShadow(NewVD, ShadowedDecl, Previous);
8027
8028 ProcessPragmaWeak(S, NewVD);
8029
8030 // If this is the first declaration of an extern C variable, update
8031 // the map of such variables.
8032 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8033 isIncompleteDeclExternC(*this, NewVD))
8035
8036 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8038 Decl *ManglingContextDecl;
8039 std::tie(MCtx, ManglingContextDecl) =
8041 if (MCtx) {
8043 NewVD, MCtx->getManglingNumber(
8044 NewVD, getMSManglingNumber(getLangOpts(), S)));
8046 }
8047 }
8048
8049 // Special handling of variable named 'main'.
8050 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
8052 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
8053
8054 // C++ [basic.start.main]p3
8055 // A program that declares a variable main at global scope is ill-formed.
8056 if (getLangOpts().CPlusPlus)
8057 Diag(D.getBeginLoc(), diag::err_main_global_variable);
8058
8059 // In C, and external-linkage variable named main results in undefined
8060 // behavior.
8061 else if (NewVD->hasExternalFormalLinkage())
8062 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8063 }
8064
8065 if (D.isRedeclaration() && !Previous.empty()) {
8066 NamedDecl *Prev = Previous.getRepresentativeDecl();
8067 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8068 D.isFunctionDefinition());
8069 }
8070
8071 if (NewTemplate) {
8072 if (NewVD->isInvalidDecl())
8073 NewTemplate->setInvalidDecl();
8074 ActOnDocumentableDecl(NewTemplate);
8075 return NewTemplate;
8076 }
8077
8078 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8080
8082
8083 return NewVD;
8084}
8085
8086/// Enum describing the %select options in diag::warn_decl_shadow.
8096
8097/// Determine what kind of declaration we're shadowing.
8099 const DeclContext *OldDC) {
8100 if (isa<TypeAliasDecl>(ShadowedDecl))
8101 return SDK_Using;
8102 else if (isa<TypedefDecl>(ShadowedDecl))
8103 return SDK_Typedef;
8104 else if (isa<BindingDecl>(ShadowedDecl))
8105 return SDK_StructuredBinding;
8106 else if (isa<RecordDecl>(OldDC))
8107 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8108
8109 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8110}
8111
8112/// Return the location of the capture if the given lambda captures the given
8113/// variable \p VD, or an invalid source location otherwise.
8115 const VarDecl *VD) {
8116 for (const Capture &Capture : LSI->Captures) {
8118 return Capture.getLocation();
8119 }
8120 return SourceLocation();
8121}
8122
8124 const LookupResult &R) {
8125 // Only diagnose if we're shadowing an unambiguous field or variable.
8127 return false;
8128
8129 // Return false if warning is ignored.
8130 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8131}
8132
8134 const LookupResult &R) {
8136 return nullptr;
8137
8138 // Don't diagnose declarations at file scope.
8139 if (D->hasGlobalStorage() && !D->isStaticLocal())
8140 return nullptr;
8141
8142 NamedDecl *ShadowedDecl = R.getFoundDecl();
8143 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8144 : nullptr;
8145}
8146
8148 const LookupResult &R) {
8149 // Don't warn if typedef declaration is part of a class
8150 if (D->getDeclContext()->isRecord())
8151 return nullptr;
8152
8154 return nullptr;
8155
8156 NamedDecl *ShadowedDecl = R.getFoundDecl();
8157 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8158}
8159
8161 const LookupResult &R) {
8163 return nullptr;
8164
8165 NamedDecl *ShadowedDecl = R.getFoundDecl();
8166 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8167 : nullptr;
8168}
8169
8171 const LookupResult &R) {
8172 DeclContext *NewDC = D->getDeclContext();
8173
8174 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8175 // Fields are not shadowed by variables in C++ static methods.
8176 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
8177 if (MD->isStatic())
8178 return;
8179
8180 // Fields shadowed by constructor parameters are a special case. Usually
8181 // the constructor initializes the field with the parameter.
8182 if (isa<CXXConstructorDecl>(NewDC))
8183 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8184 // Remember that this was shadowed so we can either warn about its
8185 // modification or its existence depending on warning settings.
8186 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8187 return;
8188 }
8189 }
8190
8191 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8192 if (shadowedVar->isExternC()) {
8193 // For shadowing external vars, make sure that we point to the global
8194 // declaration, not a locally scoped extern declaration.
8195 for (auto *I : shadowedVar->redecls())
8196 if (I->isFileVarDecl()) {
8197 ShadowedDecl = I;
8198 break;
8199 }
8200 }
8201
8202 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8203
8204 unsigned WarningDiag = diag::warn_decl_shadow;
8205 SourceLocation CaptureLoc;
8206 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8207 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8208 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8209 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8210 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8211 if (RD->getLambdaCaptureDefault() == LCD_None) {
8212 // Try to avoid warnings for lambdas with an explicit capture
8213 // list. Warn only when the lambda captures the shadowed decl
8214 // explicitly.
8215 CaptureLoc = getCaptureLocation(LSI, VD);
8216 if (CaptureLoc.isInvalid())
8217 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8218 } else {
8219 // Remember that this was shadowed so we can avoid the warning if
8220 // the shadowed decl isn't captured and the warning settings allow
8221 // it.
8222 cast<LambdaScopeInfo>(getCurFunction())
8223 ->ShadowingDecls.push_back({D, VD});
8224 return;
8225 }
8226 }
8227 if (isa<FieldDecl>(ShadowedDecl)) {
8228 // If lambda can capture this, then emit default shadowing warning,
8229 // Otherwise it is not really a shadowing case since field is not
8230 // available in lambda's body.
8231 // At this point we don't know that lambda can capture this, so
8232 // remember that this was shadowed and delay until we know.
8233 cast<LambdaScopeInfo>(getCurFunction())
8234 ->ShadowingDecls.push_back({D, ShadowedDecl});
8235 return;
8236 }
8237 }
8238 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl);
8239 VD && VD->hasLocalStorage()) {
8240 // A variable can't shadow a local variable in an enclosing scope, if
8241 // they are separated by a non-capturing declaration context.
8242 for (DeclContext *ParentDC = NewDC;
8243 ParentDC && !ParentDC->Equals(OldDC);
8244 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8245 // Only block literals, captured statements, and lambda expressions
8246 // can capture; other scopes don't.
8247 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8248 !isLambdaCallOperator(ParentDC)) {
8249 return;
8250 }
8251 }
8252 }
8253 }
8254 }
8255
8256 // Never warn about shadowing a placeholder variable.
8257 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8258 return;
8259
8260 // Only warn about certain kinds of shadowing for class members.
8261 if (NewDC && NewDC->isRecord()) {
8262 // In particular, don't warn about shadowing non-class members.
8263 if (!OldDC->isRecord())
8264 return;
8265
8266 // TODO: should we warn about static data members shadowing
8267 // static data members from base classes?
8268
8269 // TODO: don't diagnose for inaccessible shadowed members.
8270 // This is hard to do perfectly because we might friend the
8271 // shadowing context, but that's just a false negative.
8272 }
8273
8274
8275 DeclarationName Name = R.getLookupName();
8276
8277 // Emit warning and note.
8278 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8279 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8280 if (!CaptureLoc.isInvalid())
8281 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8282 << Name << /*explicitly*/ 1;
8283 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8284}
8285
8287 for (const auto &Shadow : LSI->ShadowingDecls) {
8288 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8289 // Try to avoid the warning when the shadowed decl isn't captured.
8290 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8291 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl)) {
8292 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8293 Diag(Shadow.VD->getLocation(),
8294 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8295 : diag::warn_decl_shadow)
8296 << Shadow.VD->getDeclName()
8297 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8298 if (CaptureLoc.isValid())
8299 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8300 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8301 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8302 } else if (isa<FieldDecl>(ShadowedDecl)) {
8303 Diag(Shadow.VD->getLocation(),
8304 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8305 : diag::warn_decl_shadow_uncaptured_local)
8306 << Shadow.VD->getDeclName()
8307 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8308 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8309 }
8310 }
8311}
8312
8314 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8315 return;
8316
8317 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8319 RedeclarationKind::ForVisibleRedeclaration);
8320 LookupName(R, S);
8321 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8322 CheckShadow(D, ShadowedDecl, R);
8323}
8324
8325/// Check if 'E', which is an expression that is about to be modified, refers
8326/// to a constructor parameter that shadows a field.
8328 // Quickly ignore expressions that can't be shadowing ctor parameters.
8329 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8330 return;
8331 E = E->IgnoreParenImpCasts();
8332 auto *DRE = dyn_cast<DeclRefExpr>(E);
8333 if (!DRE)
8334 return;
8335 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8336 auto I = ShadowingDecls.find(D);
8337 if (I == ShadowingDecls.end())
8338 return;
8339 const NamedDecl *ShadowedDecl = I->second;
8340 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8341 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8342 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8343 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8344
8345 // Avoid issuing multiple warnings about the same decl.
8346 ShadowingDecls.erase(I);
8347}
8348
8349/// Check for conflict between this global or extern "C" declaration and
8350/// previous global or extern "C" declarations. This is only used in C++.
8351template<typename T>
8353 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8354 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8355 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8356
8357 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8358 // The common case: this global doesn't conflict with any extern "C"
8359 // declaration.
8360 return false;
8361 }
8362
8363 if (Prev) {
8364 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8365 // Both the old and new declarations have C language linkage. This is a
8366 // redeclaration.
8367 Previous.clear();
8368 Previous.addDecl(Prev);
8369 return true;
8370 }
8371
8372 // This is a global, non-extern "C" declaration, and there is a previous
8373 // non-global extern "C" declaration. Diagnose if this is a variable
8374 // declaration.
8375 if (!isa<VarDecl>(ND))
8376 return false;
8377 } else {
8378 // The declaration is extern "C". Check for any declaration in the
8379 // translation unit which might conflict.
8380 if (IsGlobal) {
8381 // We have already performed the lookup into the translation unit.
8382 IsGlobal = false;
8383 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8384 I != E; ++I) {
8385 if (isa<VarDecl>(*I)) {
8386 Prev = *I;
8387 break;
8388 }
8389 }
8390 } else {
8392 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8393 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8394 I != E; ++I) {
8395 if (isa<VarDecl>(*I)) {
8396 Prev = *I;
8397 break;
8398 }
8399 // FIXME: If we have any other entity with this name in global scope,
8400 // the declaration is ill-formed, but that is a defect: it breaks the
8401 // 'stat' hack, for instance. Only variables can have mangled name
8402 // clashes with extern "C" declarations, so only they deserve a
8403 // diagnostic.
8404 }
8405 }
8406
8407 if (!Prev)
8408 return false;
8409 }
8410
8411 // Use the first declaration's location to ensure we point at something which
8412 // is lexically inside an extern "C" linkage-spec.
8413 assert(Prev && "should have found a previous declaration to diagnose");
8414 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8415 Prev = FD->getFirstDecl();
8416 else
8417 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8418
8419 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8420 << IsGlobal << ND;
8421 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8422 << IsGlobal;
8423 return false;
8424}
8425
8426/// Apply special rules for handling extern "C" declarations. Returns \c true
8427/// if we have found that this is a redeclaration of some prior entity.
8428///
8429/// Per C++ [dcl.link]p6:
8430/// Two declarations [for a function or variable] with C language linkage
8431/// with the same name that appear in different scopes refer to the same
8432/// [entity]. An entity with C language linkage shall not be declared with
8433/// the same name as an entity in global scope.
8434template<typename T>
8437 if (!S.getLangOpts().CPlusPlus) {
8438 // In C, when declaring a global variable, look for a corresponding 'extern'
8439 // variable declared in function scope. We don't need this in C++, because
8440 // we find local extern decls in the surrounding file-scope DeclContext.
8441 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8442 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8443 Previous.clear();
8444 Previous.addDecl(Prev);
8445 return true;
8446 }
8447 }
8448 return false;
8449 }
8450
8451 // A declaration in the translation unit can conflict with an extern "C"
8452 // declaration.
8453 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8454 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8455
8456 // An extern "C" declaration can conflict with a declaration in the
8457 // translation unit or can be a redeclaration of an extern "C" declaration
8458 // in another scope.
8459 if (isIncompleteDeclExternC(S,ND))
8460 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8461
8462 // Neither global nor extern "C": nothing to do.
8463 return false;
8464}
8465
8466static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8467 QualType T) {
8468 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8469 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8470 // any of its members, even recursively, shall not have an atomic type, or a
8471 // variably modified type, or a type that is volatile or restrict qualified.
8472 if (CanonT->isVariablyModifiedType()) {
8473 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8474 return true;
8475 }
8476
8477 // Arrays are qualified by their element type, so get the base type (this
8478 // works on non-arrays as well).
8479 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8480
8481 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8482 CanonT.isRestrictQualified()) {
8483 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8484 return true;
8485 }
8486
8487 if (CanonT->isRecordType()) {
8488 const RecordDecl *RD = CanonT->getAsRecordDecl();
8489 if (llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8490 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8491 }))
8492 return true;
8493 }
8494
8495 return false;
8496}
8497
8499 // If the decl is already known invalid, don't check it.
8500 if (NewVD->isInvalidDecl())
8501 return;
8502
8503 QualType T = NewVD->getType();
8504
8505 // Defer checking an 'auto' type until its initializer is attached.
8506 if (T->isUndeducedType())
8507 return;
8508
8509 if (NewVD->hasAttrs())
8511
8512 if (T->isObjCObjectType()) {
8513 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8514 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8516 NewVD->setType(T);
8517 }
8518
8519 // Emit an error if an address space was applied to decl with local storage.
8520 // This includes arrays of objects with address space qualifiers, but not
8521 // automatic variables that point to other address spaces.
8522 // ISO/IEC TR 18037 S5.1.2
8523 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8524 T.getAddressSpace() != LangAS::Default) {
8525 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8526 NewVD->setInvalidDecl();
8527 return;
8528 }
8529
8530 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8531 // scope.
8532 if (getLangOpts().OpenCLVersion == 120 &&
8533 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8534 getLangOpts()) &&
8535 NewVD->isStaticLocal()) {
8536 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8537 NewVD->setInvalidDecl();
8538 return;
8539 }
8540
8541 if (getLangOpts().OpenCL) {
8542 if (!diagnoseOpenCLTypes(*this, NewVD))
8543 return;
8544
8545 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8546 if (NewVD->hasAttr<BlocksAttr>()) {
8547 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8548 return;
8549 }
8550
8551 if (T->isBlockPointerType()) {
8552 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8553 // can't use 'extern' storage class.
8554 if (!T.isConstQualified()) {
8555 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8556 << 0 /*const*/;
8557 NewVD->setInvalidDecl();
8558 return;
8559 }
8560 if (NewVD->hasExternalStorage()) {
8561 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8562 NewVD->setInvalidDecl();
8563 return;
8564 }
8565 }
8566
8567 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8568 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8569 NewVD->hasExternalStorage()) {
8570 if (!T->isSamplerT() && !T->isDependentType() &&
8571 !(T.getAddressSpace() == LangAS::opencl_constant ||
8572 (T.getAddressSpace() == LangAS::opencl_global &&
8573 getOpenCLOptions().areProgramScopeVariablesSupported(
8574 getLangOpts())))) {
8575 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8576 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8577 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8578 << Scope << "global or constant";
8579 else
8580 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8581 << Scope << "constant";
8582 NewVD->setInvalidDecl();
8583 return;
8584 }
8585 } else {
8586 if (T.getAddressSpace() == LangAS::opencl_global) {
8587 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8588 << 1 /*is any function*/ << "global";
8589 NewVD->setInvalidDecl();
8590 return;
8591 }
8592 if (T.getAddressSpace() == LangAS::opencl_constant ||
8593 T.getAddressSpace() == LangAS::opencl_local) {
8595 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8596 // in functions.
8597 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8598 if (T.getAddressSpace() == LangAS::opencl_constant)
8599 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8600 << 0 /*non-kernel only*/ << "constant";
8601 else
8602 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8603 << 0 /*non-kernel only*/ << "local";
8604 NewVD->setInvalidDecl();
8605 return;
8606 }
8607 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8608 // in the outermost scope of a kernel function.
8609 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8610 if (!getCurScope()->isFunctionScope()) {
8611 if (T.getAddressSpace() == LangAS::opencl_constant)
8612 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8613 << "constant";
8614 else
8615 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8616 << "local";
8617 NewVD->setInvalidDecl();
8618 return;
8619 }
8620 }
8621 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8622 // If we are parsing a template we didn't deduce an addr
8623 // space yet.
8624 T.getAddressSpace() != LangAS::Default) {
8625 // Do not allow other address spaces on automatic variable.
8626 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8627 NewVD->setInvalidDecl();
8628 return;
8629 }
8630 }
8631 }
8632
8633 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8634 && !NewVD->hasAttr<BlocksAttr>()) {
8635 if (getLangOpts().getGC() != LangOptions::NonGC)
8636 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8637 else {
8638 assert(!getLangOpts().ObjCAutoRefCount);
8639 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8640 }
8641 }
8642
8643 // WebAssembly tables must be static with a zero length and can't be
8644 // declared within functions.
8645 if (T->isWebAssemblyTableType()) {
8646 if (getCurScope()->getParent()) { // Parent is null at top-level
8647 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
8648 NewVD->setInvalidDecl();
8649 return;
8650 }
8651 if (NewVD->getStorageClass() != SC_Static) {
8652 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
8653 NewVD->setInvalidDecl();
8654 return;
8655 }
8656 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
8657 if (!ATy || ATy->getZExtSize() != 0) {
8658 Diag(NewVD->getLocation(),
8659 diag::err_typecheck_wasm_table_must_have_zero_length);
8660 NewVD->setInvalidDecl();
8661 return;
8662 }
8663 }
8664
8665 bool isVM = T->isVariablyModifiedType();
8666 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8667 NewVD->hasAttr<BlocksAttr>())
8669
8670 if ((isVM && NewVD->hasLinkage()) ||
8671 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8672 bool SizeIsNegative;
8673 llvm::APSInt Oversized;
8675 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8676 QualType FixedT;
8677 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8678 FixedT = FixedTInfo->getType();
8679 else if (FixedTInfo) {
8680 // Type and type-as-written are canonically different. We need to fix up
8681 // both types separately.
8682 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8683 Oversized);
8684 }
8685 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8687 // FIXME: This won't give the correct result for
8688 // int a[10][n];
8689 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8690
8691 if (NewVD->isFileVarDecl())
8692 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8693 << SizeRange;
8694 else if (NewVD->isStaticLocal())
8695 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8696 << SizeRange;
8697 else
8698 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8699 << SizeRange;
8700 NewVD->setInvalidDecl();
8701 return;
8702 }
8703
8704 if (!FixedTInfo) {
8705 if (NewVD->isFileVarDecl())
8706 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8707 else
8708 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8709 NewVD->setInvalidDecl();
8710 return;
8711 }
8712
8713 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8714 NewVD->setType(FixedT);
8715 NewVD->setTypeSourceInfo(FixedTInfo);
8716 }
8717
8718 if (T->isVoidType()) {
8719 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8720 // of objects and functions.
8722 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8723 << T;
8724 NewVD->setInvalidDecl();
8725 return;
8726 }
8727 }
8728
8729 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8730 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8731 NewVD->setInvalidDecl();
8732 return;
8733 }
8734
8735 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
8736 !T.isWebAssemblyReferenceType()) {
8737 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8738 NewVD->setInvalidDecl();
8739 return;
8740 }
8741
8742 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8743 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8744 NewVD->setInvalidDecl();
8745 return;
8746 }
8747
8748 if (getLangOpts().C23 && NewVD->isConstexpr() &&
8749 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
8750 NewVD->setInvalidDecl();
8751 return;
8752 }
8753
8754 if (NewVD->isConstexpr() && !T->isDependentType() &&
8756 diag::err_constexpr_var_non_literal)) {
8757 NewVD->setInvalidDecl();
8758 return;
8759 }
8760
8761 // PPC MMA non-pointer types are not allowed as non-local variable types.
8762 if (Context.getTargetInfo().getTriple().isPPC64() &&
8763 !NewVD->isLocalVarDecl() &&
8764 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
8765 NewVD->setInvalidDecl();
8766 return;
8767 }
8768
8769 // Check that SVE types are only used in functions with SVE available.
8770 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8771 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8772 llvm::StringMap<bool> CallerFeatureMap;
8773 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8774
8775 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
8776 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap)) {
8777 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
8778 NewVD->setInvalidDecl();
8779 return;
8780 } else if (!IsArmStreamingFunction(FD,
8781 /*IncludeLocallyStreaming=*/true)) {
8782 Diag(NewVD->getLocation(),
8783 diag::err_sve_vector_in_non_streaming_function)
8784 << T;
8785 NewVD->setInvalidDecl();
8786 return;
8787 }
8788 }
8789 }
8790
8791 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
8792 const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
8793 llvm::StringMap<bool> CallerFeatureMap;
8794 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
8795 RISCV().checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext),
8796 CallerFeatureMap);
8797 }
8798}
8799
8802
8803 // If the decl is already known invalid, don't check it.
8804 if (NewVD->isInvalidDecl())
8805 return false;
8806
8807 // If we did not find anything by this name, look for a non-visible
8808 // extern "C" declaration with the same name.
8809 if (Previous.empty() &&
8811 Previous.setShadowed();
8812
8813 if (!Previous.empty()) {
8814 MergeVarDecl(NewVD, Previous);
8815 return true;
8816 }
8817 return false;
8818}
8819
8822
8823 // Look for methods in base classes that this method might override.
8824 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8825 /*DetectVirtual=*/false);
8826 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8827 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8828 DeclarationName Name = MD->getDeclName();
8829
8830 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8831 // We really want to find the base class destructor here.
8832 QualType T = Context.getTypeDeclType(BaseRecord);
8835 }
8836
8837 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8838 CXXMethodDecl *BaseMD =
8839 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8840 if (!BaseMD || !BaseMD->isVirtual() ||
8841 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8842 /*ConsiderCudaAttrs=*/true))
8843 continue;
8844 if (!CheckExplicitObjectOverride(MD, BaseMD))
8845 continue;
8846 if (Overridden.insert(BaseMD).second) {
8847 MD->addOverriddenMethod(BaseMD);
8852 }
8853
8854 // A method can only override one function from each base class. We
8855 // don't track indirectly overridden methods from bases of bases.
8856 return true;
8857 }
8858
8859 return false;
8860 };
8861
8862 DC->lookupInBases(VisitBase, Paths);
8863 return !Overridden.empty();
8864}
8865
8866namespace {
8867 // Struct for holding all of the extra arguments needed by
8868 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8869 struct ActOnFDArgs {
8870 Scope *S;
8871 Declarator &D;
8872 MultiTemplateParamsArg TemplateParamLists;
8873 bool AddToScope;
8874 };
8875} // end anonymous namespace
8876
8877namespace {
8878
8879// Callback to only accept typo corrections that have a non-zero edit distance.
8880// Also only accept corrections that have the same parent decl.
8881class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8882 public:
8883 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8885 : Context(Context), OriginalFD(TypoFD),
8886 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8887
8888 bool ValidateCandidate(const TypoCorrection &candidate) override {
8889 if (candidate.getEditDistance() == 0)
8890 return false;
8891
8892 SmallVector<unsigned, 1> MismatchedParams;
8893 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8894 CDeclEnd = candidate.end();
8895 CDecl != CDeclEnd; ++CDecl) {
8896 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8897
8898 if (FD && !FD->hasBody() &&
8899 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8900 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8901 CXXRecordDecl *Parent = MD->getParent();
8902 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8903 return true;
8904 } else if (!ExpectedParent) {
8905 return true;
8906 }
8907 }
8908 }
8909
8910 return false;
8911 }
8912
8913 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8914 return std::make_unique<DifferentNameValidatorCCC>(*this);
8915 }
8916
8917 private:
8918 ASTContext &Context;
8919 FunctionDecl *OriginalFD;
8920 CXXRecordDecl *ExpectedParent;
8921};
8922
8923} // end anonymous namespace
8924
8927}
8928
8929/// Generate diagnostics for an invalid function redeclaration.
8930///
8931/// This routine handles generating the diagnostic messages for an invalid
8932/// function redeclaration, including finding possible similar declarations
8933/// or performing typo correction if there are no previous declarations with
8934/// the same name.
8935///
8936/// Returns a NamedDecl iff typo correction was performed and substituting in
8937/// the new declaration name does not cause new errors.
8939 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8940 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8941 DeclarationName Name = NewFD->getDeclName();
8942 DeclContext *NewDC = NewFD->getDeclContext();
8943 SmallVector<unsigned, 1> MismatchedParams;
8945 TypoCorrection Correction;
8946 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8947 unsigned DiagMsg =
8948 IsLocalFriend ? diag::err_no_matching_local_friend :
8949 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8950 diag::err_member_decl_does_not_match;
8951 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8952 IsLocalFriend ? Sema::LookupLocalFriendName
8954 RedeclarationKind::ForVisibleRedeclaration);
8955
8956 NewFD->setInvalidDecl();
8957 if (IsLocalFriend)
8958 SemaRef.LookupName(Prev, S);
8959 else
8960 SemaRef.LookupQualifiedName(Prev, NewDC);
8961 assert(!Prev.isAmbiguous() &&
8962 "Cannot have an ambiguity in previous-declaration lookup");
8963 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8964 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8965 MD ? MD->getParent() : nullptr);
8966 if (!Prev.empty()) {
8967 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8968 Func != FuncEnd; ++Func) {
8969 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8970 if (FD &&
8971 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8972 // Add 1 to the index so that 0 can mean the mismatch didn't
8973 // involve a parameter
8974 unsigned ParamNum =
8975 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8976 NearMatches.push_back(std::make_pair(FD, ParamNum));
8977 }
8978 }
8979 // If the qualified name lookup yielded nothing, try typo correction
8980 } else if ((Correction = SemaRef.CorrectTypo(
8981 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8982 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8983 IsLocalFriend ? nullptr : NewDC))) {
8984 // Set up everything for the call to ActOnFunctionDeclarator
8985 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8986 ExtraArgs.D.getIdentifierLoc());
8987 Previous.clear();
8988 Previous.setLookupName(Correction.getCorrection());
8989 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8990 CDeclEnd = Correction.end();
8991 CDecl != CDeclEnd; ++CDecl) {
8992 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8993 if (FD && !FD->hasBody() &&
8994 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8995 Previous.addDecl(FD);
8996 }
8997 }
8998 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8999
9001 // Retry building the function declaration with the new previous
9002 // declarations, and with errors suppressed.
9003 {
9004 // Trap errors.
9005 Sema::SFINAETrap Trap(SemaRef);
9006
9007 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9008 // pieces need to verify the typo-corrected C++ declaration and hopefully
9009 // eliminate the need for the parameter pack ExtraArgs.
9011 ExtraArgs.S, ExtraArgs.D,
9012 Correction.getCorrectionDecl()->getDeclContext(),
9013 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9014 ExtraArgs.AddToScope);
9015
9016 if (Trap.hasErrorOccurred())
9017 Result = nullptr;
9018 }
9019
9020 if (Result) {
9021 // Determine which correction we picked.
9022 Decl *Canonical = Result->getCanonicalDecl();
9023 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9024 I != E; ++I)
9025 if ((*I)->getCanonicalDecl() == Canonical)
9026 Correction.setCorrectionDecl(*I);
9027
9028 // Let Sema know about the correction.
9030 SemaRef.diagnoseTypo(
9031 Correction,
9032 SemaRef.PDiag(IsLocalFriend
9033 ? diag::err_no_matching_local_friend_suggest
9034 : diag::err_member_decl_does_not_match_suggest)
9035 << Name << NewDC << IsDefinition);
9036 return Result;
9037 }
9038
9039 // Pretend the typo correction never occurred
9040 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9041 ExtraArgs.D.getIdentifierLoc());
9042 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9043 Previous.clear();
9044 Previous.setLookupName(Name);
9045 }
9046
9047 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9048 << Name << NewDC << IsDefinition << NewFD->getLocation();
9049
9050 bool NewFDisConst = false;
9051 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
9052 NewFDisConst = NewMD->isConst();
9053
9054 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9055 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9056 NearMatch != NearMatchEnd; ++NearMatch) {
9057 FunctionDecl *FD = NearMatch->first;
9058 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9059 bool FDisConst = MD && MD->isConst();
9060 bool IsMember = MD || !IsLocalFriend;
9061
9062 // FIXME: These notes are poorly worded for the local friend case.
9063 if (unsigned Idx = NearMatch->second) {
9064 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9066 if (Loc.isInvalid()) Loc = FD->getLocation();
9067 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9068 : diag::note_local_decl_close_param_match)
9069 << Idx << FDParam->getType()
9070 << NewFD->getParamDecl(Idx - 1)->getType();
9071 } else if (FDisConst != NewFDisConst) {
9072 auto DB = SemaRef.Diag(FD->getLocation(),
9073 diag::note_member_def_close_const_match)
9074 << NewFDisConst << FD->getSourceRange().getEnd();
9075 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9076 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9077 " const");
9078 else if (FTI.hasMethodTypeQualifiers() &&
9079 FTI.getConstQualifierLoc().isValid())
9080 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9081 } else {
9082 SemaRef.Diag(FD->getLocation(),
9083 IsMember ? diag::note_member_def_close_match
9084 : diag::note_local_decl_close_match);
9085 }
9086 }
9087 return nullptr;
9088}
9089
9091 switch (D.getDeclSpec().getStorageClassSpec()) {
9092 default: llvm_unreachable("Unknown storage class!");
9093 case DeclSpec::SCS_auto:
9096 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9097 diag::err_typecheck_sclass_func);
9098 D.getMutableDeclSpec().ClearStorageClassSpecs();
9099 D.setInvalidType();
9100 break;
9101 case DeclSpec::SCS_unspecified: break;
9103 if (D.getDeclSpec().isExternInLinkageSpec())
9104 return SC_None;
9105 return SC_Extern;
9106 case DeclSpec::SCS_static: {
9108 // C99 6.7.1p5:
9109 // The declaration of an identifier for a function that has
9110 // block scope shall have no explicit storage-class specifier
9111 // other than extern
9112 // See also (C++ [dcl.stc]p4).
9113 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9114 diag::err_static_block_func);
9115 break;
9116 } else
9117 return SC_Static;
9118 }
9120 }
9121
9122 // No explicit storage class has already been returned
9123 return SC_None;
9124}
9125
9127 DeclContext *DC, QualType &R,
9128 TypeSourceInfo *TInfo,
9129 StorageClass SC,
9130 bool &IsVirtualOkay) {
9131 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9132 DeclarationName Name = NameInfo.getName();
9133
9134 FunctionDecl *NewFD = nullptr;
9135 bool isInline = D.getDeclSpec().isInlineSpecified();
9136
9137 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9138 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9139 (SemaRef.getLangOpts().C23 &&
9140 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9141
9142 if (SemaRef.getLangOpts().C23)
9143 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9144 diag::err_c23_constexpr_not_variable);
9145 else
9146 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9147 diag::err_constexpr_wrong_decl_kind)
9148 << static_cast<int>(ConstexprKind);
9149 ConstexprKind = ConstexprSpecKind::Unspecified;
9150 D.getMutableDeclSpec().ClearConstexprSpec();
9151 }
9152
9153 if (!SemaRef.getLangOpts().CPlusPlus) {
9154 // Determine whether the function was written with a prototype. This is
9155 // true when:
9156 // - there is a prototype in the declarator, or
9157 // - the type R of the function is some kind of typedef or other non-
9158 // attributed reference to a type name (which eventually refers to a
9159 // function type). Note, we can't always look at the adjusted type to
9160 // check this case because attributes may cause a non-function
9161 // declarator to still have a function type. e.g.,
9162 // typedef void func(int a);
9163 // __attribute__((noreturn)) func other_func; // This has a prototype
9164 bool HasPrototype =
9165 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
9166 (D.getDeclSpec().isTypeRep() &&
9167 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9168 ->isFunctionProtoType()) ||
9170 assert(
9171 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9172 "Strict prototypes are required");
9173
9174 NewFD = FunctionDecl::Create(
9175 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9176 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9178 /*TrailingRequiresClause=*/nullptr);
9179 if (D.isInvalidType())
9180 NewFD->setInvalidDecl();
9181
9182 return NewFD;
9183 }
9184
9185 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
9186 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
9187
9188 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9189
9190 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
9191 // This is a C++ constructor declaration.
9192 assert(DC->isRecord() &&
9193 "Constructors can only be declared in a member context");
9194
9195 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9197 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9199 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9200 InheritedConstructor(), TrailingRequiresClause);
9201
9202 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9203 // This is a C++ destructor declaration.
9204 if (DC->isRecord()) {
9205 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9206 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
9208 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9209 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9210 /*isImplicitlyDeclared=*/false, ConstexprKind,
9211 TrailingRequiresClause);
9212 // User defined destructors start as not selected if the class definition is still
9213 // not done.
9214 if (Record->isBeingDefined())
9215 NewDD->setIneligibleOrNotSelected(true);
9216
9217 // If the destructor needs an implicit exception specification, set it
9218 // now. FIXME: It'd be nice to be able to create the right type to start
9219 // with, but the type needs to reference the destructor declaration.
9220 if (SemaRef.getLangOpts().CPlusPlus11)
9221 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9222
9223 IsVirtualOkay = true;
9224 return NewDD;
9225
9226 } else {
9227 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9228 D.setInvalidType();
9229
9230 // Create a FunctionDecl to satisfy the function definition parsing
9231 // code path.
9232 return FunctionDecl::Create(
9233 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9234 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9235 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9236 }
9237
9238 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
9239 if (!DC->isRecord()) {
9240 SemaRef.Diag(D.getIdentifierLoc(),
9241 diag::err_conv_function_not_member);
9242 return nullptr;
9243 }
9244
9245 SemaRef.CheckConversionDeclarator(D, R, SC);
9246 if (D.isInvalidType())
9247 return nullptr;
9248
9249 IsVirtualOkay = true;
9251 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9252 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9253 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9254 TrailingRequiresClause);
9255
9256 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9257 if (TrailingRequiresClause)
9258 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
9259 diag::err_trailing_requires_clause_on_deduction_guide)
9260 << TrailingRequiresClause->getSourceRange();
9261 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9262 return nullptr;
9263 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
9264 ExplicitSpecifier, NameInfo, R, TInfo,
9265 D.getEndLoc());
9266 } else if (DC->isRecord()) {
9267 // If the name of the function is the same as the name of the record,
9268 // then this must be an invalid constructor that has a return type.
9269 // (The parser checks for a return type and makes the declarator a
9270 // constructor if it has no return type).
9271 if (Name.getAsIdentifierInfo() &&
9272 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9273 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9274 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
9275 << SourceRange(D.getIdentifierLoc());
9276 return nullptr;
9277 }
9278
9279 // This is a C++ method declaration.
9281 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9282 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9283 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9284 IsVirtualOkay = !Ret->isStatic();
9285 return Ret;
9286 } else {
9287 bool isFriend =
9288 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9289 if (!isFriend && SemaRef.CurContext->isRecord())
9290 return nullptr;
9291
9292 // Determine whether the function was written with a
9293 // prototype. This true when:
9294 // - we're in C++ (where every function has a prototype),
9295 return FunctionDecl::Create(
9296 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9297 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9298 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9299 }
9300}
9301
9310
9312 // Size dependent types are just typedefs to normal integer types
9313 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9314 // integers other than by their names.
9315 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9316
9317 // Remove typedefs one by one until we reach a typedef
9318 // for a size dependent type.
9319 QualType DesugaredTy = Ty;
9320 do {
9321 ArrayRef<StringRef> Names(SizeTypeNames);
9322 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9323 if (Names.end() != Match)
9324 return true;
9325
9326 Ty = DesugaredTy;
9327 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9328 } while (DesugaredTy != Ty);
9329
9330 return false;
9331}
9332
9334 if (PT->isDependentType())
9335 return InvalidKernelParam;
9336
9337 if (PT->isPointerType() || PT->isReferenceType()) {
9338 QualType PointeeType = PT->getPointeeType();
9339 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9340 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9341 PointeeType.getAddressSpace() == LangAS::Default)
9343
9344 if (PointeeType->isPointerType()) {
9345 // This is a pointer to pointer parameter.
9346 // Recursively check inner type.
9347 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9348 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9349 ParamKind == InvalidKernelParam)
9350 return ParamKind;
9351
9352 // OpenCL v3.0 s6.11.a:
9353 // A restriction to pass pointers to pointers only applies to OpenCL C
9354 // v1.2 or below.
9356 return ValidKernelParam;
9357
9358 return PtrPtrKernelParam;
9359 }
9360
9361 // C++ for OpenCL v1.0 s2.4:
9362 // Moreover the types used in parameters of the kernel functions must be:
9363 // Standard layout types for pointer parameters. The same applies to
9364 // reference if an implementation supports them in kernel parameters.
9365 if (S.getLangOpts().OpenCLCPlusPlus &&
9367 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9368 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9369 bool IsStandardLayoutType = true;
9370 if (CXXRec) {
9371 // If template type is not ODR-used its definition is only available
9372 // in the template definition not its instantiation.
9373 // FIXME: This logic doesn't work for types that depend on template
9374 // parameter (PR58590).
9375 if (!CXXRec->hasDefinition())
9376 CXXRec = CXXRec->getTemplateInstantiationPattern();
9377 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9378 IsStandardLayoutType = false;
9379 }
9380 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9381 !IsStandardLayoutType)
9382 return InvalidKernelParam;
9383 }
9384
9385 // OpenCL v1.2 s6.9.p:
9386 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9388 return ValidKernelParam;
9389
9390 return PtrKernelParam;
9391 }
9392
9393 // OpenCL v1.2 s6.9.k:
9394 // Arguments to kernel functions in a program cannot be declared with the
9395 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9396 // uintptr_t or a struct and/or union that contain fields declared to be one
9397 // of these built-in scalar types.
9399 return InvalidKernelParam;
9400
9401 if (PT->isImageType())
9402 return PtrKernelParam;
9403
9404 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9405 return InvalidKernelParam;
9406
9407 // OpenCL extension spec v1.2 s9.5:
9408 // This extension adds support for half scalar and vector types as built-in
9409 // types that can be used for arithmetic operations, conversions etc.
9410 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9411 PT->isHalfType())
9412 return InvalidKernelParam;
9413
9414 // Look into an array argument to check if it has a forbidden type.
9415 if (PT->isArrayType()) {
9416 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9417 // Call ourself to check an underlying type of an array. Since the
9418 // getPointeeOrArrayElementType returns an innermost type which is not an
9419 // array, this recursive call only happens once.
9420 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9421 }
9422
9423 // C++ for OpenCL v1.0 s2.4:
9424 // Moreover the types used in parameters of the kernel functions must be:
9425 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9426 // types) for parameters passed by value;
9427 if (S.getLangOpts().OpenCLCPlusPlus &&
9429 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9430 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9431 return InvalidKernelParam;
9432
9433 if (PT->isRecordType())
9434 return RecordKernelParam;
9435
9436 return ValidKernelParam;
9437}
9438
9440 Sema &S,
9441 Declarator &D,
9442 ParmVarDecl *Param,
9443 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9444 QualType PT = Param->getType();
9445
9446 // Cache the valid types we encounter to avoid rechecking structs that are
9447 // used again
9448 if (ValidTypes.count(PT.getTypePtr()))
9449 return;
9450
9451 switch (getOpenCLKernelParameterType(S, PT)) {
9452 case PtrPtrKernelParam:
9453 // OpenCL v3.0 s6.11.a:
9454 // A kernel function argument cannot be declared as a pointer to a pointer
9455 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9456 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9457 D.setInvalidType();
9458 return;
9459
9461 // OpenCL v1.0 s6.5:
9462 // __kernel function arguments declared to be a pointer of a type can point
9463 // to one of the following address spaces only : __global, __local or
9464 // __constant.
9465 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9466 D.setInvalidType();
9467 return;
9468
9469 // OpenCL v1.2 s6.9.k:
9470 // Arguments to kernel functions in a program cannot be declared with the
9471 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9472 // uintptr_t or a struct and/or union that contain fields declared to be
9473 // one of these built-in scalar types.
9474
9475 case InvalidKernelParam:
9476 // OpenCL v1.2 s6.8 n:
9477 // A kernel function argument cannot be declared
9478 // of event_t type.
9479 // Do not diagnose half type since it is diagnosed as invalid argument
9480 // type for any function elsewhere.
9481 if (!PT->isHalfType()) {
9482 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9483
9484 // Explain what typedefs are involved.
9485 const TypedefType *Typedef = nullptr;
9486 while ((Typedef = PT->getAs<TypedefType>())) {
9487 SourceLocation Loc = Typedef->getDecl()->getLocation();
9488 // SourceLocation may be invalid for a built-in type.
9489 if (Loc.isValid())
9490 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9491 PT = Typedef->desugar();
9492 }
9493 }
9494
9495 D.setInvalidType();
9496 return;
9497
9498 case PtrKernelParam:
9499 case ValidKernelParam:
9500 ValidTypes.insert(PT.getTypePtr());
9501 return;
9502
9503 case RecordKernelParam:
9504 break;
9505 }
9506
9507 // Track nested structs we will inspect
9509
9510 // Track where we are in the nested structs. Items will migrate from
9511 // VisitStack to HistoryStack as we do the DFS for bad field.
9513 HistoryStack.push_back(nullptr);
9514
9515 // At this point we already handled everything except of a RecordType or
9516 // an ArrayType of a RecordType.
9517 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9518 const RecordType *RecTy =
9520 const RecordDecl *OrigRecDecl = RecTy->getDecl();
9521
9522 VisitStack.push_back(RecTy->getDecl());
9523 assert(VisitStack.back() && "First decl null?");
9524
9525 do {
9526 const Decl *Next = VisitStack.pop_back_val();
9527 if (!Next) {
9528 assert(!HistoryStack.empty());
9529 // Found a marker, we have gone up a level
9530 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9531 ValidTypes.insert(Hist->getType().getTypePtr());
9532
9533 continue;
9534 }
9535
9536 // Adds everything except the original parameter declaration (which is not a
9537 // field itself) to the history stack.
9538 const RecordDecl *RD;
9539 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9540 HistoryStack.push_back(Field);
9541
9542 QualType FieldTy = Field->getType();
9543 // Other field types (known to be valid or invalid) are handled while we
9544 // walk around RecordDecl::fields().
9545 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9546 "Unexpected type.");
9547 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9548
9549 RD = FieldRecTy->castAs<RecordType>()->getDecl();
9550 } else {
9551 RD = cast<RecordDecl>(Next);
9552 }
9553
9554 // Add a null marker so we know when we've gone back up a level
9555 VisitStack.push_back(nullptr);
9556
9557 for (const auto *FD : RD->fields()) {
9558 QualType QT = FD->getType();
9559
9560 if (ValidTypes.count(QT.getTypePtr()))
9561 continue;
9562
9564 if (ParamType == ValidKernelParam)
9565 continue;
9566
9567 if (ParamType == RecordKernelParam) {
9568 VisitStack.push_back(FD);
9569 continue;
9570 }
9571
9572 // OpenCL v1.2 s6.9.p:
9573 // Arguments to kernel functions that are declared to be a struct or union
9574 // do not allow OpenCL objects to be passed as elements of the struct or
9575 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9576 // of SVM.
9577 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9578 ParamType == InvalidAddrSpacePtrKernelParam) {
9579 S.Diag(Param->getLocation(),
9580 diag::err_record_with_pointers_kernel_param)
9581 << PT->isUnionType()
9582 << PT;
9583 } else {
9584 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9585 }
9586
9587 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9588 << OrigRecDecl->getDeclName();
9589
9590 // We have an error, now let's go back up through history and show where
9591 // the offending field came from
9593 I = HistoryStack.begin() + 1,
9594 E = HistoryStack.end();
9595 I != E; ++I) {
9596 const FieldDecl *OuterField = *I;
9597 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9598 << OuterField->getType();
9599 }
9600
9601 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9602 << QT->isPointerType()
9603 << QT;
9604 D.setInvalidType();
9605 return;
9606 }
9607 } while (!VisitStack.empty());
9608}
9609
9610/// Find the DeclContext in which a tag is implicitly declared if we see an
9611/// elaborated type specifier in the specified context, and lookup finds
9612/// nothing.
9614 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9615 DC = DC->getParent();
9616 return DC;
9617}
9618
9619/// Find the Scope in which a tag is implicitly declared if we see an
9620/// elaborated type specifier in the specified context, and lookup finds
9621/// nothing.
9622static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9623 while (S->isClassScope() ||
9624 (LangOpts.CPlusPlus &&
9625 S->isFunctionPrototypeScope()) ||
9626 ((S->getFlags() & Scope::DeclScope) == 0) ||
9627 (S->getEntity() && S->getEntity()->isTransparentContext()))
9628 S = S->getParent();
9629 return S;
9630}
9631
9632/// Determine whether a declaration matches a known function in namespace std.
9634 unsigned BuiltinID) {
9635 switch (BuiltinID) {
9636 case Builtin::BI__GetExceptionInfo:
9637 // No type checking whatsoever.
9638 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
9639
9640 case Builtin::BIaddressof:
9641 case Builtin::BI__addressof:
9642 case Builtin::BIforward:
9643 case Builtin::BIforward_like:
9644 case Builtin::BImove:
9645 case Builtin::BImove_if_noexcept:
9646 case Builtin::BIas_const: {
9647 // Ensure that we don't treat the algorithm
9648 // OutputIt std::move(InputIt, InputIt, OutputIt)
9649 // as the builtin std::move.
9650 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9651 return FPT->getNumParams() == 1 && !FPT->isVariadic();
9652 }
9653
9654 default:
9655 return false;
9656 }
9657}
9658
9659NamedDecl*
9662 MultiTemplateParamsArg TemplateParamListsRef,
9663 bool &AddToScope) {
9664 QualType R = TInfo->getType();
9665
9666 assert(R->isFunctionType());
9668 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9669
9670 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9671 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9672 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9673 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
9674 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9675 TemplateParamLists.back() = Invented;
9676 else
9677 TemplateParamLists.push_back(Invented);
9678 }
9679
9680 // TODO: consider using NameInfo for diagnostic.
9682 DeclarationName Name = NameInfo.getName();
9684
9685 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9686 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9687 diag::err_invalid_thread)
9689
9690 if (D.isFirstDeclarationOfMember())
9692 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()),
9693 D.isCtorOrDtor(), D.getIdentifierLoc());
9694
9695 bool isFriend = false;
9697 bool isMemberSpecialization = false;
9698 bool isFunctionTemplateSpecialization = false;
9699
9700 bool HasExplicitTemplateArgs = false;
9701 TemplateArgumentListInfo TemplateArgs;
9702
9703 bool isVirtualOkay = false;
9704
9705 DeclContext *OriginalDC = DC;
9706 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9707
9708 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9709 isVirtualOkay);
9710 if (!NewFD) return nullptr;
9711
9714
9715 // Set the lexical context. If this is a function-scope declaration, or has a
9716 // C++ scope specifier, or is the object of a friend declaration, the lexical
9717 // context will be different from the semantic context.
9719
9720 if (IsLocalExternDecl)
9721 NewFD->setLocalExternDecl();
9722
9723 if (getLangOpts().CPlusPlus) {
9724 // The rules for implicit inlines changed in C++20 for methods and friends
9725 // with an in-class definition (when such a definition is not attached to
9726 // the global module). User-specified 'inline' overrides this (set when
9727 // the function decl is created above).
9728 // FIXME: We need a better way to separate C++ standard and clang modules.
9729 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
9730 !NewFD->getOwningModule() ||
9731 NewFD->isFromExplicitGlobalModule() ||
9733 bool isInline = D.getDeclSpec().isInlineSpecified();
9734 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9735 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9736 isFriend = D.getDeclSpec().isFriendSpecified();
9737 if (isFriend && !isInline && D.isFunctionDefinition()) {
9738 // Pre-C++20 [class.friend]p5
9739 // A function can be defined in a friend declaration of a
9740 // class . . . . Such a function is implicitly inline.
9741 // Post C++20 [class.friend]p7
9742 // Such a function is implicitly an inline function if it is attached
9743 // to the global module.
9744 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
9745 }
9746
9747 // If this is a method defined in an __interface, and is not a constructor
9748 // or an overloaded operator, then set the pure flag (isVirtual will already
9749 // return true).
9750 if (const CXXRecordDecl *Parent =
9751 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9752 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9753 NewFD->setIsPureVirtual(true);
9754
9755 // C++ [class.union]p2
9756 // A union can have member functions, but not virtual functions.
9757 if (isVirtual && Parent->isUnion()) {
9758 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9759 NewFD->setInvalidDecl();
9760 }
9761 if ((Parent->isClass() || Parent->isStruct()) &&
9762 Parent->hasAttr<SYCLSpecialClassAttr>() &&
9763 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9764 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9765 if (auto *Def = Parent->getDefinition())
9766 Def->setInitMethod(true);
9767 }
9768 }
9769
9770 SetNestedNameSpecifier(*this, NewFD, D);
9771 isMemberSpecialization = false;
9772 isFunctionTemplateSpecialization = false;
9773 if (D.isInvalidType())
9774 NewFD->setInvalidDecl();
9775
9776 // Match up the template parameter lists with the scope specifier, then
9777 // determine whether we have a template or a template specialization.
9778 bool Invalid = false;
9779 TemplateIdAnnotation *TemplateId =
9781 ? D.getName().TemplateId
9782 : nullptr;
9783 TemplateParameterList *TemplateParams =
9785 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9786 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
9787 isMemberSpecialization, Invalid);
9788 if (TemplateParams) {
9789 // Check that we can declare a template here.
9790 if (CheckTemplateDeclScope(S, TemplateParams))
9791 NewFD->setInvalidDecl();
9792
9793 if (TemplateParams->size() > 0) {
9794 // This is a function template
9795
9796 // A destructor cannot be a template.
9797 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9798 Diag(NewFD->getLocation(), diag::err_destructor_template);
9799 NewFD->setInvalidDecl();
9800 // Function template with explicit template arguments.
9801 } else if (TemplateId) {
9802 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9803 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9804 NewFD->setInvalidDecl();
9805 }
9806
9807 // If we're adding a template to a dependent context, we may need to
9808 // rebuilding some of the types used within the template parameter list,
9809 // now that we know what the current instantiation is.
9810 if (DC->isDependentContext()) {
9811 ContextRAII SavedContext(*this, DC);
9813 Invalid = true;
9814 }
9815
9817 NewFD->getLocation(),
9818 Name, TemplateParams,
9819 NewFD);
9820 FunctionTemplate->setLexicalDeclContext(CurContext);
9822
9823 // For source fidelity, store the other template param lists.
9824 if (TemplateParamLists.size() > 1) {
9826 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9827 .drop_back(1));
9828 }
9829 } else {
9830 // This is a function template specialization.
9831 isFunctionTemplateSpecialization = true;
9832 // For source fidelity, store all the template param lists.
9833 if (TemplateParamLists.size() > 0)
9834 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9835
9836 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9837 if (isFriend) {
9838 // We want to remove the "template<>", found here.
9839 SourceRange RemoveRange = TemplateParams->getSourceRange();
9840
9841 // If we remove the template<> and the name is not a
9842 // template-id, we're actually silently creating a problem:
9843 // the friend declaration will refer to an untemplated decl,
9844 // and clearly the user wants a template specialization. So
9845 // we need to insert '<>' after the name.
9846 SourceLocation InsertLoc;
9847 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9848 InsertLoc = D.getName().getSourceRange().getEnd();
9849 InsertLoc = getLocForEndOfToken(InsertLoc);
9850 }
9851
9852 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9853 << Name << RemoveRange
9854 << FixItHint::CreateRemoval(RemoveRange)
9855 << FixItHint::CreateInsertion(InsertLoc, "<>");
9856 Invalid = true;
9857
9858 // Recover by faking up an empty template argument list.
9859 HasExplicitTemplateArgs = true;
9860 TemplateArgs.setLAngleLoc(InsertLoc);
9861 TemplateArgs.setRAngleLoc(InsertLoc);
9862 }
9863 }
9864 } else {
9865 // Check that we can declare a template here.
9866 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9867 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9868 NewFD->setInvalidDecl();
9869
9870 // All template param lists were matched against the scope specifier:
9871 // this is NOT (an explicit specialization of) a template.
9872 if (TemplateParamLists.size() > 0)
9873 // For source fidelity, store all the template param lists.
9874 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9875
9876 // "friend void foo<>(int);" is an implicit specialization decl.
9877 if (isFriend && TemplateId)
9878 isFunctionTemplateSpecialization = true;
9879 }
9880
9881 // If this is a function template specialization and the unqualified-id of
9882 // the declarator-id is a template-id, convert the template argument list
9883 // into our AST format and check for unexpanded packs.
9884 if (isFunctionTemplateSpecialization && TemplateId) {
9885 HasExplicitTemplateArgs = true;
9886
9887 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9888 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9889 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9890 TemplateId->NumArgs);
9891 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
9892
9893 // FIXME: Should we check for unexpanded packs if this was an (invalid)
9894 // declaration of a function template partial specialization? Should we
9895 // consider the unexpanded pack context to be a partial specialization?
9896 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
9898 ArgLoc, isFriend ? UPPC_FriendDeclaration
9900 NewFD->setInvalidDecl();
9901 }
9902 }
9903
9904 if (Invalid) {
9905 NewFD->setInvalidDecl();
9906 if (FunctionTemplate)
9907 FunctionTemplate->setInvalidDecl();
9908 }
9909
9910 // C++ [dcl.fct.spec]p5:
9911 // The virtual specifier shall only be used in declarations of
9912 // nonstatic class member functions that appear within a
9913 // member-specification of a class declaration; see 10.3.
9914 //
9915 if (isVirtual && !NewFD->isInvalidDecl()) {
9916 if (!isVirtualOkay) {
9917 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9918 diag::err_virtual_non_function);
9919 } else if (!CurContext->isRecord()) {
9920 // 'virtual' was specified outside of the class.
9921 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9922 diag::err_virtual_out_of_class)
9923 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9924 } else if (NewFD->getDescribedFunctionTemplate()) {
9925 // C++ [temp.mem]p3:
9926 // A member function template shall not be virtual.
9927 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9928 diag::err_virtual_member_function_template)
9929 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9930 } else {
9931 // Okay: Add virtual to the method.
9932 NewFD->setVirtualAsWritten(true);
9933 }
9934
9935 if (getLangOpts().CPlusPlus14 &&
9936 NewFD->getReturnType()->isUndeducedType())
9937 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9938 }
9939
9940 // C++ [dcl.fct.spec]p3:
9941 // The inline specifier shall not appear on a block scope function
9942 // declaration.
9943 if (isInline && !NewFD->isInvalidDecl()) {
9945 // 'inline' is not allowed on block scope function declaration.
9946 Diag(D.getDeclSpec().getInlineSpecLoc(),
9947 diag::err_inline_declaration_block_scope) << Name
9948 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9949 }
9950 }
9951
9952 // C++ [dcl.fct.spec]p6:
9953 // The explicit specifier shall be used only in the declaration of a
9954 // constructor or conversion function within its class definition;
9955 // see 12.3.1 and 12.3.2.
9956 if (hasExplicit && !NewFD->isInvalidDecl() &&
9957 !isa<CXXDeductionGuideDecl>(NewFD)) {
9958 if (!CurContext->isRecord()) {
9959 // 'explicit' was specified outside of the class.
9960 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9961 diag::err_explicit_out_of_class)
9962 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9963 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9964 !isa<CXXConversionDecl>(NewFD)) {
9965 // 'explicit' was specified on a function that wasn't a constructor
9966 // or conversion function.
9967 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9968 diag::err_explicit_non_ctor_or_conv_function)
9969 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9970 }
9971 }
9972
9973 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9974 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9975 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9976 // are implicitly inline.
9977 NewFD->setImplicitlyInline();
9978
9979 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9980 // be either constructors or to return a literal type. Therefore,
9981 // destructors cannot be declared constexpr.
9982 if (isa<CXXDestructorDecl>(NewFD) &&
9984 ConstexprKind == ConstexprSpecKind::Consteval)) {
9985 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9986 << static_cast<int>(ConstexprKind);
9987 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9990 }
9991 // C++20 [dcl.constexpr]p2: An allocation function, or a
9992 // deallocation function shall not be declared with the consteval
9993 // specifier.
9994 if (ConstexprKind == ConstexprSpecKind::Consteval &&
9995 (NewFD->getOverloadedOperator() == OO_New ||
9996 NewFD->getOverloadedOperator() == OO_Array_New ||
9997 NewFD->getOverloadedOperator() == OO_Delete ||
9998 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9999 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10000 diag::err_invalid_consteval_decl_kind)
10001 << NewFD;
10003 }
10004 }
10005
10006 // If __module_private__ was specified, mark the function accordingly.
10007 if (D.getDeclSpec().isModulePrivateSpecified()) {
10008 if (isFunctionTemplateSpecialization) {
10009 SourceLocation ModulePrivateLoc
10010 = D.getDeclSpec().getModulePrivateSpecLoc();
10011 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10012 << 0
10013 << FixItHint::CreateRemoval(ModulePrivateLoc);
10014 } else {
10015 NewFD->setModulePrivate();
10016 if (FunctionTemplate)
10017 FunctionTemplate->setModulePrivate();
10018 }
10019 }
10020
10021 if (isFriend) {
10022 if (FunctionTemplate) {
10023 FunctionTemplate->setObjectOfFriendDecl();
10024 FunctionTemplate->setAccess(AS_public);
10025 }
10026 NewFD->setObjectOfFriendDecl();
10027 NewFD->setAccess(AS_public);
10028 }
10029
10030 // If a function is defined as defaulted or deleted, mark it as such now.
10031 // We'll do the relevant checks on defaulted / deleted functions later.
10032 switch (D.getFunctionDefinitionKind()) {
10035 break;
10036
10038 NewFD->setDefaulted();
10039 break;
10040
10042 NewFD->setDeletedAsWritten();
10043 break;
10044 }
10045
10046 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10047 D.isFunctionDefinition() && !isInline) {
10048 // Pre C++20 [class.mfct]p2:
10049 // A member function may be defined (8.4) in its class definition, in
10050 // which case it is an inline member function (7.1.2)
10051 // Post C++20 [class.mfct]p1:
10052 // If a member function is attached to the global module and is defined
10053 // in its class definition, it is inline.
10054 NewFD->setImplicitlyInline(ImplicitInlineCXX20);
10055 }
10056
10057 if (!isFriend && SC != SC_None) {
10058 // C++ [temp.expl.spec]p2:
10059 // The declaration in an explicit-specialization shall not be an
10060 // export-declaration. An explicit specialization shall not use a
10061 // storage-class-specifier other than thread_local.
10062 //
10063 // We diagnose friend declarations with storage-class-specifiers
10064 // elsewhere.
10065 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10066 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10067 diag::ext_explicit_specialization_storage_class)
10069 D.getDeclSpec().getStorageClassSpecLoc());
10070 }
10071
10072 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10073 assert(isa<CXXMethodDecl>(NewFD) &&
10074 "Out-of-line member function should be a CXXMethodDecl");
10075 // C++ [class.static]p1:
10076 // A data or function member of a class may be declared static
10077 // in a class definition, in which case it is a static member of
10078 // the class.
10079
10080 // Complain about the 'static' specifier if it's on an out-of-line
10081 // member function definition.
10082
10083 // MSVC permits the use of a 'static' storage specifier on an
10084 // out-of-line member function template declaration and class member
10085 // template declaration (MSVC versions before 2015), warn about this.
10086 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
10087 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10088 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10089 (getLangOpts().MSVCCompat &&
10091 ? diag::ext_static_out_of_line
10092 : diag::err_static_out_of_line)
10094 D.getDeclSpec().getStorageClassSpecLoc());
10095 }
10096 }
10097
10098 // C++11 [except.spec]p15:
10099 // A deallocation function with no exception-specification is treated
10100 // as if it were specified with noexcept(true).
10101 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10102 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
10103 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
10104 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
10106 FPT->getReturnType(), FPT->getParamTypes(),
10108
10109 // C++20 [dcl.inline]/7
10110 // If an inline function or variable that is attached to a named module
10111 // is declared in a definition domain, it shall be defined in that
10112 // domain.
10113 // So, if the current declaration does not have a definition, we must
10114 // check at the end of the TU (or when the PMF starts) to see that we
10115 // have a definition at that point.
10116 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10117 NewFD->isInNamedModule()) {
10118 PendingInlineFuncDecls.insert(NewFD);
10119 }
10120 }
10121
10122 // Filter out previous declarations that don't match the scope.
10124 D.getCXXScopeSpec().isNotEmpty() ||
10125 isMemberSpecialization ||
10126 isFunctionTemplateSpecialization);
10127
10128 // Handle GNU asm-label extension (encoded as an attribute).
10129 if (Expr *E = (Expr*) D.getAsmLabel()) {
10130 // The parser guarantees this is a string.
10131 StringLiteral *SE = cast<StringLiteral>(E);
10132 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
10133 /*IsLiteralLabel=*/true,
10134 SE->getStrTokenLoc(0)));
10135 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10136 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10138 if (I != ExtnameUndeclaredIdentifiers.end()) {
10139 if (isDeclExternC(NewFD)) {
10140 NewFD->addAttr(I->second);
10142 } else
10143 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10144 << /*Variable*/0 << NewFD;
10145 }
10146 }
10147
10148 // Copy the parameter declarations from the declarator D to the function
10149 // declaration NewFD, if they are available. First scavenge them into Params.
10151 unsigned FTIIdx;
10152 if (D.isFunctionDeclarator(FTIIdx)) {
10153 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
10154
10155 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10156 // function that takes no arguments, not a function that takes a
10157 // single void argument.
10158 // We let through "const void" here because Sema::GetTypeForDeclarator
10159 // already checks for that case.
10160 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10161 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10162 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10163 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10164 Param->setDeclContext(NewFD);
10165 Params.push_back(Param);
10166
10167 if (Param->isInvalidDecl())
10168 NewFD->setInvalidDecl();
10169 }
10170 }
10171
10172 if (!getLangOpts().CPlusPlus) {
10173 // In C, find all the tag declarations from the prototype and move them
10174 // into the function DeclContext. Remove them from the surrounding tag
10175 // injection context of the function, which is typically but not always
10176 // the TU.
10177 DeclContext *PrototypeTagContext =
10179 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10180 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10181
10182 // We don't want to reparent enumerators. Look at their parent enum
10183 // instead.
10184 if (!TD) {
10185 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10186 TD = cast<EnumDecl>(ECD->getDeclContext());
10187 }
10188 if (!TD)
10189 continue;
10190 DeclContext *TagDC = TD->getLexicalDeclContext();
10191 if (!TagDC->containsDecl(TD))
10192 continue;
10193 TagDC->removeDecl(TD);
10194 TD->setDeclContext(NewFD);
10195 NewFD->addDecl(TD);
10196
10197 // Preserve the lexical DeclContext if it is not the surrounding tag
10198 // injection context of the FD. In this example, the semantic context of
10199 // E will be f and the lexical context will be S, while both the
10200 // semantic and lexical contexts of S will be f:
10201 // void f(struct S { enum E { a } f; } s);
10202 if (TagDC != PrototypeTagContext)
10203 TD->setLexicalDeclContext(TagDC);
10204 }
10205 }
10206 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10207 // When we're declaring a function with a typedef, typeof, etc as in the
10208 // following example, we'll need to synthesize (unnamed)
10209 // parameters for use in the declaration.
10210 //
10211 // @code
10212 // typedef void fn(int);
10213 // fn f;
10214 // @endcode
10215
10216 // Synthesize a parameter for each argument type.
10217 for (const auto &AI : FT->param_types()) {
10218 ParmVarDecl *Param =
10219 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
10220 Param->setScopeInfo(0, Params.size());
10221 Params.push_back(Param);
10222 }
10223 } else {
10224 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10225 "Should not need args for typedef of non-prototype fn");
10226 }
10227
10228 // Finally, we know we have the right number of parameters, install them.
10229 NewFD->setParams(Params);
10230
10231 if (D.getDeclSpec().isNoreturnSpecified())
10232 NewFD->addAttr(
10233 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10234
10235 // Functions returning a variably modified type violate C99 6.7.5.2p2
10236 // because all functions have linkage.
10237 if (!NewFD->isInvalidDecl() &&
10239 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10240 NewFD->setInvalidDecl();
10241 }
10242
10243 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10244 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
10245 !NewFD->hasAttr<SectionAttr>())
10246 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10249
10250 // Apply an implicit SectionAttr if #pragma code_seg is active.
10251 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10252 !NewFD->hasAttr<SectionAttr>()) {
10253 NewFD->addAttr(SectionAttr::CreateImplicit(
10254 Context, CodeSegStack.CurrentValue->getString(),
10255 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10256 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10259 NewFD))
10260 NewFD->dropAttr<SectionAttr>();
10261 }
10262
10263 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10264 // active.
10265 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10266 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10267 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10269
10270 // Apply an implicit CodeSegAttr from class declspec or
10271 // apply an implicit SectionAttr from #pragma code_seg if active.
10272 if (!NewFD->hasAttr<CodeSegAttr>()) {
10274 D.isFunctionDefinition())) {
10275 NewFD->addAttr(SAttr);
10276 }
10277 }
10278
10279 // Handle attributes.
10280 ProcessDeclAttributes(S, NewFD, D);
10281 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10282 if (NewTVA && !NewTVA->isDefaultVersion() &&
10283 !Context.getTargetInfo().hasFeature("fmv")) {
10284 // Don't add to scope fmv functions declarations if fmv disabled
10285 AddToScope = false;
10286 return NewFD;
10287 }
10288
10289 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10290 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10291 // type.
10292 //
10293 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10294 // type declaration will generate a compilation error.
10295 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10296 if (AddressSpace != LangAS::Default) {
10297 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10298 NewFD->setInvalidDecl();
10299 }
10300 }
10301
10302 if (!getLangOpts().CPlusPlus) {
10303 // Perform semantic checking on the function declaration.
10304 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10305 CheckMain(NewFD, D.getDeclSpec());
10306
10307 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10308 CheckMSVCRTEntryPoint(NewFD);
10309
10310 if (!NewFD->isInvalidDecl())
10311 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10312 isMemberSpecialization,
10313 D.isFunctionDefinition()));
10314 else if (!Previous.empty())
10315 // Recover gracefully from an invalid redeclaration.
10316 D.setRedeclaration(true);
10317 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10318 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10319 "previous declaration set still overloaded");
10320
10321 // Diagnose no-prototype function declarations with calling conventions that
10322 // don't support variadic calls. Only do this in C and do it after merging
10323 // possibly prototyped redeclarations.
10324 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10325 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
10326 CallingConv CC = FT->getExtInfo().getCC();
10327 if (!supportsVariadicCall(CC)) {
10328 // Windows system headers sometimes accidentally use stdcall without
10329 // (void) parameters, so we relax this to a warning.
10330 int DiagID =
10331 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10332 Diag(NewFD->getLocation(), DiagID)
10334 }
10335 }
10336
10342 } else {
10343 // C++11 [replacement.functions]p3:
10344 // The program's definitions shall not be specified as inline.
10345 //
10346 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10347 //
10348 // Suppress the diagnostic if the function is __attribute__((used)), since
10349 // that forces an external definition to be emitted.
10350 if (D.getDeclSpec().isInlineSpecified() &&
10352 !NewFD->hasAttr<UsedAttr>())
10353 Diag(D.getDeclSpec().getInlineSpecLoc(),
10354 diag::ext_operator_new_delete_declared_inline)
10355 << NewFD->getDeclName();
10356
10357 if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
10358 // C++20 [dcl.decl.general]p4:
10359 // The optional requires-clause in an init-declarator or
10360 // member-declarator shall be present only if the declarator declares a
10361 // templated function.
10362 //
10363 // C++20 [temp.pre]p8:
10364 // An entity is templated if it is
10365 // - a template,
10366 // - an entity defined or created in a templated entity,
10367 // - a member of a templated entity,
10368 // - an enumerator for an enumeration that is a templated entity, or
10369 // - the closure type of a lambda-expression appearing in the
10370 // declaration of a templated entity.
10371 //
10372 // [Note 6: A local class, a local or block variable, or a friend
10373 // function defined in a templated entity is a templated entity.
10374 // — end note]
10375 //
10376 // A templated function is a function template or a function that is
10377 // templated. A templated class is a class template or a class that is
10378 // templated. A templated variable is a variable template or a variable
10379 // that is templated.
10380 if (!FunctionTemplate) {
10381 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10382 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10383 // An explicit specialization shall not have a trailing
10384 // requires-clause unless it declares a function template.
10385 //
10386 // Since a friend function template specialization cannot be
10387 // definition, and since a non-template friend declaration with a
10388 // trailing requires-clause must be a definition, we diagnose
10389 // friend function template specializations with trailing
10390 // requires-clauses on the same path as explicit specializations
10391 // even though they aren't necessarily prohibited by the same
10392 // language rule.
10393 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10394 << isFriend;
10395 } else if (isFriend && NewFD->isTemplated() &&
10396 !D.isFunctionDefinition()) {
10397 // C++ [temp.friend]p9:
10398 // A non-template friend declaration with a requires-clause shall be
10399 // a definition.
10400 Diag(NewFD->getBeginLoc(),
10401 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10402 NewFD->setInvalidDecl();
10403 } else if (!NewFD->isTemplated() ||
10404 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10405 Diag(TRC->getBeginLoc(),
10406 diag::err_constrained_non_templated_function);
10407 }
10408 }
10409 }
10410
10411 // We do not add HD attributes to specializations here because
10412 // they may have different constexpr-ness compared to their
10413 // templates and, after maybeAddHostDeviceAttrs() is applied,
10414 // may end up with different effective targets. Instead, a
10415 // specialization inherits its target attributes from its template
10416 // in the CheckFunctionTemplateSpecialization() call below.
10417 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10419
10420 // Handle explicit specializations of function templates
10421 // and friend function declarations with an explicit
10422 // template argument list.
10423 if (isFunctionTemplateSpecialization) {
10424 bool isDependentSpecialization = false;
10425 if (isFriend) {
10426 // For friend function specializations, this is a dependent
10427 // specialization if its semantic context is dependent, its
10428 // type is dependent, or if its template-id is dependent.
10429 isDependentSpecialization =
10430 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10431 (HasExplicitTemplateArgs &&
10434 TemplateArgs.arguments()));
10435 assert((!isDependentSpecialization ||
10436 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10437 "dependent friend function specialization without template "
10438 "args");
10439 } else {
10440 // For class-scope explicit specializations of function templates,
10441 // if the lexical context is dependent, then the specialization
10442 // is dependent.
10443 isDependentSpecialization =
10445 }
10446
10447 TemplateArgumentListInfo *ExplicitTemplateArgs =
10448 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10449 if (isDependentSpecialization) {
10450 // If it's a dependent specialization, it may not be possible
10451 // to determine the primary template (for explicit specializations)
10452 // or befriended declaration (for friends) until the enclosing
10453 // template is instantiated. In such cases, we store the declarations
10454 // found by name lookup and defer resolution until instantiation.
10456 NewFD, ExplicitTemplateArgs, Previous))
10457 NewFD->setInvalidDecl();
10458 } else if (!NewFD->isInvalidDecl()) {
10459 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10460 Previous))
10461 NewFD->setInvalidDecl();
10462 }
10463 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
10465 NewFD->setInvalidDecl();
10466 }
10467
10468 // Perform semantic checking on the function declaration.
10469 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10470 CheckMain(NewFD, D.getDeclSpec());
10471
10472 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10473 CheckMSVCRTEntryPoint(NewFD);
10474
10475 if (!NewFD->isInvalidDecl())
10476 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
10477 isMemberSpecialization,
10478 D.isFunctionDefinition()));
10479 else if (!Previous.empty())
10480 // Recover gracefully from an invalid redeclaration.
10481 D.setRedeclaration(true);
10482
10483 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10484 !D.isRedeclaration() ||
10485 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
10486 "previous declaration set still overloaded");
10487
10488 NamedDecl *PrincipalDecl = (FunctionTemplate
10489 ? cast<NamedDecl>(FunctionTemplate)
10490 : NewFD);
10491
10492 if (isFriend && NewFD->getPreviousDecl()) {
10493 AccessSpecifier Access = AS_public;
10494 if (!NewFD->isInvalidDecl())
10495 Access = NewFD->getPreviousDecl()->getAccess();
10496
10497 NewFD->setAccess(Access);
10498 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10499 }
10500
10501 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10503 PrincipalDecl->setNonMemberOperator();
10504
10505 // If we have a function template, check the template parameter
10506 // list. This will check and merge default template arguments.
10507 if (FunctionTemplate) {
10508 FunctionTemplateDecl *PrevTemplate =
10509 FunctionTemplate->getPreviousDecl();
10510 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10511 PrevTemplate ? PrevTemplate->getTemplateParameters()
10512 : nullptr,
10513 D.getDeclSpec().isFriendSpecified()
10514 ? (D.isFunctionDefinition()
10517 : (D.getCXXScopeSpec().isSet() &&
10518 DC && DC->isRecord() &&
10519 DC->isDependentContext())
10522 }
10523
10524 if (NewFD->isInvalidDecl()) {
10525 // Ignore all the rest of this.
10526 } else if (!D.isRedeclaration()) {
10527 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10528 AddToScope };
10529 // Fake up an access specifier if it's supposed to be a class member.
10530 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10531 NewFD->setAccess(AS_public);
10532
10533 // Qualified decls generally require a previous declaration.
10534 if (D.getCXXScopeSpec().isSet()) {
10535 // ...with the major exception of templated-scope or
10536 // dependent-scope friend declarations.
10537
10538 // TODO: we currently also suppress this check in dependent
10539 // contexts because (1) the parameter depth will be off when
10540 // matching friend templates and (2) we might actually be
10541 // selecting a friend based on a dependent factor. But there
10542 // are situations where these conditions don't apply and we
10543 // can actually do this check immediately.
10544 //
10545 // Unless the scope is dependent, it's always an error if qualified
10546 // redeclaration lookup found nothing at all. Diagnose that now;
10547 // nothing will diagnose that error later.
10548 if (isFriend &&
10549 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
10550 (!Previous.empty() && CurContext->isDependentContext()))) {
10551 // ignore these
10552 } else if (NewFD->isCPUDispatchMultiVersion() ||
10553 NewFD->isCPUSpecificMultiVersion()) {
10554 // ignore this, we allow the redeclaration behavior here to create new
10555 // versions of the function.
10556 } else {
10557 // The user tried to provide an out-of-line definition for a
10558 // function that is a member of a class or namespace, but there
10559 // was no such member function declared (C++ [class.mfct]p2,
10560 // C++ [namespace.memdef]p2). For example:
10561 //
10562 // class X {
10563 // void f() const;
10564 // };
10565 //
10566 // void X::f() { } // ill-formed
10567 //
10568 // Complain about this problem, and attempt to suggest close
10569 // matches (e.g., those that differ only in cv-qualifiers and
10570 // whether the parameter types are references).
10571
10573 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10574 AddToScope = ExtraArgs.AddToScope;
10575 return Result;
10576 }
10577 }
10578
10579 // Unqualified local friend declarations are required to resolve
10580 // to something.
10581 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10583 *this, Previous, NewFD, ExtraArgs, true, S)) {
10584 AddToScope = ExtraArgs.AddToScope;
10585 return Result;
10586 }
10587 }
10588 } else if (!D.isFunctionDefinition() &&
10589 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10590 !isFriend && !isFunctionTemplateSpecialization &&
10591 !isMemberSpecialization) {
10592 // An out-of-line member function declaration must also be a
10593 // definition (C++ [class.mfct]p2).
10594 // Note that this is not the case for explicit specializations of
10595 // function templates or member functions of class templates, per
10596 // C++ [temp.expl.spec]p2. We also allow these declarations as an
10597 // extension for compatibility with old SWIG code which likes to
10598 // generate them.
10599 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10600 << D.getCXXScopeSpec().getRange();
10601 }
10602 }
10603
10604 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
10605 // Any top level function could potentially be specified as an entry.
10606 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
10607 HLSL().ActOnTopLevelFunction(NewFD);
10608
10609 if (NewFD->hasAttr<HLSLShaderAttr>())
10610 HLSL().CheckEntryPoint(NewFD);
10611 }
10612
10613 // If this is the first declaration of a library builtin function, add
10614 // attributes as appropriate.
10615 if (!D.isRedeclaration()) {
10616 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10617 if (unsigned BuiltinID = II->getBuiltinID()) {
10618 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
10619 if (!InStdNamespace &&
10621 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10622 // Validate the type matches unless this builtin is specified as
10623 // matching regardless of its declared type.
10624 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10625 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10626 } else {
10628 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10629 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10630
10631 if (!Error && !BuiltinType.isNull() &&
10633 NewFD->getType(), BuiltinType))
10634 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10635 }
10636 }
10637 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
10638 isStdBuiltin(Context, NewFD, BuiltinID)) {
10639 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10640 }
10641 }
10642 }
10643 }
10644
10645 ProcessPragmaWeak(S, NewFD);
10646 checkAttributesAfterMerging(*this, *NewFD);
10647
10649
10650 if (NewFD->hasAttr<OverloadableAttr>() &&
10651 !NewFD->getType()->getAs<FunctionProtoType>()) {
10652 Diag(NewFD->getLocation(),
10653 diag::err_attribute_overloadable_no_prototype)
10654 << NewFD;
10655 NewFD->dropAttr<OverloadableAttr>();
10656 }
10657
10658 // If there's a #pragma GCC visibility in scope, and this isn't a class
10659 // member, set the visibility of this function.
10660 if (!DC->isRecord() && NewFD->isExternallyVisible())
10662
10663 // If there's a #pragma clang arc_cf_code_audited in scope, consider
10664 // marking the function.
10665 ObjC().AddCFAuditedAttribute(NewFD);
10666
10667 // If this is a function definition, check if we have to apply any
10668 // attributes (i.e. optnone and no_builtin) due to a pragma.
10669 if (D.isFunctionDefinition()) {
10670 AddRangeBasedOptnone(NewFD);
10672 AddSectionMSAllocText(NewFD);
10674 }
10675
10676 // If this is the first declaration of an extern C variable, update
10677 // the map of such variables.
10678 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10679 isIncompleteDeclExternC(*this, NewFD))
10681
10682 // Set this FunctionDecl's range up to the right paren.
10683 NewFD->setRangeEnd(D.getSourceRange().getEnd());
10684
10685 if (D.isRedeclaration() && !Previous.empty()) {
10686 NamedDecl *Prev = Previous.getRepresentativeDecl();
10687 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10688 isMemberSpecialization ||
10689 isFunctionTemplateSpecialization,
10690 D.isFunctionDefinition());
10691 }
10692
10693 if (getLangOpts().CUDA) {
10694 IdentifierInfo *II = NewFD->getIdentifier();
10695 if (II && II->isStr(CUDA().getConfigureFuncName()) &&
10696 !NewFD->isInvalidDecl() &&
10699 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10702 }
10703
10704 // Variadic functions, other than a *declaration* of printf, are not allowed
10705 // in device-side CUDA code, unless someone passed
10706 // -fcuda-allow-variadic-functions.
10707 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10708 (NewFD->hasAttr<CUDADeviceAttr>() ||
10709 NewFD->hasAttr<CUDAGlobalAttr>()) &&
10710 !(II && II->isStr("printf") && NewFD->isExternC() &&
10711 !D.isFunctionDefinition())) {
10712 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10713 }
10714 }
10715
10717
10718
10719
10720 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10721 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10722 if (SC == SC_Static) {
10723 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10724 D.setInvalidType();
10725 }
10726
10727 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10728 if (!NewFD->getReturnType()->isVoidType()) {
10729 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10730 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10731 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10732 : FixItHint());
10733 D.setInvalidType();
10734 }
10735
10737 for (auto *Param : NewFD->parameters())
10738 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10739
10740 if (getLangOpts().OpenCLCPlusPlus) {
10741 if (DC->isRecord()) {
10742 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10743 D.setInvalidType();
10744 }
10745 if (FunctionTemplate) {
10746 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10747 D.setInvalidType();
10748 }
10749 }
10750 }
10751
10752 if (getLangOpts().CPlusPlus) {
10753 // Precalculate whether this is a friend function template with a constraint
10754 // that depends on an enclosing template, per [temp.friend]p9.
10755 if (isFriend && FunctionTemplate &&
10758
10759 // C++ [temp.friend]p9:
10760 // A friend function template with a constraint that depends on a
10761 // template parameter from an enclosing template shall be a definition.
10762 if (!D.isFunctionDefinition()) {
10763 Diag(NewFD->getBeginLoc(),
10764 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
10765 NewFD->setInvalidDecl();
10766 }
10767 }
10768
10769 if (FunctionTemplate) {
10770 if (NewFD->isInvalidDecl())
10771 FunctionTemplate->setInvalidDecl();
10772 return FunctionTemplate;
10773 }
10774
10775 if (isMemberSpecialization && !NewFD->isInvalidDecl())
10777 }
10778
10779 for (const ParmVarDecl *Param : NewFD->parameters()) {
10780 QualType PT = Param->getType();
10781
10782 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10783 // types.
10784 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10785 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10786 QualType ElemTy = PipeTy->getElementType();
10787 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10788 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10789 D.setInvalidType();
10790 }
10791 }
10792 }
10793 // WebAssembly tables can't be used as function parameters.
10794 if (Context.getTargetInfo().getTriple().isWasm()) {
10796 Diag(Param->getTypeSpecStartLoc(),
10797 diag::err_wasm_table_as_function_parameter);
10798 D.setInvalidType();
10799 }
10800 }
10801 }
10802
10803 // Diagnose availability attributes. Availability cannot be used on functions
10804 // that are run during load/unload.
10805 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10806 if (NewFD->hasAttr<ConstructorAttr>()) {
10807 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10808 << 1;
10809 NewFD->dropAttr<AvailabilityAttr>();
10810 }
10811 if (NewFD->hasAttr<DestructorAttr>()) {
10812 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10813 << 2;
10814 NewFD->dropAttr<AvailabilityAttr>();
10815 }
10816 }
10817
10818 // Diagnose no_builtin attribute on function declaration that are not a
10819 // definition.
10820 // FIXME: We should really be doing this in
10821 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10822 // the FunctionDecl and at this point of the code
10823 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10824 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10825 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10826 switch (D.getFunctionDefinitionKind()) {
10829 Diag(NBA->getLocation(),
10830 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10831 << NBA->getSpelling();
10832 break;
10834 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10835 << NBA->getSpelling();
10836 break;
10838 break;
10839 }
10840
10841 // Similar to no_builtin logic above, at this point of the code
10842 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
10843 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10845 !NewFD->isInvalidDecl() &&
10846 D.getFunctionDefinitionKind() == FunctionDefinitionKind::Declaration)
10847 ExternalDeclarations.push_back(NewFD);
10848
10849 return NewFD;
10850}
10851
10852/// Return a CodeSegAttr from a containing class. The Microsoft docs say
10853/// when __declspec(code_seg) "is applied to a class, all member functions of
10854/// the class and nested classes -- this includes compiler-generated special
10855/// member functions -- are put in the specified segment."
10856/// The actual behavior is a little more complicated. The Microsoft compiler
10857/// won't check outer classes if there is an active value from #pragma code_seg.
10858/// The CodeSeg is always applied from the direct parent but only from outer
10859/// classes when the #pragma code_seg stack is empty. See:
10860/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10861/// available since MS has removed the page.
10863 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10864 if (!Method)
10865 return nullptr;
10866 const CXXRecordDecl *Parent = Method->getParent();
10867 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10868 Attr *NewAttr = SAttr->clone(S.getASTContext());
10869 NewAttr->setImplicit(true);
10870 return NewAttr;
10871 }
10872
10873 // The Microsoft compiler won't check outer classes for the CodeSeg
10874 // when the #pragma code_seg stack is active.
10875 if (S.CodeSegStack.CurrentValue)
10876 return nullptr;
10877
10878 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10879 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10880 Attr *NewAttr = SAttr->clone(S.getASTContext());
10881 NewAttr->setImplicit(true);
10882 return NewAttr;
10883 }
10884 }
10885 return nullptr;
10886}
10887
10889 bool IsDefinition) {
10890 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10891 return A;
10892 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10893 CodeSegStack.CurrentValue)
10894 return SectionAttr::CreateImplicit(
10895 getASTContext(), CodeSegStack.CurrentValue->getString(),
10896 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
10897 return nullptr;
10898}
10899
10901 QualType NewT, QualType OldT) {
10903 return true;
10904
10905 // For dependently-typed local extern declarations and friends, we can't
10906 // perform a correct type check in general until instantiation:
10907 //
10908 // int f();
10909 // template<typename T> void g() { T f(); }
10910 //
10911 // (valid if g() is only instantiated with T = int).
10912 if (NewT->isDependentType() &&
10913 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10914 return false;
10915
10916 // Similarly, if the previous declaration was a dependent local extern
10917 // declaration, we don't really know its type yet.
10918 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10919 return false;
10920
10921 return true;
10922}
10923
10926 return true;
10927
10928 // Don't chain dependent friend function definitions until instantiation, to
10929 // permit cases like
10930 //
10931 // void func();
10932 // template<typename T> class C1 { friend void func() {} };
10933 // template<typename T> class C2 { friend void func() {} };
10934 //
10935 // ... which is valid if only one of C1 and C2 is ever instantiated.
10936 //
10937 // FIXME: This need only apply to function definitions. For now, we proxy
10938 // this by checking for a file-scope function. We do not want this to apply
10939 // to friend declarations nominating member functions, because that gets in
10940 // the way of access checks.
10942 return false;
10943
10944 auto *VD = dyn_cast<ValueDecl>(D);
10945 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10946 return !VD || !PrevVD ||
10947 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10948 PrevVD->getType());
10949}
10950
10951/// Check the target or target_version attribute of the function for
10952/// MultiVersion validity.
10953///
10954/// Returns true if there was an error, false otherwise.
10955static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10956 const auto *TA = FD->getAttr<TargetAttr>();
10957 const auto *TVA = FD->getAttr<TargetVersionAttr>();
10958 assert(
10959 (TA || TVA) &&
10960 "MultiVersion candidate requires a target or target_version attribute");
10962 enum ErrType { Feature = 0, Architecture = 1 };
10963
10964 if (TA) {
10965 ParsedTargetAttr ParseInfo =
10966 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
10967 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
10968 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10969 << Architecture << ParseInfo.CPU;
10970 return true;
10971 }
10972 for (const auto &Feat : ParseInfo.Features) {
10973 auto BareFeat = StringRef{Feat}.substr(1);
10974 if (Feat[0] == '-') {
10975 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10976 << Feature << ("no-" + BareFeat).str();
10977 return true;
10978 }
10979
10980 if (!TargetInfo.validateCpuSupports(BareFeat) ||
10981 !TargetInfo.isValidFeatureName(BareFeat)) {
10982 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10983 << Feature << BareFeat;
10984 return true;
10985 }
10986 }
10987 }
10988
10989 if (TVA) {
10991 TVA->getFeatures(Feats);
10992 for (const auto &Feat : Feats) {
10993 if (!TargetInfo.validateCpuSupports(Feat)) {
10994 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10995 << Feature << Feat;
10996 return true;
10997 }
10998 }
10999 }
11000 return false;
11001}
11002
11003// Provide a white-list of attributes that are allowed to be combined with
11004// multiversion functions.
11006 MultiVersionKind MVKind) {
11007 // Note: this list/diagnosis must match the list in
11008 // checkMultiversionAttributesAllSame.
11009 switch (Kind) {
11010 default:
11011 return false;
11012 case attr::Used:
11013 return MVKind == MultiVersionKind::Target;
11014 case attr::NonNull:
11015 case attr::NoThrow:
11016 return true;
11017 }
11018}
11019
11021 const FunctionDecl *FD,
11022 const FunctionDecl *CausedFD,
11023 MultiVersionKind MVKind) {
11024 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11025 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11026 << static_cast<unsigned>(MVKind) << A;
11027 if (CausedFD)
11028 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11029 return true;
11030 };
11031
11032 for (const Attr *A : FD->attrs()) {
11033 switch (A->getKind()) {
11034 case attr::CPUDispatch:
11035 case attr::CPUSpecific:
11036 if (MVKind != MultiVersionKind::CPUDispatch &&
11038 return Diagnose(S, A);
11039 break;
11040 case attr::Target:
11041 if (MVKind != MultiVersionKind::Target)
11042 return Diagnose(S, A);
11043 break;
11044 case attr::TargetVersion:
11045 if (MVKind != MultiVersionKind::TargetVersion &&
11047 return Diagnose(S, A);
11048 break;
11049 case attr::TargetClones:
11050 if (MVKind != MultiVersionKind::TargetClones &&
11052 return Diagnose(S, A);
11053 break;
11054 default:
11055 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11056 return Diagnose(S, A);
11057 break;
11058 }
11059 }
11060 return false;
11061}
11062
11064 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11065 const PartialDiagnostic &NoProtoDiagID,
11066 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11067 const PartialDiagnosticAt &NoSupportDiagIDAt,
11068 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11069 bool ConstexprSupported, bool CLinkageMayDiffer) {
11070 enum DoesntSupport {
11071 FuncTemplates = 0,
11072 VirtFuncs = 1,
11073 DeducedReturn = 2,
11074 Constructors = 3,
11075 Destructors = 4,
11076 DeletedFuncs = 5,
11077 DefaultedFuncs = 6,
11078 ConstexprFuncs = 7,
11079 ConstevalFuncs = 8,
11080 Lambda = 9,
11081 };
11082 enum Different {
11083 CallingConv = 0,
11084 ReturnType = 1,
11085 ConstexprSpec = 2,
11086 InlineSpec = 3,
11087 Linkage = 4,
11088 LanguageLinkage = 5,
11089 };
11090
11091 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11092 !OldFD->getType()->getAs<FunctionProtoType>()) {
11093 Diag(OldFD->getLocation(), NoProtoDiagID);
11094 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11095 return true;
11096 }
11097
11098 if (NoProtoDiagID.getDiagID() != 0 &&
11099 !NewFD->getType()->getAs<FunctionProtoType>())
11100 return Diag(NewFD->getLocation(), NoProtoDiagID);
11101
11102 if (!TemplatesSupported &&
11104 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11105 << FuncTemplates;
11106
11107 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11108 if (NewCXXFD->isVirtual())
11109 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11110 << VirtFuncs;
11111
11112 if (isa<CXXConstructorDecl>(NewCXXFD))
11113 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11114 << Constructors;
11115
11116 if (isa<CXXDestructorDecl>(NewCXXFD))
11117 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11118 << Destructors;
11119 }
11120
11121 if (NewFD->isDeleted())
11122 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11123 << DeletedFuncs;
11124
11125 if (NewFD->isDefaulted())
11126 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11127 << DefaultedFuncs;
11128
11129 if (!ConstexprSupported && NewFD->isConstexpr())
11130 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11131 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11132
11133 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11134 const auto *NewType = cast<FunctionType>(NewQType);
11135 QualType NewReturnType = NewType->getReturnType();
11136
11137 if (NewReturnType->isUndeducedType())
11138 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11139 << DeducedReturn;
11140
11141 // Ensure the return type is identical.
11142 if (OldFD) {
11143 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11144 const auto *OldType = cast<FunctionType>(OldQType);
11145 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11146 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11147
11148 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
11149 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11150
11151 QualType OldReturnType = OldType->getReturnType();
11152
11153 if (OldReturnType != NewReturnType)
11154 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11155
11156 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11157 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11158
11159 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11160 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11161
11162 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11163 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11164
11165 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11166 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11167
11169 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
11170 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
11171 return true;
11172 }
11173 return false;
11174}
11175
11177 const FunctionDecl *NewFD,
11178 bool CausesMV,
11179 MultiVersionKind MVKind) {
11181 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11182 if (OldFD)
11183 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11184 return true;
11185 }
11186
11187 bool IsCPUSpecificCPUDispatchMVKind =
11190
11191 if (CausesMV && OldFD &&
11192 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11193 return true;
11194
11195 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11196 return true;
11197
11198 // Only allow transition to MultiVersion if it hasn't been used.
11199 if (OldFD && CausesMV && OldFD->isUsed(false))
11200 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11201
11203 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11205 S.PDiag(diag::note_multiversioning_caused_here)),
11207 S.PDiag(diag::err_multiversion_doesnt_support)
11208 << static_cast<unsigned>(MVKind)),
11210 S.PDiag(diag::err_multiversion_diff)),
11211 /*TemplatesSupported=*/false,
11212 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11213 /*CLinkageMayDiffer=*/false);
11214}
11215
11216/// Check the validity of a multiversion function declaration that is the
11217/// first of its kind. Also sets the multiversion'ness' of the function itself.
11218///
11219/// This sets NewFD->isInvalidDecl() to true if there was an error.
11220///
11221/// Returns true if there was an error, false otherwise.
11224 assert(MVKind != MultiVersionKind::None &&
11225 "Function lacks multiversion attribute");
11226 const auto *TA = FD->getAttr<TargetAttr>();
11227 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11228 // The target attribute only causes MV if this declaration is the default,
11229 // otherwise it is treated as a normal function.
11230 if (TA && !TA->isDefaultVersion())
11231 return false;
11232 // The target_version attribute only causes Multiversioning if this
11233 // declaration is NOT the default version.
11234 if (TVA && TVA->isDefaultVersion())
11235 return false;
11236
11237 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11238 FD->setInvalidDecl();
11239 return true;
11240 }
11241
11242 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11243 FD->setInvalidDecl();
11244 return true;
11245 }
11246
11247 FD->setIsMultiVersion();
11248 return false;
11249}
11250
11252 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11254 return true;
11255 }
11256
11257 return false;
11258}
11259
11261 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64())
11262 return;
11263
11264 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11265 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11266
11267 if (MVKindTo == MultiVersionKind::None &&
11268 (MVKindFrom == MultiVersionKind::TargetVersion ||
11269 MVKindFrom == MultiVersionKind::TargetClones))
11270 To->addAttr(TargetVersionAttr::CreateImplicit(
11271 To->getASTContext(), "default", To->getSourceRange()));
11272}
11273
11275 FunctionDecl *NewFD,
11276 bool &Redeclaration,
11277 NamedDecl *&OldDecl,
11279 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11280
11281 // The definitions should be allowed in any order. If we have discovered
11282 // a new target version and the preceeding was the default, then add the
11283 // corresponding attribute to it.
11284 patchDefaultTargetVersion(NewFD, OldFD);
11285
11286 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11287 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11288 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11289
11290 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11291 // to change, this is a simple redeclaration.
11292 if (NewTA && !NewTA->isDefaultVersion() &&
11293 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11294 return false;
11295
11296 // The target_version attribute only causes Multiversioning if this
11297 // declaration is NOT the default version.
11298 if (NewTVA && NewTVA->isDefaultVersion())
11299 return false;
11300
11301 // Otherwise, this decl causes MultiVersioning.
11302 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11305 NewFD->setInvalidDecl();
11306 return true;
11307 }
11308
11309 if (CheckMultiVersionValue(S, NewFD)) {
11310 NewFD->setInvalidDecl();
11311 return true;
11312 }
11313
11314 // If this is 'default', permit the forward declaration.
11315 if (NewTA && NewTA->isDefaultVersion() && !OldTA) {
11316 Redeclaration = true;
11317 OldDecl = OldFD;
11318 OldFD->setIsMultiVersion();
11319 NewFD->setIsMultiVersion();
11320 return false;
11321 }
11322
11323 if (CheckMultiVersionValue(S, OldFD)) {
11324 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11325 NewFD->setInvalidDecl();
11326 return true;
11327 }
11328
11329 if (NewTA) {
11330 ParsedTargetAttr OldParsed =
11332 OldTA->getFeaturesStr());
11333 llvm::sort(OldParsed.Features);
11334 ParsedTargetAttr NewParsed =
11336 NewTA->getFeaturesStr());
11337 // Sort order doesn't matter, it just needs to be consistent.
11338 llvm::sort(NewParsed.Features);
11339 if (OldParsed == NewParsed) {
11340 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11341 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11342 NewFD->setInvalidDecl();
11343 return true;
11344 }
11345 }
11346
11347 for (const auto *FD : OldFD->redecls()) {
11348 const auto *CurTA = FD->getAttr<TargetAttr>();
11349 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11350 // We allow forward declarations before ANY multiversioning attributes, but
11351 // nothing after the fact.
11353 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11354 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11355 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11356 << (NewTA ? 0 : 2);
11357 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11358 NewFD->setInvalidDecl();
11359 return true;
11360 }
11361 }
11362
11363 OldFD->setIsMultiVersion();
11364 NewFD->setIsMultiVersion();
11365 Redeclaration = false;
11366 OldDecl = nullptr;
11367 Previous.clear();
11368 return false;
11369}
11370
11372 MultiVersionKind OldKind = Old->getMultiVersionKind();
11373 MultiVersionKind NewKind = New->getMultiVersionKind();
11374
11375 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11376 NewKind == MultiVersionKind::None)
11377 return true;
11378
11379 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11380 switch (OldKind) {
11382 return NewKind == MultiVersionKind::TargetClones;
11384 return NewKind == MultiVersionKind::TargetVersion;
11385 default:
11386 return false;
11387 }
11388 } else {
11389 switch (OldKind) {
11391 return NewKind == MultiVersionKind::CPUSpecific;
11393 return NewKind == MultiVersionKind::CPUDispatch;
11394 default:
11395 return false;
11396 }
11397 }
11398}
11399
11400/// Check the validity of a new function declaration being added to an existing
11401/// multiversioned declaration collection.
11403 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11404 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11405 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11407
11408 // Disallow mixing of multiversioning types.
11409 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11410 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11411 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11412 NewFD->setInvalidDecl();
11413 return true;
11414 }
11415
11416 // Add the default target_version attribute if it's missing.
11417 patchDefaultTargetVersion(OldFD, NewFD);
11418 patchDefaultTargetVersion(NewFD, OldFD);
11419
11420 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11421 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11422 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11423 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11424
11425 ParsedTargetAttr NewParsed;
11426 if (NewTA) {
11428 NewTA->getFeaturesStr());
11429 llvm::sort(NewParsed.Features);
11430 }
11432 if (NewTVA) {
11433 NewTVA->getFeatures(NewFeats);
11434 llvm::sort(NewFeats);
11435 }
11436
11437 bool UseMemberUsingDeclRules =
11438 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11439
11440 bool MayNeedOverloadableChecks =
11442
11443 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11444 // of a previous member of the MultiVersion set.
11445 for (NamedDecl *ND : Previous) {
11446 FunctionDecl *CurFD = ND->getAsFunction();
11447 if (!CurFD || CurFD->isInvalidDecl())
11448 continue;
11449 if (MayNeedOverloadableChecks &&
11450 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11451 continue;
11452
11453 switch (NewMVKind) {
11455 assert(OldMVKind == MultiVersionKind::TargetClones &&
11456 "Only target_clones can be omitted in subsequent declarations");
11457 break;
11459 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11460 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11461 NewFD->setIsMultiVersion();
11462 Redeclaration = true;
11463 OldDecl = ND;
11464 return false;
11465 }
11466
11467 ParsedTargetAttr CurParsed =
11469 CurTA->getFeaturesStr());
11470 llvm::sort(CurParsed.Features);
11471 if (CurParsed == NewParsed) {
11472 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11473 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11474 NewFD->setInvalidDecl();
11475 return true;
11476 }
11477 break;
11478 }
11480 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11481 if (CurTVA->getName() == NewTVA->getName()) {
11482 NewFD->setIsMultiVersion();
11483 Redeclaration = true;
11484 OldDecl = ND;
11485 return false;
11486 }
11488 CurTVA->getFeatures(CurFeats);
11489 llvm::sort(CurFeats);
11490
11491 if (CurFeats == NewFeats) {
11492 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11493 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11494 NewFD->setInvalidDecl();
11495 return true;
11496 }
11497 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11498 // Default
11499 if (NewFeats.empty())
11500 break;
11501
11502 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11504 CurClones->getFeatures(CurFeats, I);
11505 llvm::sort(CurFeats);
11506
11507 if (CurFeats == NewFeats) {
11508 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11509 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11510 NewFD->setInvalidDecl();
11511 return true;
11512 }
11513 }
11514 }
11515 break;
11516 }
11518 assert(NewClones && "MultiVersionKind does not match attribute type");
11519 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11520 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11521 !std::equal(CurClones->featuresStrs_begin(),
11522 CurClones->featuresStrs_end(),
11523 NewClones->featuresStrs_begin())) {
11524 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11525 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11526 NewFD->setInvalidDecl();
11527 return true;
11528 }
11529 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11531 CurTVA->getFeatures(CurFeats);
11532 llvm::sort(CurFeats);
11533
11534 // Default
11535 if (CurFeats.empty())
11536 break;
11537
11538 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11539 NewFeats.clear();
11540 NewClones->getFeatures(NewFeats, I);
11541 llvm::sort(NewFeats);
11542
11543 if (CurFeats == NewFeats) {
11544 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11545 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11546 NewFD->setInvalidDecl();
11547 return true;
11548 }
11549 }
11550 break;
11551 }
11552 Redeclaration = true;
11553 OldDecl = CurFD;
11554 NewFD->setIsMultiVersion();
11555 return false;
11556 }
11559 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
11560 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
11561 // Handle CPUDispatch/CPUSpecific versions.
11562 // Only 1 CPUDispatch function is allowed, this will make it go through
11563 // the redeclaration errors.
11564 if (NewMVKind == MultiVersionKind::CPUDispatch &&
11565 CurFD->hasAttr<CPUDispatchAttr>()) {
11566 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
11567 std::equal(
11568 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
11569 NewCPUDisp->cpus_begin(),
11570 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11571 return Cur->getName() == New->getName();
11572 })) {
11573 NewFD->setIsMultiVersion();
11574 Redeclaration = true;
11575 OldDecl = ND;
11576 return false;
11577 }
11578
11579 // If the declarations don't match, this is an error condition.
11580 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
11581 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11582 NewFD->setInvalidDecl();
11583 return true;
11584 }
11585 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
11586 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
11587 std::equal(
11588 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
11589 NewCPUSpec->cpus_begin(),
11590 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
11591 return Cur->getName() == New->getName();
11592 })) {
11593 NewFD->setIsMultiVersion();
11594 Redeclaration = true;
11595 OldDecl = ND;
11596 return false;
11597 }
11598
11599 // Only 1 version of CPUSpecific is allowed for each CPU.
11600 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
11601 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
11602 if (CurII == NewII) {
11603 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
11604 << NewII;
11605 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11606 NewFD->setInvalidDecl();
11607 return true;
11608 }
11609 }
11610 }
11611 }
11612 break;
11613 }
11614 }
11615 }
11616
11617 // Else, this is simply a non-redecl case. Checking the 'value' is only
11618 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
11619 // handled in the attribute adding step.
11620 if ((NewMVKind == MultiVersionKind::TargetVersion ||
11621 NewMVKind == MultiVersionKind::Target) &&
11622 CheckMultiVersionValue(S, NewFD)) {
11623 NewFD->setInvalidDecl();
11624 return true;
11625 }
11626
11627 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
11628 !OldFD->isMultiVersion(), NewMVKind)) {
11629 NewFD->setInvalidDecl();
11630 return true;
11631 }
11632
11633 // Permit forward declarations in the case where these two are compatible.
11634 if (!OldFD->isMultiVersion()) {
11635 OldFD->setIsMultiVersion();
11636 NewFD->setIsMultiVersion();
11637 Redeclaration = true;
11638 OldDecl = OldFD;
11639 return false;
11640 }
11641
11642 NewFD->setIsMultiVersion();
11643 Redeclaration = false;
11644 OldDecl = nullptr;
11645 Previous.clear();
11646 return false;
11647}
11648
11649/// Check the validity of a mulitversion function declaration.
11650/// Also sets the multiversion'ness' of the function itself.
11651///
11652/// This sets NewFD->isInvalidDecl() to true if there was an error.
11653///
11654/// Returns true if there was an error, false otherwise.
11656 bool &Redeclaration, NamedDecl *&OldDecl,
11658 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11659 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11660 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
11661 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
11662 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
11663 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
11664
11665 // Main isn't allowed to become a multiversion function, however it IS
11666 // permitted to have 'main' be marked with the 'target' optimization hint,
11667 // for 'target_version' only default is allowed.
11668 if (NewFD->isMain()) {
11669 if (MVKind != MultiVersionKind::None &&
11670 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
11671 !(MVKind == MultiVersionKind::TargetVersion &&
11672 NewTVA->isDefaultVersion())) {
11673 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
11674 NewFD->setInvalidDecl();
11675 return true;
11676 }
11677 return false;
11678 }
11679
11680 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
11681
11682 // Target attribute on AArch64 is not used for multiversioning
11683 if (NewTA && T.isAArch64())
11684 return false;
11685
11686 // Target attribute on RISCV is not used for multiversioning
11687 if (NewTA && T.isRISCV())
11688 return false;
11689
11690 if (!OldDecl || !OldDecl->getAsFunction() ||
11691 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
11692 NewFD->getDeclContext()->getRedeclContext())) {
11693 // If there's no previous declaration, AND this isn't attempting to cause
11694 // multiversioning, this isn't an error condition.
11695 if (MVKind == MultiVersionKind::None)
11696 return false;
11697 return CheckMultiVersionFirstFunction(S, NewFD);
11698 }
11699
11700 FunctionDecl *OldFD = OldDecl->getAsFunction();
11701
11702 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
11703 return false;
11704
11705 // Multiversioned redeclarations aren't allowed to omit the attribute, except
11706 // for target_clones and target_version.
11707 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
11710 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
11712 NewFD->setInvalidDecl();
11713 return true;
11714 }
11715
11716 if (!OldFD->isMultiVersion()) {
11717 switch (MVKind) {
11721 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
11723 if (OldFD->isUsed(false)) {
11724 NewFD->setInvalidDecl();
11725 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11726 }
11727 OldFD->setIsMultiVersion();
11728 break;
11729
11733 break;
11734 }
11735 }
11736
11737 // At this point, we have a multiversion function decl (in OldFD) AND an
11738 // appropriate attribute in the current function decl. Resolve that these are
11739 // still compatible with previous declarations.
11740 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
11741 NewCPUSpec, NewClones, Redeclaration,
11742 OldDecl, Previous);
11743}
11744
11746 bool IsPure = NewFD->hasAttr<PureAttr>();
11747 bool IsConst = NewFD->hasAttr<ConstAttr>();
11748
11749 // If there are no pure or const attributes, there's nothing to check.
11750 if (!IsPure && !IsConst)
11751 return;
11752
11753 // If the function is marked both pure and const, we retain the const
11754 // attribute because it makes stronger guarantees than the pure attribute, and
11755 // we drop the pure attribute explicitly to prevent later confusion about
11756 // semantics.
11757 if (IsPure && IsConst) {
11758 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
11759 NewFD->dropAttrs<PureAttr>();
11760 }
11761
11762 // Constructors and destructors are functions which return void, so are
11763 // handled here as well.
11764 if (NewFD->getReturnType()->isVoidType()) {
11765 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
11766 << IsConst;
11767 NewFD->dropAttrs<PureAttr, ConstAttr>();
11768 }
11769}
11770
11773 bool IsMemberSpecialization,
11774 bool DeclIsDefn) {
11775 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11776 "Variably modified return types are not handled here");
11777
11778 // Determine whether the type of this function should be merged with
11779 // a previous visible declaration. This never happens for functions in C++,
11780 // and always happens in C if the previous declaration was visible.
11781 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11782 !Previous.isShadowed();
11783
11784 bool Redeclaration = false;
11785 NamedDecl *OldDecl = nullptr;
11786 bool MayNeedOverloadableChecks = false;
11787
11788 // Merge or overload the declaration with an existing declaration of
11789 // the same name, if appropriate.
11790 if (!Previous.empty()) {
11791 // Determine whether NewFD is an overload of PrevDecl or
11792 // a declaration that requires merging. If it's an overload,
11793 // there's no more work to do here; we'll just add the new
11794 // function to the scope.
11796 NamedDecl *Candidate = Previous.getRepresentativeDecl();
11797 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11798 Redeclaration = true;
11799 OldDecl = Candidate;
11800 }
11801 } else {
11802 MayNeedOverloadableChecks = true;
11803 switch (CheckOverload(S, NewFD, Previous, OldDecl,
11804 /*NewIsUsingDecl*/ false)) {
11805 case Ovl_Match:
11806 Redeclaration = true;
11807 break;
11808
11809 case Ovl_NonFunction:
11810 Redeclaration = true;
11811 break;
11812
11813 case Ovl_Overload:
11814 Redeclaration = false;
11815 break;
11816 }
11817 }
11818 }
11819
11820 // Check for a previous extern "C" declaration with this name.
11821 if (!Redeclaration &&
11823 if (!Previous.empty()) {
11824 // This is an extern "C" declaration with the same name as a previous
11825 // declaration, and thus redeclares that entity...
11826 Redeclaration = true;
11827 OldDecl = Previous.getFoundDecl();
11828 MergeTypeWithPrevious = false;
11829
11830 // ... except in the presence of __attribute__((overloadable)).
11831 if (OldDecl->hasAttr<OverloadableAttr>() ||
11832 NewFD->hasAttr<OverloadableAttr>()) {
11833 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11834 MayNeedOverloadableChecks = true;
11835 Redeclaration = false;
11836 OldDecl = nullptr;
11837 }
11838 }
11839 }
11840 }
11841
11842 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11843 return Redeclaration;
11844
11845 // PPC MMA non-pointer types are not allowed as function return types.
11846 if (Context.getTargetInfo().getTriple().isPPC64() &&
11847 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11848 NewFD->setInvalidDecl();
11849 }
11850
11851 CheckConstPureAttributesUsage(*this, NewFD);
11852
11853 // C++ [dcl.spec.auto.general]p12:
11854 // Return type deduction for a templated function with a placeholder in its
11855 // declared type occurs when the definition is instantiated even if the
11856 // function body contains a return statement with a non-type-dependent
11857 // operand.
11858 //
11859 // C++ [temp.dep.expr]p3:
11860 // An id-expression is type-dependent if it is a template-id that is not a
11861 // concept-id and is dependent; or if its terminal name is:
11862 // - [...]
11863 // - associated by name lookup with one or more declarations of member
11864 // functions of a class that is the current instantiation declared with a
11865 // return type that contains a placeholder type,
11866 // - [...]
11867 //
11868 // If this is a templated function with a placeholder in its return type,
11869 // make the placeholder type dependent since it won't be deduced until the
11870 // definition is instantiated. We do this here because it needs to happen
11871 // for implicitly instantiated member functions/member function templates.
11872 if (getLangOpts().CPlusPlus14 &&
11873 (NewFD->isDependentContext() &&
11874 NewFD->getReturnType()->isUndeducedType())) {
11875 const FunctionProtoType *FPT =
11876 NewFD->getType()->castAs<FunctionProtoType>();
11877 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
11878 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
11879 FPT->getExtProtoInfo()));
11880 }
11881
11882 // C++11 [dcl.constexpr]p8:
11883 // A constexpr specifier for a non-static member function that is not
11884 // a constructor declares that member function to be const.
11885 //
11886 // This needs to be delayed until we know whether this is an out-of-line
11887 // definition of a static member function.
11888 //
11889 // This rule is not present in C++1y, so we produce a backwards
11890 // compatibility warning whenever it happens in C++11.
11891 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11892 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11893 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11894 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11895 CXXMethodDecl *OldMD = nullptr;
11896 if (OldDecl)
11897 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11898 if (!OldMD || !OldMD->isStatic()) {
11899 const FunctionProtoType *FPT =
11902 EPI.TypeQuals.addConst();
11904 FPT->getParamTypes(), EPI));
11905
11906 // Warn that we did this, if we're not performing template instantiation.
11907 // In that case, we'll have warned already when the template was defined.
11908 if (!inTemplateInstantiation()) {
11909 SourceLocation AddConstLoc;
11912 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11913
11914 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11915 << FixItHint::CreateInsertion(AddConstLoc, " const");
11916 }
11917 }
11918 }
11919
11920 if (Redeclaration) {
11921 // NewFD and OldDecl represent declarations that need to be
11922 // merged.
11923 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
11924 DeclIsDefn)) {
11925 NewFD->setInvalidDecl();
11926 return Redeclaration;
11927 }
11928
11929 Previous.clear();
11930 Previous.addDecl(OldDecl);
11931
11932 if (FunctionTemplateDecl *OldTemplateDecl =
11933 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11934 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11935 FunctionTemplateDecl *NewTemplateDecl
11937 assert(NewTemplateDecl && "Template/non-template mismatch");
11938
11939 // The call to MergeFunctionDecl above may have created some state in
11940 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11941 // can add it as a redeclaration.
11942 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11943
11944 NewFD->setPreviousDeclaration(OldFD);
11945 if (NewFD->isCXXClassMember()) {
11946 NewFD->setAccess(OldTemplateDecl->getAccess());
11947 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11948 }
11949
11950 // If this is an explicit specialization of a member that is a function
11951 // template, mark it as a member specialization.
11952 if (IsMemberSpecialization &&
11953 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11954 NewTemplateDecl->setMemberSpecialization();
11955 assert(OldTemplateDecl->isMemberSpecialization());
11956 // Explicit specializations of a member template do not inherit deleted
11957 // status from the parent member template that they are specializing.
11958 if (OldFD->isDeleted()) {
11959 // FIXME: This assert will not hold in the presence of modules.
11960 assert(OldFD->getCanonicalDecl() == OldFD);
11961 // FIXME: We need an update record for this AST mutation.
11962 OldFD->setDeletedAsWritten(false);
11963 }
11964 }
11965
11966 } else {
11967 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11968 auto *OldFD = cast<FunctionDecl>(OldDecl);
11969 // This needs to happen first so that 'inline' propagates.
11970 NewFD->setPreviousDeclaration(OldFD);
11971 if (NewFD->isCXXClassMember())
11972 NewFD->setAccess(OldFD->getAccess());
11973 }
11974 }
11975 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11976 !NewFD->getAttr<OverloadableAttr>()) {
11977 assert((Previous.empty() ||
11978 llvm::any_of(Previous,
11979 [](const NamedDecl *ND) {
11980 return ND->hasAttr<OverloadableAttr>();
11981 })) &&
11982 "Non-redecls shouldn't happen without overloadable present");
11983
11984 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11985 const auto *FD = dyn_cast<FunctionDecl>(ND);
11986 return FD && !FD->hasAttr<OverloadableAttr>();
11987 });
11988
11989 if (OtherUnmarkedIter != Previous.end()) {
11990 Diag(NewFD->getLocation(),
11991 diag::err_attribute_overloadable_multiple_unmarked_overloads);
11992 Diag((*OtherUnmarkedIter)->getLocation(),
11993 diag::note_attribute_overloadable_prev_overload)
11994 << false;
11995
11996 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11997 }
11998 }
11999
12000 if (LangOpts.OpenMP)
12002
12003 // Semantic checking for this function declaration (in isolation).
12004
12005 if (getLangOpts().CPlusPlus) {
12006 // C++-specific checks.
12007 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12008 CheckConstructor(Constructor);
12009 } else if (CXXDestructorDecl *Destructor =
12010 dyn_cast<CXXDestructorDecl>(NewFD)) {
12011 // We check here for invalid destructor names.
12012 // If we have a friend destructor declaration that is dependent, we can't
12013 // diagnose right away because cases like this are still valid:
12014 // template <class T> struct A { friend T::X::~Y(); };
12015 // struct B { struct Y { ~Y(); }; using X = Y; };
12016 // template struct A<B>;
12018 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12019 CXXRecordDecl *Record = Destructor->getParent();
12021
12023 Context.getCanonicalType(ClassType));
12024 if (NewFD->getDeclName() != Name) {
12025 Diag(NewFD->getLocation(), diag::err_destructor_name);
12026 NewFD->setInvalidDecl();
12027 return Redeclaration;
12028 }
12029 }
12030 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12031 if (auto *TD = Guide->getDescribedFunctionTemplate())
12033
12034 // A deduction guide is not on the list of entities that can be
12035 // explicitly specialized.
12036 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12037 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12038 << /*explicit specialization*/ 1;
12039 }
12040
12041 // Find any virtual functions that this function overrides.
12042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12043 if (!Method->isFunctionTemplateSpecialization() &&
12044 !Method->getDescribedFunctionTemplate() &&
12045 Method->isCanonicalDecl()) {
12046 AddOverriddenMethods(Method->getParent(), Method);
12047 }
12048 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12049 // C++2a [class.virtual]p6
12050 // A virtual method shall not have a requires-clause.
12052 diag::err_constrained_virtual_method);
12053
12054 if (Method->isStatic())
12056 }
12057
12058 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12059 ActOnConversionDeclarator(Conversion);
12060
12061 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12062 if (NewFD->isOverloadedOperator() &&
12064 NewFD->setInvalidDecl();
12065 return Redeclaration;
12066 }
12067
12068 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12069 if (NewFD->getLiteralIdentifier() &&
12071 NewFD->setInvalidDecl();
12072 return Redeclaration;
12073 }
12074
12075 // In C++, check default arguments now that we have merged decls. Unless
12076 // the lexical context is the class, because in this case this is done
12077 // during delayed parsing anyway.
12078 if (!CurContext->isRecord())
12080
12081 // If this function is declared as being extern "C", then check to see if
12082 // the function returns a UDT (class, struct, or union type) that is not C
12083 // compatible, and if it does, warn the user.
12084 // But, issue any diagnostic on the first declaration only.
12085 if (Previous.empty() && NewFD->isExternC()) {
12086 QualType R = NewFD->getReturnType();
12087 if (R->isIncompleteType() && !R->isVoidType())
12088 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12089 << NewFD << R;
12090 else if (!R.isPODType(Context) && !R->isVoidType() &&
12092 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12093 }
12094
12095 // C++1z [dcl.fct]p6:
12096 // [...] whether the function has a non-throwing exception-specification
12097 // [is] part of the function type
12098 //
12099 // This results in an ABI break between C++14 and C++17 for functions whose
12100 // declared type includes an exception-specification in a parameter or
12101 // return type. (Exception specifications on the function itself are OK in
12102 // most cases, and exception specifications are not permitted in most other
12103 // contexts where they could make it into a mangling.)
12104 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12105 auto HasNoexcept = [&](QualType T) -> bool {
12106 // Strip off declarator chunks that could be between us and a function
12107 // type. We don't need to look far, exception specifications are very
12108 // restricted prior to C++17.
12109 if (auto *RT = T->getAs<ReferenceType>())
12110 T = RT->getPointeeType();
12111 else if (T->isAnyPointerType())
12112 T = T->getPointeeType();
12113 else if (auto *MPT = T->getAs<MemberPointerType>())
12114 T = MPT->getPointeeType();
12115 if (auto *FPT = T->getAs<FunctionProtoType>())
12116 if (FPT->isNothrow())
12117 return true;
12118 return false;
12119 };
12120
12121 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12122 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12123 for (QualType T : FPT->param_types())
12124 AnyNoexcept |= HasNoexcept(T);
12125 if (AnyNoexcept)
12126 Diag(NewFD->getLocation(),
12127 diag::warn_cxx17_compat_exception_spec_in_signature)
12128 << NewFD;
12129 }
12130
12131 if (!Redeclaration && LangOpts.CUDA)
12133 }
12134
12135 // Check if the function definition uses any AArch64 SME features without
12136 // having the '+sme' feature enabled and warn user if sme locally streaming
12137 // function returns or uses arguments with VL-based types.
12138 if (DeclIsDefn) {
12139 const auto *Attr = NewFD->getAttr<ArmNewAttr>();
12140 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>();
12141 bool UsesZA = Attr && Attr->isNewZA();
12142 bool UsesZT0 = Attr && Attr->isNewZT0();
12143
12144 if (NewFD->hasAttr<ArmLocallyStreamingAttr>()) {
12145 if (NewFD->getReturnType()->isSizelessVectorType())
12146 Diag(NewFD->getLocation(),
12147 diag::warn_sme_locally_streaming_has_vl_args_returns)
12148 << /*IsArg=*/false;
12149 if (llvm::any_of(NewFD->parameters(), [](ParmVarDecl *P) {
12150 return P->getOriginalType()->isSizelessVectorType();
12151 }))
12152 Diag(NewFD->getLocation(),
12153 diag::warn_sme_locally_streaming_has_vl_args_returns)
12154 << /*IsArg=*/true;
12155 }
12156 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) {
12157 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12158 UsesSM |=
12164 }
12165
12166 if (UsesSM || UsesZA) {
12167 llvm::StringMap<bool> FeatureMap;
12168 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12169 if (!FeatureMap.contains("sme")) {
12170 if (UsesSM)
12171 Diag(NewFD->getLocation(),
12172 diag::err_sme_definition_using_sm_in_non_sme_target);
12173 else
12174 Diag(NewFD->getLocation(),
12175 diag::err_sme_definition_using_za_in_non_sme_target);
12176 }
12177 }
12178 if (UsesZT0) {
12179 llvm::StringMap<bool> FeatureMap;
12180 Context.getFunctionFeatureMap(FeatureMap, NewFD);
12181 if (!FeatureMap.contains("sme2")) {
12182 Diag(NewFD->getLocation(),
12183 diag::err_sme_definition_using_zt0_in_non_sme2_target);
12184 }
12185 }
12186 }
12187
12188 return Redeclaration;
12189}
12190
12192 // C++11 [basic.start.main]p3:
12193 // A program that [...] declares main to be inline, static or
12194 // constexpr is ill-formed.
12195 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12196 // appear in a declaration of main.
12197 // static main is not an error under C99, but we should warn about it.
12198 // We accept _Noreturn main as an extension.
12199 if (FD->getStorageClass() == SC_Static)
12201 ? diag::err_static_main : diag::warn_static_main)
12203 if (FD->isInlineSpecified())
12204 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12206 if (DS.isNoreturnSpecified()) {
12207 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12208 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12209 Diag(NoreturnLoc, diag::ext_noreturn_main);
12210 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12211 << FixItHint::CreateRemoval(NoreturnRange);
12212 }
12213 if (FD->isConstexpr()) {
12214 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12215 << FD->isConsteval()
12218 }
12219
12220 if (getLangOpts().OpenCL) {
12221 Diag(FD->getLocation(), diag::err_opencl_no_main)
12222 << FD->hasAttr<OpenCLKernelAttr>();
12223 FD->setInvalidDecl();
12224 return;
12225 }
12226
12227 // Functions named main in hlsl are default entries, but don't have specific
12228 // signatures they are required to conform to.
12229 if (getLangOpts().HLSL)
12230 return;
12231
12232 QualType T = FD->getType();
12233 assert(T->isFunctionType() && "function decl is not of function type");
12234 const FunctionType* FT = T->castAs<FunctionType>();
12235
12236 // Set default calling convention for main()
12237 if (FT->getCallConv() != CC_C) {
12239 FD->setType(QualType(FT, 0));
12241 }
12242
12243 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
12244 // In C with GNU extensions we allow main() to have non-integer return
12245 // type, but we should warn about the extension, and we disable the
12246 // implicit-return-zero rule.
12247
12248 // GCC in C mode accepts qualified 'int'.
12250 FD->setHasImplicitReturnZero(true);
12251 else {
12252 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12253 SourceRange RTRange = FD->getReturnTypeSourceRange();
12254 if (RTRange.isValid())
12255 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12256 << FixItHint::CreateReplacement(RTRange, "int");
12257 }
12258 } else {
12259 // In C and C++, main magically returns 0 if you fall off the end;
12260 // set the flag which tells us that.
12261 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12262
12263 // All the standards say that main() should return 'int'.
12265 FD->setHasImplicitReturnZero(true);
12266 else {
12267 // Otherwise, this is just a flat-out error.
12268 SourceRange RTRange = FD->getReturnTypeSourceRange();
12269 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12270 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12271 : FixItHint());
12272 FD->setInvalidDecl(true);
12273 }
12274 }
12275
12276 // Treat protoless main() as nullary.
12277 if (isa<FunctionNoProtoType>(FT)) return;
12278
12279 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
12280 unsigned nparams = FTP->getNumParams();
12281 assert(FD->getNumParams() == nparams);
12282
12283 bool HasExtraParameters = (nparams > 3);
12284
12285 if (FTP->isVariadic()) {
12286 Diag(FD->getLocation(), diag::ext_variadic_main);
12287 // FIXME: if we had information about the location of the ellipsis, we
12288 // could add a FixIt hint to remove it as a parameter.
12289 }
12290
12291 // Darwin passes an undocumented fourth argument of type char**. If
12292 // other platforms start sprouting these, the logic below will start
12293 // getting shifty.
12294 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12295 HasExtraParameters = false;
12296
12297 if (HasExtraParameters) {
12298 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12299 FD->setInvalidDecl(true);
12300 nparams = 3;
12301 }
12302
12303 // FIXME: a lot of the following diagnostics would be improved
12304 // if we had some location information about types.
12305
12306 QualType CharPP =
12308 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12309
12310 for (unsigned i = 0; i < nparams; ++i) {
12311 QualType AT = FTP->getParamType(i);
12312
12313 bool mismatch = true;
12314
12316 mismatch = false;
12317 else if (Expected[i] == CharPP) {
12318 // As an extension, the following forms are okay:
12319 // char const **
12320 // char const * const *
12321 // char * const *
12322
12324 const PointerType* PT;
12325 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12326 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12328 Context.CharTy)) {
12329 qs.removeConst();
12330 mismatch = !qs.empty();
12331 }
12332 }
12333
12334 if (mismatch) {
12335 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12336 // TODO: suggest replacing given type with expected type
12337 FD->setInvalidDecl(true);
12338 }
12339 }
12340
12341 if (nparams == 1 && !FD->isInvalidDecl()) {
12342 Diag(FD->getLocation(), diag::warn_main_one_arg);
12343 }
12344
12345 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12346 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12347 FD->setInvalidDecl();
12348 }
12349}
12350
12351static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12352
12353 // Default calling convention for main and wmain is __cdecl
12354 if (FD->getName() == "main" || FD->getName() == "wmain")
12355 return false;
12356
12357 // Default calling convention for MinGW is __cdecl
12358 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12359 if (T.isWindowsGNUEnvironment())
12360 return false;
12361
12362 // Default calling convention for WinMain, wWinMain and DllMain
12363 // is __stdcall on 32 bit Windows
12364 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12365 return true;
12366
12367 return false;
12368}
12369
12371 QualType T = FD->getType();
12372 assert(T->isFunctionType() && "function decl is not of function type");
12373 const FunctionType *FT = T->castAs<FunctionType>();
12374
12375 // Set an implicit return of 'zero' if the function can return some integral,
12376 // enumeration, pointer or nullptr type.
12380 // DllMain is exempt because a return value of zero means it failed.
12381 if (FD->getName() != "DllMain")
12382 FD->setHasImplicitReturnZero(true);
12383
12384 // Explicitly specified calling conventions are applied to MSVC entry points
12385 if (!hasExplicitCallingConv(T)) {
12386 if (isDefaultStdCall(FD, *this)) {
12387 if (FT->getCallConv() != CC_X86StdCall) {
12390 FD->setType(QualType(FT, 0));
12391 }
12392 } else if (FT->getCallConv() != CC_C) {
12395 FD->setType(QualType(FT, 0));
12396 }
12397 }
12398
12399 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12400 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12401 FD->setInvalidDecl();
12402 }
12403}
12404
12406 // FIXME: Need strict checking. In C89, we need to check for
12407 // any assignment, increment, decrement, function-calls, or
12408 // commas outside of a sizeof. In C99, it's the same list,
12409 // except that the aforementioned are allowed in unevaluated
12410 // expressions. Everything else falls under the
12411 // "may accept other forms of constant expressions" exception.
12412 //
12413 // Regular C++ code will not end up here (exceptions: language extensions,
12414 // OpenCL C++ etc), so the constant expression rules there don't matter.
12415 if (Init->isValueDependent()) {
12416 assert(Init->containsErrors() &&
12417 "Dependent code should only occur in error-recovery path.");
12418 return true;
12419 }
12420 const Expr *Culprit;
12421 if (Init->isConstantInitializer(Context, false, &Culprit))
12422 return false;
12423 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12424 return true;
12425}
12426
12427namespace {
12428 // Visits an initialization expression to see if OrigDecl is evaluated in
12429 // its own initialization and throws a warning if it does.
12430 class SelfReferenceChecker
12431 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12432 Sema &S;
12433 Decl *OrigDecl;
12434 bool isRecordType;
12435 bool isPODType;
12436 bool isReferenceType;
12437
12438 bool isInitList;
12439 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12440
12441 public:
12443
12444 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12445 S(S), OrigDecl(OrigDecl) {
12446 isPODType = false;
12447 isRecordType = false;
12448 isReferenceType = false;
12449 isInitList = false;
12450 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12451 isPODType = VD->getType().isPODType(S.Context);
12452 isRecordType = VD->getType()->isRecordType();
12453 isReferenceType = VD->getType()->isReferenceType();
12454 }
12455 }
12456
12457 // For most expressions, just call the visitor. For initializer lists,
12458 // track the index of the field being initialized since fields are
12459 // initialized in order allowing use of previously initialized fields.
12460 void CheckExpr(Expr *E) {
12461 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12462 if (!InitList) {
12463 Visit(E);
12464 return;
12465 }
12466
12467 // Track and increment the index here.
12468 isInitList = true;
12469 InitFieldIndex.push_back(0);
12470 for (auto *Child : InitList->children()) {
12471 CheckExpr(cast<Expr>(Child));
12472 ++InitFieldIndex.back();
12473 }
12474 InitFieldIndex.pop_back();
12475 }
12476
12477 // Returns true if MemberExpr is checked and no further checking is needed.
12478 // Returns false if additional checking is required.
12479 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12481 Expr *Base = E;
12482 bool ReferenceField = false;
12483
12484 // Get the field members used.
12485 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12486 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12487 if (!FD)
12488 return false;
12489 Fields.push_back(FD);
12490 if (FD->getType()->isReferenceType())
12491 ReferenceField = true;
12492 Base = ME->getBase()->IgnoreParenImpCasts();
12493 }
12494
12495 // Keep checking only if the base Decl is the same.
12496 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12497 if (!DRE || DRE->getDecl() != OrigDecl)
12498 return false;
12499
12500 // A reference field can be bound to an unininitialized field.
12501 if (CheckReference && !ReferenceField)
12502 return true;
12503
12504 // Convert FieldDecls to their index number.
12505 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12506 for (const FieldDecl *I : llvm::reverse(Fields))
12507 UsedFieldIndex.push_back(I->getFieldIndex());
12508
12509 // See if a warning is needed by checking the first difference in index
12510 // numbers. If field being used has index less than the field being
12511 // initialized, then the use is safe.
12512 for (auto UsedIter = UsedFieldIndex.begin(),
12513 UsedEnd = UsedFieldIndex.end(),
12514 OrigIter = InitFieldIndex.begin(),
12515 OrigEnd = InitFieldIndex.end();
12516 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12517 if (*UsedIter < *OrigIter)
12518 return true;
12519 if (*UsedIter > *OrigIter)
12520 break;
12521 }
12522
12523 // TODO: Add a different warning which will print the field names.
12524 HandleDeclRefExpr(DRE);
12525 return true;
12526 }
12527
12528 // For most expressions, the cast is directly above the DeclRefExpr.
12529 // For conditional operators, the cast can be outside the conditional
12530 // operator if both expressions are DeclRefExpr's.
12531 void HandleValue(Expr *E) {
12532 E = E->IgnoreParens();
12533 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12534 HandleDeclRefExpr(DRE);
12535 return;
12536 }
12537
12538 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12539 Visit(CO->getCond());
12540 HandleValue(CO->getTrueExpr());
12541 HandleValue(CO->getFalseExpr());
12542 return;
12543 }
12544
12545 if (BinaryConditionalOperator *BCO =
12546 dyn_cast<BinaryConditionalOperator>(E)) {
12547 Visit(BCO->getCond());
12548 HandleValue(BCO->getFalseExpr());
12549 return;
12550 }
12551
12552 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12553 if (Expr *SE = OVE->getSourceExpr())
12554 HandleValue(SE);
12555 return;
12556 }
12557
12558 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12559 if (BO->getOpcode() == BO_Comma) {
12560 Visit(BO->getLHS());
12561 HandleValue(BO->getRHS());
12562 return;
12563 }
12564 }
12565
12566 if (isa<MemberExpr>(E)) {
12567 if (isInitList) {
12568 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
12569 false /*CheckReference*/))
12570 return;
12571 }
12572
12574 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12575 // Check for static member variables and don't warn on them.
12576 if (!isa<FieldDecl>(ME->getMemberDecl()))
12577 return;
12578 Base = ME->getBase()->IgnoreParenImpCasts();
12579 }
12580 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
12581 HandleDeclRefExpr(DRE);
12582 return;
12583 }
12584
12585 Visit(E);
12586 }
12587
12588 // Reference types not handled in HandleValue are handled here since all
12589 // uses of references are bad, not just r-value uses.
12590 void VisitDeclRefExpr(DeclRefExpr *E) {
12591 if (isReferenceType)
12592 HandleDeclRefExpr(E);
12593 }
12594
12595 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12596 if (E->getCastKind() == CK_LValueToRValue) {
12597 HandleValue(E->getSubExpr());
12598 return;
12599 }
12600
12601 Inherited::VisitImplicitCastExpr(E);
12602 }
12603
12604 void VisitMemberExpr(MemberExpr *E) {
12605 if (isInitList) {
12606 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
12607 return;
12608 }
12609
12610 // Don't warn on arrays since they can be treated as pointers.
12611 if (E->getType()->canDecayToPointerType()) return;
12612
12613 // Warn when a non-static method call is followed by non-static member
12614 // field accesses, which is followed by a DeclRefExpr.
12615 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
12616 bool Warn = (MD && !MD->isStatic());
12617 Expr *Base = E->getBase()->IgnoreParenImpCasts();
12618 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12619 if (!isa<FieldDecl>(ME->getMemberDecl()))
12620 Warn = false;
12621 Base = ME->getBase()->IgnoreParenImpCasts();
12622 }
12623
12624 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
12625 if (Warn)
12626 HandleDeclRefExpr(DRE);
12627 return;
12628 }
12629
12630 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
12631 // Visit that expression.
12632 Visit(Base);
12633 }
12634
12635 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12636 Expr *Callee = E->getCallee();
12637
12638 if (isa<UnresolvedLookupExpr>(Callee))
12639 return Inherited::VisitCXXOperatorCallExpr(E);
12640
12641 Visit(Callee);
12642 for (auto Arg: E->arguments())
12643 HandleValue(Arg->IgnoreParenImpCasts());
12644 }
12645
12646 void VisitUnaryOperator(UnaryOperator *E) {
12647 // For POD record types, addresses of its own members are well-defined.
12648 if (E->getOpcode() == UO_AddrOf && isRecordType &&
12649 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
12650 if (!isPODType)
12651 HandleValue(E->getSubExpr());
12652 return;
12653 }
12654
12655 if (E->isIncrementDecrementOp()) {
12656 HandleValue(E->getSubExpr());
12657 return;
12658 }
12659
12660 Inherited::VisitUnaryOperator(E);
12661 }
12662
12663 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
12664
12665 void VisitCXXConstructExpr(CXXConstructExpr *E) {
12666 if (E->getConstructor()->isCopyConstructor()) {
12667 Expr *ArgExpr = E->getArg(0);
12668 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
12669 if (ILE->getNumInits() == 1)
12670 ArgExpr = ILE->getInit(0);
12671 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
12672 if (ICE->getCastKind() == CK_NoOp)
12673 ArgExpr = ICE->getSubExpr();
12674 HandleValue(ArgExpr);
12675 return;
12676 }
12677 Inherited::VisitCXXConstructExpr(E);
12678 }
12679
12680 void VisitCallExpr(CallExpr *E) {
12681 // Treat std::move as a use.
12682 if (E->isCallToStdMove()) {
12683 HandleValue(E->getArg(0));
12684 return;
12685 }
12686
12687 Inherited::VisitCallExpr(E);
12688 }
12689
12690 void VisitBinaryOperator(BinaryOperator *E) {
12691 if (E->isCompoundAssignmentOp()) {
12692 HandleValue(E->getLHS());
12693 Visit(E->getRHS());
12694 return;
12695 }
12696
12697 Inherited::VisitBinaryOperator(E);
12698 }
12699
12700 // A custom visitor for BinaryConditionalOperator is needed because the
12701 // regular visitor would check the condition and true expression separately
12702 // but both point to the same place giving duplicate diagnostics.
12703 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
12704 Visit(E->getCond());
12705 Visit(E->getFalseExpr());
12706 }
12707
12708 void HandleDeclRefExpr(DeclRefExpr *DRE) {
12709 Decl* ReferenceDecl = DRE->getDecl();
12710 if (OrigDecl != ReferenceDecl) return;
12711 unsigned diag;
12712 if (isReferenceType) {
12713 diag = diag::warn_uninit_self_reference_in_reference_init;
12714 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
12715 diag = diag::warn_static_self_reference_in_init;
12716 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
12717 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
12718 DRE->getDecl()->getType()->isRecordType()) {
12719 diag = diag::warn_uninit_self_reference_in_init;
12720 } else {
12721 // Local variables will be handled by the CFG analysis.
12722 return;
12723 }
12724
12725 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
12726 S.PDiag(diag)
12727 << DRE->getDecl() << OrigDecl->getLocation()
12728 << DRE->getSourceRange());
12729 }
12730 };
12731
12732 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
12733 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
12734 bool DirectInit) {
12735 // Parameters arguments are occassionially constructed with itself,
12736 // for instance, in recursive functions. Skip them.
12737 if (isa<ParmVarDecl>(OrigDecl))
12738 return;
12739
12740 E = E->IgnoreParens();
12741
12742 // Skip checking T a = a where T is not a record or reference type.
12743 // Doing so is a way to silence uninitialized warnings.
12744 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
12745 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
12746 if (ICE->getCastKind() == CK_LValueToRValue)
12747 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
12748 if (DRE->getDecl() == OrigDecl)
12749 return;
12750
12751 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
12752 }
12753} // end anonymous namespace
12754
12755namespace {
12756 // Simple wrapper to add the name of a variable or (if no variable is
12757 // available) a DeclarationName into a diagnostic.
12758 struct VarDeclOrName {
12759 VarDecl *VDecl;
12760 DeclarationName Name;
12761
12762 friend const Sema::SemaDiagnosticBuilder &
12763 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
12764 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
12765 }
12766 };
12767} // end anonymous namespace
12768
12771 TypeSourceInfo *TSI,
12773 Expr *Init) {
12774 bool IsInitCapture = !VDecl;
12775 assert((!VDecl || !VDecl->isInitCapture()) &&
12776 "init captures are expected to be deduced prior to initialization");
12777
12778 VarDeclOrName VN{VDecl, Name};
12779
12781 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
12782
12783 // Diagnose auto array declarations in C23, unless it's a supported extension.
12784 if (getLangOpts().C23 && Type->isArrayType() &&
12785 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
12786 Diag(Range.getBegin(), diag::err_auto_not_allowed)
12787 << (int)Deduced->getContainedAutoType()->getKeyword()
12788 << /*in array decl*/ 23 << Range;
12789 return QualType();
12790 }
12791
12792 // C++11 [dcl.spec.auto]p3
12793 if (!Init) {
12794 assert(VDecl && "no init for init capture deduction?");
12795
12796 // Except for class argument deduction, and then for an initializing
12797 // declaration only, i.e. no static at class scope or extern.
12798 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
12799 VDecl->hasExternalStorage() ||
12800 VDecl->isStaticDataMember()) {
12801 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
12802 << VDecl->getDeclName() << Type;
12803 return QualType();
12804 }
12805 }
12806
12807 ArrayRef<Expr*> DeduceInits;
12808 if (Init)
12809 DeduceInits = Init;
12810
12811 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
12812 if (DirectInit && PL)
12813 DeduceInits = PL->exprs();
12814
12815 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
12816 assert(VDecl && "non-auto type for init capture deduction?");
12819 VDecl->getLocation(), DirectInit, Init);
12820 // FIXME: Initialization should not be taking a mutable list of inits.
12821 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
12822 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
12823 InitsCopy);
12824 }
12825
12826 if (DirectInit) {
12827 if (auto *IL = dyn_cast<InitListExpr>(Init))
12828 DeduceInits = IL->inits();
12829 }
12830
12831 // Deduction only works if we have exactly one source expression.
12832 if (DeduceInits.empty()) {
12833 // It isn't possible to write this directly, but it is possible to
12834 // end up in this situation with "auto x(some_pack...);"
12835 Diag(Init->getBeginLoc(), IsInitCapture
12836 ? diag::err_init_capture_no_expression
12837 : diag::err_auto_var_init_no_expression)
12838 << VN << Type << Range;
12839 return QualType();
12840 }
12841
12842 if (DeduceInits.size() > 1) {
12843 Diag(DeduceInits[1]->getBeginLoc(),
12844 IsInitCapture ? diag::err_init_capture_multiple_expressions
12845 : diag::err_auto_var_init_multiple_expressions)
12846 << VN << Type << Range;
12847 return QualType();
12848 }
12849
12850 Expr *DeduceInit = DeduceInits[0];
12851 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12852 Diag(Init->getBeginLoc(), IsInitCapture
12853 ? diag::err_init_capture_paren_braces
12854 : diag::err_auto_var_init_paren_braces)
12855 << isa<InitListExpr>(Init) << VN << Type << Range;
12856 return QualType();
12857 }
12858
12859 // Expressions default to 'id' when we're in a debugger.
12860 bool DefaultedAnyToId = false;
12861 if (getLangOpts().DebuggerCastResultToId &&
12862 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12864 if (Result.isInvalid()) {
12865 return QualType();
12866 }
12867 Init = Result.get();
12868 DefaultedAnyToId = true;
12869 }
12870
12871 // C++ [dcl.decomp]p1:
12872 // If the assignment-expression [...] has array type A and no ref-qualifier
12873 // is present, e has type cv A
12874 if (VDecl && isa<DecompositionDecl>(VDecl) &&
12876 DeduceInit->getType()->isConstantArrayType())
12877 return Context.getQualifiedType(DeduceInit->getType(),
12878 Type.getQualifiers());
12879
12881 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
12883 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
12886 if (!IsInitCapture)
12887 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12888 else if (isa<InitListExpr>(Init))
12890 diag::err_init_capture_deduction_failure_from_init_list)
12891 << VN
12892 << (DeduceInit->getType().isNull() ? TSI->getType()
12893 : DeduceInit->getType())
12894 << DeduceInit->getSourceRange();
12895 else
12896 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12897 << VN << TSI->getType()
12898 << (DeduceInit->getType().isNull() ? TSI->getType()
12899 : DeduceInit->getType())
12900 << DeduceInit->getSourceRange();
12901 }
12902
12903 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12904 // 'id' instead of a specific object type prevents most of our usual
12905 // checks.
12906 // We only want to warn outside of template instantiations, though:
12907 // inside a template, the 'id' could have come from a parameter.
12908 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12909 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12911 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12912 }
12913
12914 return DeducedType;
12915}
12916
12918 Expr *Init) {
12919 assert(!Init || !Init->containsErrors());
12921 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12922 VDecl->getSourceRange(), DirectInit, Init);
12923 if (DeducedType.isNull()) {
12924 VDecl->setInvalidDecl();
12925 return true;
12926 }
12927
12928 VDecl->setType(DeducedType);
12929 assert(VDecl->isLinkageValid());
12930
12931 // In ARC, infer lifetime.
12932 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
12933 VDecl->setInvalidDecl();
12934
12935 if (getLangOpts().OpenCL)
12937
12938 // If this is a redeclaration, check that the type we just deduced matches
12939 // the previously declared type.
12940 if (VarDecl *Old = VDecl->getPreviousDecl()) {
12941 // We never need to merge the type, because we cannot form an incomplete
12942 // array of auto, nor deduce such a type.
12943 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12944 }
12945
12946 // Check the deduced type is valid for a variable declaration.
12948 return VDecl->isInvalidDecl();
12949}
12950
12953 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12954 Init = EWC->getSubExpr();
12955
12956 if (auto *CE = dyn_cast<ConstantExpr>(Init))
12957 Init = CE->getSubExpr();
12958
12959 QualType InitType = Init->getType();
12962 "shouldn't be called if type doesn't have a non-trivial C struct");
12963 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12964 for (auto *I : ILE->inits()) {
12965 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12966 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12967 continue;
12968 SourceLocation SL = I->getExprLoc();
12970 }
12971 return;
12972 }
12973
12974 if (isa<ImplicitValueInitExpr>(Init)) {
12977 NTCUK_Init);
12978 } else {
12979 // Assume all other explicit initializers involving copying some existing
12980 // object.
12981 // TODO: ignore any explicit initializers where we can guarantee
12982 // copy-elision.
12985 }
12986}
12987
12988namespace {
12989
12990bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12991 // Ignore unavailable fields. A field can be marked as unavailable explicitly
12992 // in the source code or implicitly by the compiler if it is in a union
12993 // defined in a system header and has non-trivial ObjC ownership
12994 // qualifications. We don't want those fields to participate in determining
12995 // whether the containing union is non-trivial.
12996 return FD->hasAttr<UnavailableAttr>();
12997}
12998
12999struct DiagNonTrivalCUnionDefaultInitializeVisitor
13000 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13001 void> {
13002 using Super =
13003 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13004 void>;
13005
13006 DiagNonTrivalCUnionDefaultInitializeVisitor(
13007 QualType OrigTy, SourceLocation OrigLoc,
13008 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13009 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13010
13011 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13012 const FieldDecl *FD, bool InNonTrivialUnion) {
13013 if (const auto *AT = S.Context.getAsArrayType(QT))
13014 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13015 InNonTrivialUnion);
13016 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13017 }
13018
13019 void visitARCStrong(QualType QT, const FieldDecl *FD,
13020 bool InNonTrivialUnion) {
13021 if (InNonTrivialUnion)
13022 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13023 << 1 << 0 << QT << FD->getName();
13024 }
13025
13026 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13027 if (InNonTrivialUnion)
13028 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13029 << 1 << 0 << QT << FD->getName();
13030 }
13031
13032 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13033 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13034 if (RD->isUnion()) {
13035 if (OrigLoc.isValid()) {
13036 bool IsUnion = false;
13037 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13038 IsUnion = OrigRD->isUnion();
13039 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13040 << 0 << OrigTy << IsUnion << UseContext;
13041 // Reset OrigLoc so that this diagnostic is emitted only once.
13042 OrigLoc = SourceLocation();
13043 }
13044 InNonTrivialUnion = true;
13045 }
13046
13047 if (InNonTrivialUnion)
13048 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13049 << 0 << 0 << QT.getUnqualifiedType() << "";
13050
13051 for (const FieldDecl *FD : RD->fields())
13052 if (!shouldIgnoreForRecordTriviality(FD))
13053 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13054 }
13055
13056 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13057
13058 // The non-trivial C union type or the struct/union type that contains a
13059 // non-trivial C union.
13060 QualType OrigTy;
13061 SourceLocation OrigLoc;
13063 Sema &S;
13064};
13065
13066struct DiagNonTrivalCUnionDestructedTypeVisitor
13067 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13068 using Super =
13070
13071 DiagNonTrivalCUnionDestructedTypeVisitor(
13072 QualType OrigTy, SourceLocation OrigLoc,
13073 Sema::NonTrivialCUnionContext UseContext, Sema &S)
13074 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13075
13076 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13077 const FieldDecl *FD, bool InNonTrivialUnion) {
13078 if (const auto *AT = S.Context.getAsArrayType(QT))
13079 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13080 InNonTrivialUnion);
13081 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13082 }
13083
13084 void visitARCStrong(QualType QT, const FieldDecl *FD,
13085 bool InNonTrivialUnion) {
13086 if (InNonTrivialUnion)
13087 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13088 << 1 << 1 << QT << FD->getName();
13089 }
13090
13091 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13092 if (InNonTrivialUnion)
13093 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13094 << 1 << 1 << QT << FD->getName();
13095 }
13096
13097 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13098 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13099 if (RD->isUnion()) {
13100 if (OrigLoc.isValid()) {
13101 bool IsUnion = false;
13102 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13103 IsUnion = OrigRD->isUnion();
13104 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13105 << 1 << OrigTy << IsUnion << UseContext;
13106 // Reset OrigLoc so that this diagnostic is emitted only once.
13107 OrigLoc = SourceLocation();
13108 }
13109 InNonTrivialUnion = true;
13110 }
13111
13112 if (InNonTrivialUnion)
13113 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13114 << 0 << 1 << QT.getUnqualifiedType() << "";
13115
13116 for (const FieldDecl *FD : RD->fields())
13117 if (!shouldIgnoreForRecordTriviality(FD))
13118 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13119 }
13120
13121 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13122 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13123 bool InNonTrivialUnion) {}
13124
13125 // The non-trivial C union type or the struct/union type that contains a
13126 // non-trivial C union.
13127 QualType OrigTy;
13128 SourceLocation OrigLoc;
13130 Sema &S;
13131};
13132
13133struct DiagNonTrivalCUnionCopyVisitor
13134 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13136
13137 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13139 Sema &S)
13140 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13141
13142 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13143 const FieldDecl *FD, bool InNonTrivialUnion) {
13144 if (const auto *AT = S.Context.getAsArrayType(QT))
13145 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13146 InNonTrivialUnion);
13147 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13148 }
13149
13150 void visitARCStrong(QualType QT, const FieldDecl *FD,
13151 bool InNonTrivialUnion) {
13152 if (InNonTrivialUnion)
13153 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13154 << 1 << 2 << QT << FD->getName();
13155 }
13156
13157 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13158 if (InNonTrivialUnion)
13159 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13160 << 1 << 2 << QT << FD->getName();
13161 }
13162
13163 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13164 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
13165 if (RD->isUnion()) {
13166 if (OrigLoc.isValid()) {
13167 bool IsUnion = false;
13168 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13169 IsUnion = OrigRD->isUnion();
13170 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13171 << 2 << OrigTy << IsUnion << UseContext;
13172 // Reset OrigLoc so that this diagnostic is emitted only once.
13173 OrigLoc = SourceLocation();
13174 }
13175 InNonTrivialUnion = true;
13176 }
13177
13178 if (InNonTrivialUnion)
13179 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13180 << 0 << 2 << QT.getUnqualifiedType() << "";
13181
13182 for (const FieldDecl *FD : RD->fields())
13183 if (!shouldIgnoreForRecordTriviality(FD))
13184 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13185 }
13186
13187 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13188 const FieldDecl *FD, bool InNonTrivialUnion) {}
13189 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13190 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13191 bool InNonTrivialUnion) {}
13192
13193 // The non-trivial C union type or the struct/union type that contains a
13194 // non-trivial C union.
13195 QualType OrigTy;
13196 SourceLocation OrigLoc;
13198 Sema &S;
13199};
13200
13201} // namespace
13202
13204 NonTrivialCUnionContext UseContext,
13205 unsigned NonTrivialKind) {
13209 "shouldn't be called if type doesn't have a non-trivial C union");
13210
13211 if ((NonTrivialKind & NTCUK_Init) &&
13213 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13214 .visit(QT, nullptr, false);
13215 if ((NonTrivialKind & NTCUK_Destruct) &&
13217 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13218 .visit(QT, nullptr, false);
13219 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13220 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13221 .visit(QT, nullptr, false);
13222}
13223
13225 // If there is no declaration, there was an error parsing it. Just ignore
13226 // the initializer.
13227 if (!RealDecl) {
13228 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
13229 return;
13230 }
13231
13232 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13233 if (!Method->isInvalidDecl()) {
13234 // Pure-specifiers are handled in ActOnPureSpecifier.
13235 Diag(Method->getLocation(), diag::err_member_function_initialization)
13236 << Method->getDeclName() << Init->getSourceRange();
13237 Method->setInvalidDecl();
13238 }
13239 return;
13240 }
13241
13242 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13243 if (!VDecl) {
13244 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13245 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13246 RealDecl->setInvalidDecl();
13247 return;
13248 }
13249
13250 if (VDecl->isInvalidDecl()) {
13252 SmallVector<Expr *> SubExprs;
13253 if (Res.isUsable())
13254 SubExprs.push_back(Res.get());
13255 ExprResult Recovery =
13256 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), SubExprs);
13257 if (Expr *E = Recovery.get())
13258 VDecl->setInit(E);
13259 return;
13260 }
13261
13262 // WebAssembly tables can't be used to initialise a variable.
13263 if (Init && !Init->getType().isNull() &&
13264 Init->getType()->isWebAssemblyTableType()) {
13265 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13266 VDecl->setInvalidDecl();
13267 return;
13268 }
13269
13270 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13271 if (VDecl->getType()->isUndeducedType()) {
13272 // Attempt typo correction early so that the type of the init expression can
13273 // be deduced based on the chosen correction if the original init contains a
13274 // TypoExpr.
13276 if (!Res.isUsable()) {
13277 // There are unresolved typos in Init, just drop them.
13278 // FIXME: improve the recovery strategy to preserve the Init.
13279 RealDecl->setInvalidDecl();
13280 return;
13281 }
13282 if (Res.get()->containsErrors()) {
13283 // Invalidate the decl as we don't know the type for recovery-expr yet.
13284 RealDecl->setInvalidDecl();
13285 VDecl->setInit(Res.get());
13286 return;
13287 }
13288 Init = Res.get();
13289
13291 return;
13292 }
13293
13294 // dllimport cannot be used on variable definitions.
13295 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13296 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13297 VDecl->setInvalidDecl();
13298 return;
13299 }
13300
13301 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13302 // the identifier has external or internal linkage, the declaration shall
13303 // have no initializer for the identifier.
13304 // C++14 [dcl.init]p5 is the same restriction for C++.
13305 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13306 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13307 VDecl->setInvalidDecl();
13308 return;
13309 }
13310
13311 if (!VDecl->getType()->isDependentType()) {
13312 // A definition must end up with a complete type, which means it must be
13313 // complete with the restriction that an array type might be completed by
13314 // the initializer; note that later code assumes this restriction.
13315 QualType BaseDeclType = VDecl->getType();
13316 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13317 BaseDeclType = Array->getElementType();
13318 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13319 diag::err_typecheck_decl_incomplete_type)) {
13320 RealDecl->setInvalidDecl();
13321 return;
13322 }
13323
13324 // The variable can not have an abstract class type.
13325 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13326 diag::err_abstract_type_in_decl,
13328 VDecl->setInvalidDecl();
13329 }
13330
13331 // C++ [module.import/6] external definitions are not permitted in header
13332 // units.
13333 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13334 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13335 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13336 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13338 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13339 VDecl->setInvalidDecl();
13340 }
13341
13342 // If adding the initializer will turn this declaration into a definition,
13343 // and we already have a definition for this variable, diagnose or otherwise
13344 // handle the situation.
13345 if (VarDecl *Def = VDecl->getDefinition())
13346 if (Def != VDecl &&
13347 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13349 checkVarDeclRedefinition(Def, VDecl))
13350 return;
13351
13352 if (getLangOpts().CPlusPlus) {
13353 // C++ [class.static.data]p4
13354 // If a static data member is of const integral or const
13355 // enumeration type, its declaration in the class definition can
13356 // specify a constant-initializer which shall be an integral
13357 // constant expression (5.19). In that case, the member can appear
13358 // in integral constant expressions. The member shall still be
13359 // defined in a namespace scope if it is used in the program and the
13360 // namespace scope definition shall not contain an initializer.
13361 //
13362 // We already performed a redefinition check above, but for static
13363 // data members we also need to check whether there was an in-class
13364 // declaration with an initializer.
13365 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13366 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13367 << VDecl->getDeclName();
13368 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13369 diag::note_previous_initializer)
13370 << 0;
13371 return;
13372 }
13373
13374 if (VDecl->hasLocalStorage())
13376
13378 VDecl->setInvalidDecl();
13379 return;
13380 }
13381 }
13382
13383 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
13384 // a kernel function cannot be initialized."
13385 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
13386 Diag(VDecl->getLocation(), diag::err_local_cant_init);
13387 VDecl->setInvalidDecl();
13388 return;
13389 }
13390
13391 // The LoaderUninitialized attribute acts as a definition (of undef).
13392 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
13393 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
13394 VDecl->setInvalidDecl();
13395 return;
13396 }
13397
13398 // Get the decls type and save a reference for later, since
13399 // CheckInitializerTypes may change it.
13400 QualType DclT = VDecl->getType(), SavT = DclT;
13401
13402 // Expressions default to 'id' when we're in a debugger
13403 // and we are assigning it to a variable of Objective-C pointer type.
13404 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
13405 Init->getType() == Context.UnknownAnyTy) {
13407 if (Result.isInvalid()) {
13408 VDecl->setInvalidDecl();
13409 return;
13410 }
13411 Init = Result.get();
13412 }
13413
13414 // Perform the initialization.
13415 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
13416 bool IsParenListInit = false;
13417 if (!VDecl->isInvalidDecl()) {
13420 VDecl->getLocation(), DirectInit, Init);
13421
13422 MultiExprArg Args = Init;
13423 if (CXXDirectInit)
13424 Args = MultiExprArg(CXXDirectInit->getExprs(),
13425 CXXDirectInit->getNumExprs());
13426
13427 // Try to correct any TypoExprs in the initialization arguments.
13428 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
13430 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
13431 [this, Entity, Kind](Expr *E) {
13432 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
13433 return Init.Failed() ? ExprError() : E;
13434 });
13435 if (Res.isInvalid()) {
13436 VDecl->setInvalidDecl();
13437 } else if (Res.get() != Args[Idx]) {
13438 Args[Idx] = Res.get();
13439 }
13440 }
13441 if (VDecl->isInvalidDecl())
13442 return;
13443
13444 InitializationSequence InitSeq(*this, Entity, Kind, Args,
13445 /*TopLevelOfInitList=*/false,
13446 /*TreatUnavailableAsInvalid=*/false);
13447 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
13448 if (Result.isInvalid()) {
13449 // If the provided initializer fails to initialize the var decl,
13450 // we attach a recovery expr for better recovery.
13451 auto RecoveryExpr =
13452 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
13453 if (RecoveryExpr.get())
13454 VDecl->setInit(RecoveryExpr.get());
13455 // In general, for error recovery purposes, the initializer doesn't play
13456 // part in the valid bit of the declaration. There are a few exceptions:
13457 // 1) if the var decl has a deduced auto type, and the type cannot be
13458 // deduced by an invalid initializer;
13459 // 2) if the var decl is a decomposition decl with a non-deduced type,
13460 // and the initialization fails (e.g. `int [a] = {1, 2};`);
13461 // Case 1) was already handled elsewhere.
13462 if (isa<DecompositionDecl>(VDecl)) // Case 2)
13463 VDecl->setInvalidDecl();
13464 return;
13465 }
13466
13467 Init = Result.getAs<Expr>();
13468 IsParenListInit = !InitSeq.steps().empty() &&
13469 InitSeq.step_begin()->Kind ==
13471 QualType VDeclType = VDecl->getType();
13472 if (Init && !Init->getType().isNull() &&
13473 !Init->getType()->isDependentType() && !VDeclType->isDependentType() &&
13474 Context.getAsIncompleteArrayType(VDeclType) &&
13476 // Bail out if it is not possible to deduce array size from the
13477 // initializer.
13478 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
13479 << VDeclType;
13480 VDecl->setInvalidDecl();
13481 return;
13482 }
13483 }
13484
13485 // Check for self-references within variable initializers.
13486 // Variables declared within a function/method body (except for references)
13487 // are handled by a dataflow analysis.
13488 // This is undefined behavior in C++, but valid in C.
13489 if (getLangOpts().CPlusPlus)
13490 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
13491 VDecl->getType()->isReferenceType())
13492 CheckSelfReference(*this, RealDecl, Init, DirectInit);
13493
13494 // If the type changed, it means we had an incomplete type that was
13495 // completed by the initializer. For example:
13496 // int ary[] = { 1, 3, 5 };
13497 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
13498 if (!VDecl->isInvalidDecl() && (DclT != SavT))
13499 VDecl->setType(DclT);
13500
13501 if (!VDecl->isInvalidDecl()) {
13502 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
13503
13504 if (VDecl->hasAttr<BlocksAttr>())
13505 ObjC().checkRetainCycles(VDecl, Init);
13506
13507 // It is safe to assign a weak reference into a strong variable.
13508 // Although this code can still have problems:
13509 // id x = self.weakProp;
13510 // id y = self.weakProp;
13511 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13512 // paths through the function. This should be revisited if
13513 // -Wrepeated-use-of-weak is made flow-sensitive.
13514 if (FunctionScopeInfo *FSI = getCurFunction())
13515 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
13517 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13518 Init->getBeginLoc()))
13519 FSI->markSafeWeakUse(Init);
13520 }
13521
13522 // The initialization is usually a full-expression.
13523 //
13524 // FIXME: If this is a braced initialization of an aggregate, it is not
13525 // an expression, and each individual field initializer is a separate
13526 // full-expression. For instance, in:
13527 //
13528 // struct Temp { ~Temp(); };
13529 // struct S { S(Temp); };
13530 // struct T { S a, b; } t = { Temp(), Temp() }
13531 //
13532 // we should destroy the first Temp before constructing the second.
13535 /*DiscardedValue*/ false, VDecl->isConstexpr());
13536 if (Result.isInvalid()) {
13537 VDecl->setInvalidDecl();
13538 return;
13539 }
13540 Init = Result.get();
13541
13542 // Attach the initializer to the decl.
13543 VDecl->setInit(Init);
13544
13545 if (VDecl->isLocalVarDecl()) {
13546 // Don't check the initializer if the declaration is malformed.
13547 if (VDecl->isInvalidDecl()) {
13548 // do nothing
13549
13550 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
13551 // This is true even in C++ for OpenCL.
13552 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
13554
13555 // Otherwise, C++ does not restrict the initializer.
13556 } else if (getLangOpts().CPlusPlus) {
13557 // do nothing
13558
13559 // C99 6.7.8p4: All the expressions in an initializer for an object that has
13560 // static storage duration shall be constant expressions or string literals.
13561 } else if (VDecl->getStorageClass() == SC_Static) {
13563
13564 // C89 is stricter than C99 for aggregate initializers.
13565 // C89 6.5.7p3: All the expressions [...] in an initializer list
13566 // for an object that has aggregate or union type shall be
13567 // constant expressions.
13568 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
13569 isa<InitListExpr>(Init)) {
13570 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
13571 }
13572
13573 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
13574 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
13575 if (VDecl->hasLocalStorage())
13576 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13577 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
13578 VDecl->getLexicalDeclContext()->isRecord()) {
13579 // This is an in-class initialization for a static data member, e.g.,
13580 //
13581 // struct S {
13582 // static const int value = 17;
13583 // };
13584
13585 // C++ [class.mem]p4:
13586 // A member-declarator can contain a constant-initializer only
13587 // if it declares a static member (9.4) of const integral or
13588 // const enumeration type, see 9.4.2.
13589 //
13590 // C++11 [class.static.data]p3:
13591 // If a non-volatile non-inline const static data member is of integral
13592 // or enumeration type, its declaration in the class definition can
13593 // specify a brace-or-equal-initializer in which every initializer-clause
13594 // that is an assignment-expression is a constant expression. A static
13595 // data member of literal type can be declared in the class definition
13596 // with the constexpr specifier; if so, its declaration shall specify a
13597 // brace-or-equal-initializer in which every initializer-clause that is
13598 // an assignment-expression is a constant expression.
13599
13600 // Do nothing on dependent types.
13601 if (DclT->isDependentType()) {
13602
13603 // Allow any 'static constexpr' members, whether or not they are of literal
13604 // type. We separately check that every constexpr variable is of literal
13605 // type.
13606 } else if (VDecl->isConstexpr()) {
13607
13608 // Require constness.
13609 } else if (!DclT.isConstQualified()) {
13610 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
13611 << Init->getSourceRange();
13612 VDecl->setInvalidDecl();
13613
13614 // We allow integer constant expressions in all cases.
13615 } else if (DclT->isIntegralOrEnumerationType()) {
13616 // Check whether the expression is a constant expression.
13619 // In C++11, a non-constexpr const static data member with an
13620 // in-class initializer cannot be volatile.
13621 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
13622 else if (Init->isValueDependent())
13623 ; // Nothing to check.
13624 else if (Init->isIntegerConstantExpr(Context, &Loc))
13625 ; // Ok, it's an ICE!
13626 else if (Init->getType()->isScopedEnumeralType() &&
13627 Init->isCXX11ConstantExpr(Context))
13628 ; // Ok, it is a scoped-enum constant expression.
13629 else if (Init->isEvaluatable(Context)) {
13630 // If we can constant fold the initializer through heroics, accept it,
13631 // but report this as a use of an extension for -pedantic.
13632 Diag(Loc, diag::ext_in_class_initializer_non_constant)
13633 << Init->getSourceRange();
13634 } else {
13635 // Otherwise, this is some crazy unknown case. Report the issue at the
13636 // location provided by the isIntegerConstantExpr failed check.
13637 Diag(Loc, diag::err_in_class_initializer_non_constant)
13638 << Init->getSourceRange();
13639 VDecl->setInvalidDecl();
13640 }
13641
13642 // We allow foldable floating-point constants as an extension.
13643 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
13644 // In C++98, this is a GNU extension. In C++11, it is not, but we support
13645 // it anyway and provide a fixit to add the 'constexpr'.
13646 if (getLangOpts().CPlusPlus11) {
13647 Diag(VDecl->getLocation(),
13648 diag::ext_in_class_initializer_float_type_cxx11)
13649 << DclT << Init->getSourceRange();
13650 Diag(VDecl->getBeginLoc(),
13651 diag::note_in_class_initializer_float_type_cxx11)
13652 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13653 } else {
13654 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
13655 << DclT << Init->getSourceRange();
13656
13657 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
13658 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
13659 << Init->getSourceRange();
13660 VDecl->setInvalidDecl();
13661 }
13662 }
13663
13664 // Suggest adding 'constexpr' in C++11 for literal types.
13665 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
13666 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
13667 << DclT << Init->getSourceRange()
13668 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
13669 VDecl->setConstexpr(true);
13670
13671 } else {
13672 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
13673 << DclT << Init->getSourceRange();
13674 VDecl->setInvalidDecl();
13675 }
13676 } else if (VDecl->isFileVarDecl()) {
13677 // In C, extern is typically used to avoid tentative definitions when
13678 // declaring variables in headers, but adding an initializer makes it a
13679 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
13680 // In C++, extern is often used to give implicitly static const variables
13681 // external linkage, so don't warn in that case. If selectany is present,
13682 // this might be header code intended for C and C++ inclusion, so apply the
13683 // C++ rules.
13684 if (VDecl->getStorageClass() == SC_Extern &&
13685 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
13687 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
13689 Diag(VDecl->getLocation(), diag::warn_extern_init);
13690
13691 // In Microsoft C++ mode, a const variable defined in namespace scope has
13692 // external linkage by default if the variable is declared with
13693 // __declspec(dllexport).
13696 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
13697 VDecl->setStorageClass(SC_Extern);
13698
13699 // C99 6.7.8p4. All file scoped initializers need to be constant.
13700 // Avoid duplicate diagnostics for constexpr variables.
13701 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
13702 !VDecl->isConstexpr())
13704 }
13705
13706 QualType InitType = Init->getType();
13707 if (!InitType.isNull() &&
13711
13712 // We will represent direct-initialization similarly to copy-initialization:
13713 // int x(1); -as-> int x = 1;
13714 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
13715 //
13716 // Clients that want to distinguish between the two forms, can check for
13717 // direct initializer using VarDecl::getInitStyle().
13718 // A major benefit is that clients that don't particularly care about which
13719 // exactly form was it (like the CodeGen) can handle both cases without
13720 // special case code.
13721
13722 // C++ 8.5p11:
13723 // The form of initialization (using parentheses or '=') is generally
13724 // insignificant, but does matter when the entity being initialized has a
13725 // class type.
13726 if (CXXDirectInit) {
13727 assert(DirectInit && "Call-style initializer must be direct init.");
13728 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
13730 } else if (DirectInit) {
13731 // This must be list-initialization. No other way is direct-initialization.
13733 }
13734
13735 if (LangOpts.OpenMP &&
13736 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
13737 VDecl->isFileVarDecl())
13738 DeclsToCheckForDeferredDiags.insert(VDecl);
13740}
13741
13743 // Our main concern here is re-establishing invariants like "a
13744 // variable's type is either dependent or complete".
13745 if (!D || D->isInvalidDecl()) return;
13746
13747 VarDecl *VD = dyn_cast<VarDecl>(D);
13748 if (!VD) return;
13749
13750 // Bindings are not usable if we can't make sense of the initializer.
13751 if (auto *DD = dyn_cast<DecompositionDecl>(D))
13752 for (auto *BD : DD->bindings())
13753 BD->setInvalidDecl();
13754
13755 // Auto types are meaningless if we can't make sense of the initializer.
13756 if (VD->getType()->isUndeducedType()) {
13757 D->setInvalidDecl();
13758 return;
13759 }
13760
13761 QualType Ty = VD->getType();
13762 if (Ty->isDependentType()) return;
13763
13764 // Require a complete type.
13767 diag::err_typecheck_decl_incomplete_type)) {
13768 VD->setInvalidDecl();
13769 return;
13770 }
13771
13772 // Require a non-abstract type.
13773 if (RequireNonAbstractType(VD->getLocation(), Ty,
13774 diag::err_abstract_type_in_decl,
13776 VD->setInvalidDecl();
13777 return;
13778 }
13779
13780 // Don't bother complaining about constructors or destructors,
13781 // though.
13782}
13783
13785 // If there is no declaration, there was an error parsing it. Just ignore it.
13786 if (!RealDecl)
13787 return;
13788
13789 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
13790 QualType Type = Var->getType();
13791
13792 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
13793 if (isa<DecompositionDecl>(RealDecl)) {
13794 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
13795 Var->setInvalidDecl();
13796 return;
13797 }
13798
13799 if (Type->isUndeducedType() &&
13800 DeduceVariableDeclarationType(Var, false, nullptr))
13801 return;
13802
13803 // C++11 [class.static.data]p3: A static data member can be declared with
13804 // the constexpr specifier; if so, its declaration shall specify
13805 // a brace-or-equal-initializer.
13806 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
13807 // the definition of a variable [...] or the declaration of a static data
13808 // member.
13809 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
13810 !Var->isThisDeclarationADemotedDefinition()) {
13811 if (Var->isStaticDataMember()) {
13812 // C++1z removes the relevant rule; the in-class declaration is always
13813 // a definition there.
13814 if (!getLangOpts().CPlusPlus17 &&
13816 Diag(Var->getLocation(),
13817 diag::err_constexpr_static_mem_var_requires_init)
13818 << Var;
13819 Var->setInvalidDecl();
13820 return;
13821 }
13822 } else {
13823 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
13824 Var->setInvalidDecl();
13825 return;
13826 }
13827 }
13828
13829 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
13830 // be initialized.
13831 if (!Var->isInvalidDecl() &&
13832 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
13833 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
13834 bool HasConstExprDefaultConstructor = false;
13835 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13836 for (auto *Ctor : RD->ctors()) {
13837 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
13838 Ctor->getMethodQualifiers().getAddressSpace() ==
13840 HasConstExprDefaultConstructor = true;
13841 }
13842 }
13843 }
13844 if (!HasConstExprDefaultConstructor) {
13845 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
13846 Var->setInvalidDecl();
13847 return;
13848 }
13849 }
13850
13851 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
13852 if (Var->getStorageClass() == SC_Extern) {
13853 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
13854 << Var;
13855 Var->setInvalidDecl();
13856 return;
13857 }
13858 if (RequireCompleteType(Var->getLocation(), Var->getType(),
13859 diag::err_typecheck_decl_incomplete_type)) {
13860 Var->setInvalidDecl();
13861 return;
13862 }
13863 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
13864 if (!RD->hasTrivialDefaultConstructor()) {
13865 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
13866 Var->setInvalidDecl();
13867 return;
13868 }
13869 }
13870 // The declaration is uninitialized, no need for further checks.
13871 return;
13872 }
13873
13874 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
13875 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
13876 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
13877 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
13879
13880
13881 switch (DefKind) {
13883 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
13884 break;
13885
13886 // We have an out-of-line definition of a static data member
13887 // that has an in-class initializer, so we type-check this like
13888 // a declaration.
13889 //
13890 [[fallthrough]];
13891
13893 // It's only a declaration.
13894
13895 // Block scope. C99 6.7p7: If an identifier for an object is
13896 // declared with no linkage (C99 6.2.2p6), the type for the
13897 // object shall be complete.
13898 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
13899 !Var->hasLinkage() && !Var->isInvalidDecl() &&
13900 RequireCompleteType(Var->getLocation(), Type,
13901 diag::err_typecheck_decl_incomplete_type))
13902 Var->setInvalidDecl();
13903
13904 // Make sure that the type is not abstract.
13905 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13906 RequireNonAbstractType(Var->getLocation(), Type,
13907 diag::err_abstract_type_in_decl,
13909 Var->setInvalidDecl();
13910 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13911 Var->getStorageClass() == SC_PrivateExtern) {
13912 Diag(Var->getLocation(), diag::warn_private_extern);
13913 Diag(Var->getLocation(), diag::note_private_extern);
13914 }
13915
13917 !Var->isInvalidDecl())
13918 ExternalDeclarations.push_back(Var);
13919
13920 return;
13921
13923 // File scope. C99 6.9.2p2: A declaration of an identifier for an
13924 // object that has file scope without an initializer, and without a
13925 // storage-class specifier or with the storage-class specifier "static",
13926 // constitutes a tentative definition. Note: A tentative definition with
13927 // external linkage is valid (C99 6.2.2p5).
13928 if (!Var->isInvalidDecl()) {
13929 if (const IncompleteArrayType *ArrayT
13932 Var->getLocation(), ArrayT->getElementType(),
13933 diag::err_array_incomplete_or_sizeless_type))
13934 Var->setInvalidDecl();
13935 } else if (Var->getStorageClass() == SC_Static) {
13936 // C99 6.9.2p3: If the declaration of an identifier for an object is
13937 // a tentative definition and has internal linkage (C99 6.2.2p3), the
13938 // declared type shall not be an incomplete type.
13939 // NOTE: code such as the following
13940 // static struct s;
13941 // struct s { int a; };
13942 // is accepted by gcc. Hence here we issue a warning instead of
13943 // an error and we do not invalidate the static declaration.
13944 // NOTE: to avoid multiple warnings, only check the first declaration.
13945 if (Var->isFirstDecl())
13946 RequireCompleteType(Var->getLocation(), Type,
13947 diag::ext_typecheck_decl_incomplete_type);
13948 }
13949 }
13950
13951 // Record the tentative definition; we're done.
13952 if (!Var->isInvalidDecl())
13954 return;
13955 }
13956
13957 // Provide a specific diagnostic for uninitialized variable
13958 // definitions with incomplete array type.
13959 if (Type->isIncompleteArrayType()) {
13960 if (Var->isConstexpr())
13961 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
13962 << Var;
13963 else
13964 Diag(Var->getLocation(),
13965 diag::err_typecheck_incomplete_array_needs_initializer);
13966 Var->setInvalidDecl();
13967 return;
13968 }
13969
13970 // Provide a specific diagnostic for uninitialized variable
13971 // definitions with reference type.
13972 if (Type->isReferenceType()) {
13973 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13974 << Var << SourceRange(Var->getLocation(), Var->getLocation());
13975 return;
13976 }
13977
13978 // Do not attempt to type-check the default initializer for a
13979 // variable with dependent type.
13980 if (Type->isDependentType())
13981 return;
13982
13983 if (Var->isInvalidDecl())
13984 return;
13985
13986 if (!Var->hasAttr<AliasAttr>()) {
13987 if (RequireCompleteType(Var->getLocation(),
13989 diag::err_typecheck_decl_incomplete_type)) {
13990 Var->setInvalidDecl();
13991 return;
13992 }
13993 } else {
13994 return;
13995 }
13996
13997 // The variable can not have an abstract class type.
13998 if (RequireNonAbstractType(Var->getLocation(), Type,
13999 diag::err_abstract_type_in_decl,
14001 Var->setInvalidDecl();
14002 return;
14003 }
14004
14005 // Check for jumps past the implicit initializer. C++0x
14006 // clarifies that this applies to a "variable with automatic
14007 // storage duration", not a "local variable".
14008 // C++11 [stmt.dcl]p3
14009 // A program that jumps from a point where a variable with automatic
14010 // storage duration is not in scope to a point where it is in scope is
14011 // ill-formed unless the variable has scalar type, class type with a
14012 // trivial default constructor and a trivial destructor, a cv-qualified
14013 // version of one of these types, or an array of one of the preceding
14014 // types and is declared without an initializer.
14015 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14016 if (const RecordType *Record
14018 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
14019 // Mark the function (if we're in one) for further checking even if the
14020 // looser rules of C++11 do not require such checks, so that we can
14021 // diagnose incompatibilities with C++98.
14022 if (!CXXRecord->isPOD())
14024 }
14025 }
14026 // In OpenCL, we can't initialize objects in the __local address space,
14027 // even implicitly, so don't synthesize an implicit initializer.
14028 if (getLangOpts().OpenCL &&
14029 Var->getType().getAddressSpace() == LangAS::opencl_local)
14030 return;
14031 // C++03 [dcl.init]p9:
14032 // If no initializer is specified for an object, and the
14033 // object is of (possibly cv-qualified) non-POD class type (or
14034 // array thereof), the object shall be default-initialized; if
14035 // the object is of const-qualified type, the underlying class
14036 // type shall have a user-declared default
14037 // constructor. Otherwise, if no initializer is specified for
14038 // a non- static object, the object and its subobjects, if
14039 // any, have an indeterminate initial value); if the object
14040 // or any of its subobjects are of const-qualified type, the
14041 // program is ill-formed.
14042 // C++0x [dcl.init]p11:
14043 // If no initializer is specified for an object, the object is
14044 // default-initialized; [...].
14047 = InitializationKind::CreateDefault(Var->getLocation());
14048
14049 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
14050 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
14051
14052 if (Init.get()) {
14053 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14054 // This is important for template substitution.
14055 Var->setInitStyle(VarDecl::CallInit);
14056 } else if (Init.isInvalid()) {
14057 // If default-init fails, attach a recovery-expr initializer to track
14058 // that initialization was attempted and failed.
14059 auto RecoveryExpr =
14060 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14061 if (RecoveryExpr.get())
14062 Var->setInit(RecoveryExpr.get());
14063 }
14064
14066 }
14067}
14068
14070 // If there is no declaration, there was an error parsing it. Ignore it.
14071 if (!D)
14072 return;
14073
14074 VarDecl *VD = dyn_cast<VarDecl>(D);
14075 if (!VD) {
14076 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14077 D->setInvalidDecl();
14078 return;
14079 }
14080
14081 VD->setCXXForRangeDecl(true);
14082
14083 // for-range-declaration cannot be given a storage class specifier.
14084 int Error = -1;
14085 switch (VD->getStorageClass()) {
14086 case SC_None:
14087 break;
14088 case SC_Extern:
14089 Error = 0;
14090 break;
14091 case SC_Static:
14092 Error = 1;
14093 break;
14094 case SC_PrivateExtern:
14095 Error = 2;
14096 break;
14097 case SC_Auto:
14098 Error = 3;
14099 break;
14100 case SC_Register:
14101 Error = 4;
14102 break;
14103 }
14104
14105 // for-range-declaration cannot be given a storage class specifier con't.
14106 switch (VD->getTSCSpec()) {
14107 case TSCS_thread_local:
14108 Error = 6;
14109 break;
14110 case TSCS___thread:
14111 case TSCS__Thread_local:
14112 case TSCS_unspecified:
14113 break;
14114 }
14115
14116 if (Error != -1) {
14117 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14118 << VD << Error;
14119 D->setInvalidDecl();
14120 }
14121}
14122
14124 IdentifierInfo *Ident,
14125 ParsedAttributes &Attrs) {
14126 // C++1y [stmt.iter]p1:
14127 // A range-based for statement of the form
14128 // for ( for-range-identifier : for-range-initializer ) statement
14129 // is equivalent to
14130 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14131 DeclSpec DS(Attrs.getPool().getFactory());
14132
14133 const char *PrevSpec;
14134 unsigned DiagID;
14135 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14137
14139 D.SetIdentifier(Ident, IdentLoc);
14140 D.takeAttributes(Attrs);
14141
14142 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14143 IdentLoc);
14144 Decl *Var = ActOnDeclarator(S, D);
14145 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14147 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14148 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14149 : IdentLoc);
14150}
14151
14153 if (var->isInvalidDecl()) return;
14154
14156
14157 if (getLangOpts().OpenCL) {
14158 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14159 // initialiser
14160 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14161 !var->hasInit()) {
14162 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14163 << 1 /*Init*/;
14164 var->setInvalidDecl();
14165 return;
14166 }
14167 }
14168
14169 // In Objective-C, don't allow jumps past the implicit initialization of a
14170 // local retaining variable.
14171 if (getLangOpts().ObjC &&
14172 var->hasLocalStorage()) {
14173 switch (var->getType().getObjCLifetime()) {
14177 break;
14178
14182 break;
14183 }
14184 }
14185
14186 if (var->hasLocalStorage() &&
14187 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14189
14190 // Warn about externally-visible variables being defined without a
14191 // prior declaration. We only want to do this for global
14192 // declarations, but we also specifically need to avoid doing it for
14193 // class members because the linkage of an anonymous class can
14194 // change if it's later given a typedef name.
14195 if (var->isThisDeclarationADefinition() &&
14196 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14197 var->isExternallyVisible() && var->hasLinkage() &&
14198 !var->isInline() && !var->getDescribedVarTemplate() &&
14199 var->getStorageClass() != SC_Register &&
14200 !isa<VarTemplatePartialSpecializationDecl>(var) &&
14201 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14202 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14203 var->getLocation())) {
14204 // Find a previous declaration that's not a definition.
14205 VarDecl *prev = var->getPreviousDecl();
14206 while (prev && prev->isThisDeclarationADefinition())
14207 prev = prev->getPreviousDecl();
14208
14209 if (!prev) {
14210 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14211 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14212 << /* variable */ 0;
14213 }
14214 }
14215
14216 // Cache the result of checking for constant initialization.
14217 std::optional<bool> CacheHasConstInit;
14218 const Expr *CacheCulprit = nullptr;
14219 auto checkConstInit = [&]() mutable {
14220 if (!CacheHasConstInit)
14221 CacheHasConstInit = var->getInit()->isConstantInitializer(
14222 Context, var->getType()->isReferenceType(), &CacheCulprit);
14223 return *CacheHasConstInit;
14224 };
14225
14226 if (var->getTLSKind() == VarDecl::TLS_Static) {
14227 if (var->getType().isDestructedType()) {
14228 // GNU C++98 edits for __thread, [basic.start.term]p3:
14229 // The type of an object with thread storage duration shall not
14230 // have a non-trivial destructor.
14231 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14233 Diag(var->getLocation(), diag::note_use_thread_local);
14234 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14235 if (!checkConstInit()) {
14236 // GNU C++98 edits for __thread, [basic.start.init]p4:
14237 // An object of thread storage duration shall not require dynamic
14238 // initialization.
14239 // FIXME: Need strict checking here.
14240 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14241 << CacheCulprit->getSourceRange();
14243 Diag(var->getLocation(), diag::note_use_thread_local);
14244 }
14245 }
14246 }
14247
14248
14249 if (!var->getType()->isStructureType() && var->hasInit() &&
14250 isa<InitListExpr>(var->getInit())) {
14251 const auto *ILE = cast<InitListExpr>(var->getInit());
14252 unsigned NumInits = ILE->getNumInits();
14253 if (NumInits > 2)
14254 for (unsigned I = 0; I < NumInits; ++I) {
14255 const auto *Init = ILE->getInit(I);
14256 if (!Init)
14257 break;
14258 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14259 if (!SL)
14260 break;
14261
14262 unsigned NumConcat = SL->getNumConcatenated();
14263 // Diagnose missing comma in string array initialization.
14264 // Do not warn when all the elements in the initializer are concatenated
14265 // together. Do not warn for macros too.
14266 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14267 bool OnlyOneMissingComma = true;
14268 for (unsigned J = I + 1; J < NumInits; ++J) {
14269 const auto *Init = ILE->getInit(J);
14270 if (!Init)
14271 break;
14272 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14273 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14274 OnlyOneMissingComma = false;
14275 break;
14276 }
14277 }
14278
14279 if (OnlyOneMissingComma) {
14281 for (unsigned i = 0; i < NumConcat - 1; ++i)
14282 Hints.push_back(FixItHint::CreateInsertion(
14283 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14284
14285 Diag(SL->getStrTokenLoc(1),
14286 diag::warn_concatenated_literal_array_init)
14287 << Hints;
14288 Diag(SL->getBeginLoc(),
14289 diag::note_concatenated_string_literal_silence);
14290 }
14291 // In any case, stop now.
14292 break;
14293 }
14294 }
14295 }
14296
14297
14298 QualType type = var->getType();
14299
14300 if (var->hasAttr<BlocksAttr>())
14302
14303 Expr *Init = var->getInit();
14304 bool GlobalStorage = var->hasGlobalStorage();
14305 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14307 bool HasConstInit = true;
14308
14309 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14310 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14311 << var;
14312
14313 // Check whether the initializer is sufficiently constant.
14314 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14315 !type->isDependentType() && Init && !Init->isValueDependent() &&
14316 (GlobalStorage || var->isConstexpr() ||
14317 var->mightBeUsableInConstantExpressions(Context))) {
14318 // If this variable might have a constant initializer or might be usable in
14319 // constant expressions, check whether or not it actually is now. We can't
14320 // do this lazily, because the result might depend on things that change
14321 // later, such as which constexpr functions happen to be defined.
14323 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14324 // Prior to C++11, in contexts where a constant initializer is required,
14325 // the set of valid constant initializers is described by syntactic rules
14326 // in [expr.const]p2-6.
14327 // FIXME: Stricter checking for these rules would be useful for constinit /
14328 // -Wglobal-constructors.
14329 HasConstInit = checkConstInit();
14330
14331 // Compute and cache the constant value, and remember that we have a
14332 // constant initializer.
14333 if (HasConstInit) {
14334 (void)var->checkForConstantInitialization(Notes);
14335 Notes.clear();
14336 } else if (CacheCulprit) {
14337 Notes.emplace_back(CacheCulprit->getExprLoc(),
14338 PDiag(diag::note_invalid_subexpr_in_const_expr));
14339 Notes.back().second << CacheCulprit->getSourceRange();
14340 }
14341 } else {
14342 // Evaluate the initializer to see if it's a constant initializer.
14343 HasConstInit = var->checkForConstantInitialization(Notes);
14344 }
14345
14346 if (HasConstInit) {
14347 // FIXME: Consider replacing the initializer with a ConstantExpr.
14348 } else if (var->isConstexpr()) {
14349 SourceLocation DiagLoc = var->getLocation();
14350 // If the note doesn't add any useful information other than a source
14351 // location, fold it into the primary diagnostic.
14352 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14353 diag::note_invalid_subexpr_in_const_expr) {
14354 DiagLoc = Notes[0].first;
14355 Notes.clear();
14356 }
14357 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
14358 << var << Init->getSourceRange();
14359 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
14360 Diag(Notes[I].first, Notes[I].second);
14361 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
14362 auto *Attr = var->getAttr<ConstInitAttr>();
14363 Diag(var->getLocation(), diag::err_require_constant_init_failed)
14364 << Init->getSourceRange();
14365 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
14366 << Attr->getRange() << Attr->isConstinit();
14367 for (auto &it : Notes)
14368 Diag(it.first, it.second);
14369 } else if (IsGlobal &&
14370 !getDiagnostics().isIgnored(diag::warn_global_constructor,
14371 var->getLocation())) {
14372 // Warn about globals which don't have a constant initializer. Don't
14373 // warn about globals with a non-trivial destructor because we already
14374 // warned about them.
14375 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
14376 if (!(RD && !RD->hasTrivialDestructor())) {
14377 // checkConstInit() here permits trivial default initialization even in
14378 // C++11 onwards, where such an initializer is not a constant initializer
14379 // but nonetheless doesn't require a global constructor.
14380 if (!checkConstInit())
14381 Diag(var->getLocation(), diag::warn_global_constructor)
14382 << Init->getSourceRange();
14383 }
14384 }
14385 }
14386
14387 // Apply section attributes and pragmas to global variables.
14388 if (GlobalStorage && var->isThisDeclarationADefinition() &&
14390 PragmaStack<StringLiteral *> *Stack = nullptr;
14391 int SectionFlags = ASTContext::PSF_Read;
14392 bool MSVCEnv =
14393 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
14394 std::optional<QualType::NonConstantStorageReason> Reason;
14395 if (HasConstInit &&
14396 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
14397 Stack = &ConstSegStack;
14398 } else {
14399 SectionFlags |= ASTContext::PSF_Write;
14400 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
14401 }
14402 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
14403 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
14404 SectionFlags |= ASTContext::PSF_Implicit;
14405 UnifySection(SA->getName(), SectionFlags, var);
14406 } else if (Stack->CurrentValue) {
14407 if (Stack != &ConstSegStack && MSVCEnv &&
14408 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
14409 var->getType().isConstQualified()) {
14410 assert((!Reason || Reason != QualType::NonConstantStorageReason::
14411 NonConstNonReferenceType) &&
14412 "This case should've already been handled elsewhere");
14413 Diag(var->getLocation(), diag::warn_section_msvc_compat)
14414 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
14416 : *Reason);
14417 }
14418 SectionFlags |= ASTContext::PSF_Implicit;
14419 auto SectionName = Stack->CurrentValue->getString();
14420 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
14421 Stack->CurrentPragmaLocation,
14422 SectionAttr::Declspec_allocate));
14423 if (UnifySection(SectionName, SectionFlags, var))
14424 var->dropAttr<SectionAttr>();
14425 }
14426
14427 // Apply the init_seg attribute if this has an initializer. If the
14428 // initializer turns out to not be dynamic, we'll end up ignoring this
14429 // attribute.
14430 if (CurInitSeg && var->getInit())
14431 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
14432 CurInitSegLoc));
14433 }
14434
14435 // All the following checks are C++ only.
14436 if (!getLangOpts().CPlusPlus) {
14437 // If this variable must be emitted, add it as an initializer for the
14438 // current module.
14439 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14440 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14441 return;
14442 }
14443
14444 // Require the destructor.
14445 if (!type->isDependentType())
14446 if (const RecordType *recordType = baseType->getAs<RecordType>())
14448
14449 // If this variable must be emitted, add it as an initializer for the current
14450 // module.
14451 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
14452 Context.addModuleInitializer(ModuleScopes.back().Module, var);
14453
14454 // Build the bindings if this is a structured binding declaration.
14455 if (auto *DD = dyn_cast<DecompositionDecl>(var))
14457}
14458
14460 assert(VD->isStaticLocal());
14461
14462 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14463
14464 // Find outermost function when VD is in lambda function.
14465 while (FD && !getDLLAttr(FD) &&
14466 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
14467 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
14468 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
14469 }
14470
14471 if (!FD)
14472 return;
14473
14474 // Static locals inherit dll attributes from their function.
14475 if (Attr *A = getDLLAttr(FD)) {
14476 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
14477 NewAttr->setInherited(true);
14478 VD->addAttr(NewAttr);
14479 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
14480 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
14481 NewAttr->setInherited(true);
14482 VD->addAttr(NewAttr);
14483
14484 // Export this function to enforce exporting this static variable even
14485 // if it is not used in this compilation unit.
14486 if (!FD->hasAttr<DLLExportAttr>())
14487 FD->addAttr(NewAttr);
14488
14489 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
14490 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
14491 NewAttr->setInherited(true);
14492 VD->addAttr(NewAttr);
14493 }
14494}
14495
14497 assert(VD->getTLSKind());
14498
14499 // Perform TLS alignment check here after attributes attached to the variable
14500 // which may affect the alignment have been processed. Only perform the check
14501 // if the target has a maximum TLS alignment (zero means no constraints).
14502 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
14503 // Protect the check so that it's not performed on dependent types and
14504 // dependent alignments (we can't determine the alignment in that case).
14505 if (!VD->hasDependentAlignment()) {
14506 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
14507 if (Context.getDeclAlign(VD) > MaxAlignChars) {
14508 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
14510 << (unsigned)MaxAlignChars.getQuantity();
14511 }
14512 }
14513 }
14514}
14515
14517 // Note that we are no longer parsing the initializer for this declaration.
14518 ParsingInitForAutoVars.erase(ThisDecl);
14519
14520 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
14521 if (!VD)
14522 return;
14523
14524 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
14526 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
14528 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
14532 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
14536 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
14540 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
14543 }
14544
14545 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
14546 for (auto *BD : DD->bindings()) {
14548 }
14549 }
14550
14551 checkAttributesAfterMerging(*this, *VD);
14552
14553 if (VD->isStaticLocal())
14555
14556 if (VD->getTLSKind())
14558
14559 // Perform check for initializers of device-side global variables.
14560 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
14561 // 7.5). We must also apply the same checks to all __shared__
14562 // variables whether they are local or not. CUDA also allows
14563 // constant initializers for __constant__ and __device__ variables.
14564 if (getLangOpts().CUDA)
14566
14567 // Grab the dllimport or dllexport attribute off of the VarDecl.
14568 const InheritableAttr *DLLAttr = getDLLAttr(VD);
14569
14570 // Imported static data members cannot be defined out-of-line.
14571 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
14572 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
14574 // We allow definitions of dllimport class template static data members
14575 // with a warning.
14577 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
14578 bool IsClassTemplateMember =
14579 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
14580 Context->getDescribedClassTemplate();
14581
14582 Diag(VD->getLocation(),
14583 IsClassTemplateMember
14584 ? diag::warn_attribute_dllimport_static_field_definition
14585 : diag::err_attribute_dllimport_static_field_definition);
14586 Diag(IA->getLocation(), diag::note_attribute);
14587 if (!IsClassTemplateMember)
14588 VD->setInvalidDecl();
14589 }
14590 }
14591
14592 // dllimport/dllexport variables cannot be thread local, their TLS index
14593 // isn't exported with the variable.
14594 if (DLLAttr && VD->getTLSKind()) {
14595 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
14596 if (F && getDLLAttr(F)) {
14597 assert(VD->isStaticLocal());
14598 // But if this is a static local in a dlimport/dllexport function, the
14599 // function will never be inlined, which means the var would never be
14600 // imported, so having it marked import/export is safe.
14601 } else {
14602 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
14603 << DLLAttr;
14604 VD->setInvalidDecl();
14605 }
14606 }
14607
14608 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
14609 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14610 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14611 << Attr;
14612 VD->dropAttr<UsedAttr>();
14613 }
14614 }
14615 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
14616 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
14617 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
14618 << Attr;
14619 VD->dropAttr<RetainAttr>();
14620 }
14621 }
14622
14623 const DeclContext *DC = VD->getDeclContext();
14624 // If there's a #pragma GCC visibility in scope, and this isn't a class
14625 // member, set the visibility of this variable.
14628
14629 // FIXME: Warn on unused var template partial specializations.
14630 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
14632
14633 // Now we have parsed the initializer and can update the table of magic
14634 // tag values.
14635 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
14637 return;
14638
14639 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
14640 const Expr *MagicValueExpr = VD->getInit();
14641 if (!MagicValueExpr) {
14642 continue;
14643 }
14644 std::optional<llvm::APSInt> MagicValueInt;
14645 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
14646 Diag(I->getRange().getBegin(),
14647 diag::err_type_tag_for_datatype_not_ice)
14648 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14649 continue;
14650 }
14651 if (MagicValueInt->getActiveBits() > 64) {
14652 Diag(I->getRange().getBegin(),
14653 diag::err_type_tag_for_datatype_too_large)
14654 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
14655 continue;
14656 }
14657 uint64_t MagicValue = MagicValueInt->getZExtValue();
14658 RegisterTypeTagForDatatype(I->getArgumentKind(),
14659 MagicValue,
14660 I->getMatchingCType(),
14661 I->getLayoutCompatible(),
14662 I->getMustBeNull());
14663 }
14664}
14665
14667 auto *VD = dyn_cast<VarDecl>(DD);
14668 return VD && !VD->getType()->hasAutoForTrailingReturnType();
14669}
14670
14672 ArrayRef<Decl *> Group) {
14674
14675 if (DS.isTypeSpecOwned())
14676 Decls.push_back(DS.getRepAsDecl());
14677
14678 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
14679 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
14680 bool DiagnosedMultipleDecomps = false;
14681 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
14682 bool DiagnosedNonDeducedAuto = false;
14683
14684 for (Decl *D : Group) {
14685 if (!D)
14686 continue;
14687 // Check if the Decl has been declared in '#pragma omp declare target'
14688 // directive and has static storage duration.
14689 if (auto *VD = dyn_cast<VarDecl>(D);
14690 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
14691 VD->hasGlobalStorage())
14693 // For declarators, there are some additional syntactic-ish checks we need
14694 // to perform.
14695 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
14696 if (!FirstDeclaratorInGroup)
14697 FirstDeclaratorInGroup = DD;
14698 if (!FirstDecompDeclaratorInGroup)
14699 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
14700 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
14701 !hasDeducedAuto(DD))
14702 FirstNonDeducedAutoInGroup = DD;
14703
14704 if (FirstDeclaratorInGroup != DD) {
14705 // A decomposition declaration cannot be combined with any other
14706 // declaration in the same group.
14707 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
14708 Diag(FirstDecompDeclaratorInGroup->getLocation(),
14709 diag::err_decomp_decl_not_alone)
14710 << FirstDeclaratorInGroup->getSourceRange()
14711 << DD->getSourceRange();
14712 DiagnosedMultipleDecomps = true;
14713 }
14714
14715 // A declarator that uses 'auto' in any way other than to declare a
14716 // variable with a deduced type cannot be combined with any other
14717 // declarator in the same group.
14718 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
14719 Diag(FirstNonDeducedAutoInGroup->getLocation(),
14720 diag::err_auto_non_deduced_not_alone)
14721 << FirstNonDeducedAutoInGroup->getType()
14723 << FirstDeclaratorInGroup->getSourceRange()
14724 << DD->getSourceRange();
14725 DiagnosedNonDeducedAuto = true;
14726 }
14727 }
14728 }
14729
14730 Decls.push_back(D);
14731 }
14732
14734 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
14735 handleTagNumbering(Tag, S);
14736 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
14738 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
14739 }
14740 }
14741
14742 return BuildDeclaratorGroup(Decls);
14743}
14744
14747 // C++14 [dcl.spec.auto]p7: (DR1347)
14748 // If the type that replaces the placeholder type is not the same in each
14749 // deduction, the program is ill-formed.
14750 if (Group.size() > 1) {
14751 QualType Deduced;
14752 VarDecl *DeducedDecl = nullptr;
14753 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
14754 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
14755 if (!D || D->isInvalidDecl())
14756 break;
14757 DeducedType *DT = D->getType()->getContainedDeducedType();
14758 if (!DT || DT->getDeducedType().isNull())
14759 continue;
14760 if (Deduced.isNull()) {
14761 Deduced = DT->getDeducedType();
14762 DeducedDecl = D;
14763 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
14764 auto *AT = dyn_cast<AutoType>(DT);
14765 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
14766 diag::err_auto_different_deductions)
14767 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
14768 << DeducedDecl->getDeclName() << DT->getDeducedType()
14769 << D->getDeclName();
14770 if (DeducedDecl->hasInit())
14771 Dia << DeducedDecl->getInit()->getSourceRange();
14772 if (D->getInit())
14773 Dia << D->getInit()->getSourceRange();
14774 D->setInvalidDecl();
14775 break;
14776 }
14777 }
14778 }
14779
14781
14782 return DeclGroupPtrTy::make(
14783 DeclGroupRef::Create(Context, Group.data(), Group.size()));
14784}
14785
14788}
14789
14791 // Don't parse the comment if Doxygen diagnostics are ignored.
14792 if (Group.empty() || !Group[0])
14793 return;
14794
14795 if (Diags.isIgnored(diag::warn_doc_param_not_found,
14796 Group[0]->getLocation()) &&
14797 Diags.isIgnored(diag::warn_unknown_comment_command_name,
14798 Group[0]->getLocation()))
14799 return;
14800
14801 if (Group.size() >= 2) {
14802 // This is a decl group. Normally it will contain only declarations
14803 // produced from declarator list. But in case we have any definitions or
14804 // additional declaration references:
14805 // 'typedef struct S {} S;'
14806 // 'typedef struct S *S;'
14807 // 'struct S *pS;'
14808 // FinalizeDeclaratorGroup adds these as separate declarations.
14809 Decl *MaybeTagDecl = Group[0];
14810 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
14811 Group = Group.slice(1);
14812 }
14813 }
14814
14815 // FIMXE: We assume every Decl in the group is in the same file.
14816 // This is false when preprocessor constructs the group from decls in
14817 // different files (e. g. macros or #include).
14819}
14820
14822 // Check that there are no default arguments inside the type of this
14823 // parameter.
14824 if (getLangOpts().CPlusPlus)
14826
14827 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
14828 if (D.getCXXScopeSpec().isSet()) {
14829 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
14830 << D.getCXXScopeSpec().getRange();
14831 }
14832
14833 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
14834 // simple identifier except [...irrelevant cases...].
14835 switch (D.getName().getKind()) {
14837 break;
14838
14846 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
14848 break;
14849
14852 // GetNameForDeclarator would not produce a useful name in this case.
14853 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
14854 break;
14855 }
14856}
14857
14859 SourceLocation ExplicitThisLoc) {
14860 if (!ExplicitThisLoc.isValid())
14861 return;
14862 assert(S.getLangOpts().CPlusPlus &&
14863 "explicit parameter in non-cplusplus mode");
14864 if (!S.getLangOpts().CPlusPlus23)
14865 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
14866 << P->getSourceRange();
14867
14868 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
14869 // parameter pack.
14870 if (P->isParameterPack()) {
14871 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
14872 << P->getSourceRange();
14873 return;
14874 }
14875 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
14876 if (LambdaScopeInfo *LSI = S.getCurLambda())
14877 LSI->ExplicitObjectParameter = P;
14878}
14879
14881 SourceLocation ExplicitThisLoc) {
14882 const DeclSpec &DS = D.getDeclSpec();
14883
14884 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
14885
14886 // C++03 [dcl.stc]p2 also permits 'auto'.
14887 StorageClass SC = SC_None;
14889 SC = SC_Register;
14890 // In C++11, the 'register' storage class specifier is deprecated.
14891 // In C++17, it is not allowed, but we tolerate it as an extension.
14892 if (getLangOpts().CPlusPlus11) {
14894 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
14895 : diag::warn_deprecated_register)
14897 }
14898 } else if (getLangOpts().CPlusPlus &&
14900 SC = SC_Auto;
14903 diag::err_invalid_storage_class_in_func_decl);
14904 D.getMutableDeclSpec().ClearStorageClassSpecs();
14905 }
14906
14908 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
14910 if (DS.isInlineSpecified())
14911 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
14912 << getLangOpts().CPlusPlus17;
14913 if (DS.hasConstexprSpecifier())
14914 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
14915 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
14916
14918
14920
14922 QualType parmDeclType = TInfo->getType();
14923
14924 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
14925 const IdentifierInfo *II = D.getIdentifier();
14926 if (II) {
14927 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
14928 RedeclarationKind::ForVisibleRedeclaration);
14929 LookupName(R, S);
14930 if (!R.empty()) {
14931 NamedDecl *PrevDecl = *R.begin();
14932 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
14933 // Maybe we will complain about the shadowed template parameter.
14934 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14935 // Just pretend that we didn't see the previous declaration.
14936 PrevDecl = nullptr;
14937 }
14938 if (PrevDecl && S->isDeclScope(PrevDecl)) {
14939 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14940 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14941 // Recover by removing the name
14942 II = nullptr;
14943 D.SetIdentifier(nullptr, D.getIdentifierLoc());
14944 D.setInvalidType(true);
14945 }
14946 }
14947 }
14948
14949 // Temporarily put parameter variables in the translation unit, not
14950 // the enclosing context. This prevents them from accidentally
14951 // looking like class members in C++.
14952 ParmVarDecl *New =
14954 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14955
14956 if (D.isInvalidType())
14957 New->setInvalidDecl();
14958
14959 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
14960
14961 assert(S->isFunctionPrototypeScope());
14962 assert(S->getFunctionPrototypeDepth() >= 1);
14963 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14964 S->getNextFunctionPrototypeIndex());
14965
14966 // Add the parameter declaration into this scope.
14967 S->AddDecl(New);
14968 if (II)
14969 IdResolver.AddDecl(New);
14970
14971 ProcessDeclAttributes(S, New, D);
14972
14973 if (D.getDeclSpec().isModulePrivateSpecified())
14974 Diag(New->getLocation(), diag::err_module_private_local)
14975 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14976 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
14977
14978 if (New->hasAttr<BlocksAttr>()) {
14979 Diag(New->getLocation(), diag::err_block_on_nonlocal);
14980 }
14981
14982 if (getLangOpts().OpenCL)
14984
14985 return New;
14986}
14987
14990 QualType T) {
14991 /* FIXME: setting StartLoc == Loc.
14992 Would it be worth to modify callers so as to provide proper source
14993 location for the unnamed parameters, embedding the parameter's type? */
14994 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14996 SC_None, nullptr);
14997 Param->setImplicit();
14998 return Param;
14999}
15000
15002 // Don't diagnose unused-parameter errors in template instantiations; we
15003 // will already have done so in the template itself.
15005 return;
15006
15007 for (const ParmVarDecl *Parameter : Parameters) {
15008 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15009 !Parameter->hasAttr<UnusedAttr>() &&
15010 !Parameter->getIdentifier()->isPlaceholder()) {
15011 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15012 << Parameter->getDeclName();
15013 }
15014 }
15015}
15016
15018 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15019 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15020 return;
15021
15022 // Warn if the return value is pass-by-value and larger than the specified
15023 // threshold.
15024 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15025 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15026 if (Size > LangOpts.NumLargeByValueCopy)
15027 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15028 }
15029
15030 // Warn if any parameter is pass-by-value and larger than the specified
15031 // threshold.
15032 for (const ParmVarDecl *Parameter : Parameters) {
15033 QualType T = Parameter->getType();
15034 if (T->isDependentType() || !T.isPODType(Context))
15035 continue;
15036 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15037 if (Size > LangOpts.NumLargeByValueCopy)
15038 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15039 << Parameter << Size;
15040 }
15041}
15042
15044 SourceLocation NameLoc,
15045 const IdentifierInfo *Name, QualType T,
15046 TypeSourceInfo *TSInfo, StorageClass SC) {
15047 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15048 if (getLangOpts().ObjCAutoRefCount &&
15049 T.getObjCLifetime() == Qualifiers::OCL_None &&
15050 T->isObjCLifetimeType()) {
15051
15052 Qualifiers::ObjCLifetime lifetime;
15053
15054 // Special cases for arrays:
15055 // - if it's const, use __unsafe_unretained
15056 // - otherwise, it's an error
15057 if (T->isArrayType()) {
15058 if (!T.isConstQualified()) {
15062 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15063 else
15064 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15065 << TSInfo->getTypeLoc().getSourceRange();
15066 }
15068 } else {
15069 lifetime = T->getObjCARCImplicitLifetime();
15070 }
15071 T = Context.getLifetimeQualifiedType(T, lifetime);
15072 }
15073
15074 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15076 TSInfo, SC, nullptr);
15077
15078 // Make a note if we created a new pack in the scope of a lambda, so that
15079 // we know that references to that pack must also be expanded within the
15080 // lambda scope.
15081 if (New->isParameterPack())
15082 if (auto *LSI = getEnclosingLambda())
15083 LSI->LocalPacks.push_back(New);
15084
15089
15090 // Parameter declarators cannot be interface types. All ObjC objects are
15091 // passed by reference.
15092 if (T->isObjCObjectType()) {
15093 SourceLocation TypeEndLoc =
15095 Diag(NameLoc,
15096 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15097 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15099 New->setType(T);
15100 }
15101
15102 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15103 // duration shall not be qualified by an address-space qualifier."
15104 // Since all parameters have automatic store duration, they can not have
15105 // an address space.
15106 if (T.getAddressSpace() != LangAS::Default &&
15107 // OpenCL allows function arguments declared to be an array of a type
15108 // to be qualified with an address space.
15109 !(getLangOpts().OpenCL &&
15110 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15111 // WebAssembly allows reference types as parameters. Funcref in particular
15112 // lives in a different address space.
15113 !(T->isFunctionPointerType() &&
15114 T.getAddressSpace() == LangAS::wasm_funcref)) {
15115 Diag(NameLoc, diag::err_arg_with_address_space);
15116 New->setInvalidDecl();
15117 }
15118
15119 // PPC MMA non-pointer types are not allowed as function argument types.
15120 if (Context.getTargetInfo().getTriple().isPPC64() &&
15121 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15122 New->setInvalidDecl();
15123 }
15124
15125 return New;
15126}
15127
15129 SourceLocation LocAfterDecls) {
15130 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
15131
15132 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15133 // in the declaration list shall have at least one declarator, those
15134 // declarators shall only declare identifiers from the identifier list, and
15135 // every identifier in the identifier list shall be declared.
15136 //
15137 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15138 // identifiers it names shall be declared in the declaration list."
15139 //
15140 // This is why we only diagnose in C99 and later. Note, the other conditions
15141 // listed are checked elsewhere.
15142 if (!FTI.hasPrototype) {
15143 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15144 --i;
15145 if (FTI.Params[i].Param == nullptr) {
15146 if (getLangOpts().C99) {
15147 SmallString<256> Code;
15148 llvm::raw_svector_ostream(Code)
15149 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15150 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15151 << FTI.Params[i].Ident
15152 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15153 }
15154
15155 // Implicitly declare the argument as type 'int' for lack of a better
15156 // type.
15157 AttributeFactory attrs;
15158 DeclSpec DS(attrs);
15159 const char* PrevSpec; // unused
15160 unsigned DiagID; // unused
15161 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15162 DiagID, Context.getPrintingPolicy());
15163 // Use the identifier location for the type source range.
15164 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15165 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15168 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15169 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15170 }
15171 }
15172 }
15173}
15174
15175Decl *
15177 MultiTemplateParamsArg TemplateParameterLists,
15178 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15179 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15180 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15181 Scope *ParentScope = FnBodyScope->getParent();
15182
15183 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15184 // we define a non-templated function definition, we will create a declaration
15185 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15186 // The base function declaration will have the equivalent of an `omp declare
15187 // variant` annotation which specifies the mangled definition as a
15188 // specialization function under the OpenMP context defined as part of the
15189 // `omp begin declare variant`.
15191 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15193 ParentScope, D, TemplateParameterLists, Bases);
15194
15195 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
15196 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15197 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15198
15199 if (!Bases.empty())
15201 Bases);
15202
15203 return Dcl;
15204}
15205
15208}
15209
15211 const FunctionDecl *&PossiblePrototype) {
15212 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15213 Prev = Prev->getPreviousDecl()) {
15214 // Ignore any declarations that occur in function or method
15215 // scope, because they aren't visible from the header.
15216 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15217 continue;
15218
15219 PossiblePrototype = Prev;
15220 return Prev->getType()->isFunctionProtoType();
15221 }
15222 return false;
15223}
15224
15225static bool
15227 const FunctionDecl *&PossiblePrototype) {
15228 // Don't warn about invalid declarations.
15229 if (FD->isInvalidDecl())
15230 return false;
15231
15232 // Or declarations that aren't global.
15233 if (!FD->isGlobal())
15234 return false;
15235
15236 // Don't warn about C++ member functions.
15237 if (isa<CXXMethodDecl>(FD))
15238 return false;
15239
15240 // Don't warn about 'main'.
15241 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
15242 if (IdentifierInfo *II = FD->getIdentifier())
15243 if (II->isStr("main") || II->isStr("efi_main"))
15244 return false;
15245
15246 if (FD->isMSVCRTEntryPoint())
15247 return false;
15248
15249 // Don't warn about inline functions.
15250 if (FD->isInlined())
15251 return false;
15252
15253 // Don't warn about function templates.
15255 return false;
15256
15257 // Don't warn about function template specializations.
15259 return false;
15260
15261 // Don't warn for OpenCL kernels.
15262 if (FD->hasAttr<OpenCLKernelAttr>())
15263 return false;
15264
15265 // Don't warn on explicitly deleted functions.
15266 if (FD->isDeleted())
15267 return false;
15268
15269 // Don't warn on implicitly local functions (such as having local-typed
15270 // parameters).
15271 if (!FD->isExternallyVisible())
15272 return false;
15273
15274 // If we were able to find a potential prototype, don't warn.
15275 if (FindPossiblePrototype(FD, PossiblePrototype))
15276 return false;
15277
15278 return true;
15279}
15280
15281void
15283 const FunctionDecl *EffectiveDefinition,
15284 SkipBodyInfo *SkipBody) {
15285 const FunctionDecl *Definition = EffectiveDefinition;
15286 if (!Definition &&
15287 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
15288 return;
15289
15290 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
15291 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
15292 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
15293 // A merged copy of the same function, instantiated as a member of
15294 // the same class, is OK.
15295 if (declaresSameEntity(OrigFD, OrigDef) &&
15296 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
15297 cast<Decl>(FD->getLexicalDeclContext())))
15298 return;
15299 }
15300 }
15301 }
15302
15304 return;
15305
15306 // Don't emit an error when this is redefinition of a typo-corrected
15307 // definition.
15309 return;
15310
15311 // If we don't have a visible definition of the function, and it's inline or
15312 // a template, skip the new definition.
15313 if (SkipBody && !hasVisibleDefinition(Definition) &&
15314 (Definition->getFormalLinkage() == Linkage::Internal ||
15315 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
15316 Definition->getNumTemplateParameterLists())) {
15317 SkipBody->ShouldSkip = true;
15318 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
15319 if (auto *TD = Definition->getDescribedFunctionTemplate())
15322 return;
15323 }
15324
15325 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
15326 Definition->getStorageClass() == SC_Extern)
15327 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
15328 << FD << getLangOpts().CPlusPlus;
15329 else
15330 Diag(FD->getLocation(), diag::err_redefinition) << FD;
15331
15332 Diag(Definition->getLocation(), diag::note_previous_definition);
15333 FD->setInvalidDecl();
15334}
15335
15337 CXXRecordDecl *LambdaClass = CallOperator->getParent();
15338
15340 LSI->CallOperator = CallOperator;
15341 LSI->Lambda = LambdaClass;
15342 LSI->ReturnType = CallOperator->getReturnType();
15343 // This function in calls in situation where the context of the call operator
15344 // is not entered, so we set AfterParameterList to false, so that
15345 // `tryCaptureVariable` finds explicit captures in the appropriate context.
15346 LSI->AfterParameterList = false;
15347 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
15348
15349 if (LCD == LCD_None)
15351 else if (LCD == LCD_ByCopy)
15353 else if (LCD == LCD_ByRef)
15355 DeclarationNameInfo DNI = CallOperator->getNameInfo();
15356
15358 LSI->Mutable = !CallOperator->isConst();
15359 if (CallOperator->isExplicitObjectMemberFunction())
15360 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
15361
15362 // Add the captures to the LSI so they can be noted as already
15363 // captured within tryCaptureVar.
15364 auto I = LambdaClass->field_begin();
15365 for (const auto &C : LambdaClass->captures()) {
15366 if (C.capturesVariable()) {
15367 ValueDecl *VD = C.getCapturedVar();
15368 if (VD->isInitCapture())
15370 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
15371 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
15372 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
15373 /*EllipsisLoc*/C.isPackExpansion()
15374 ? C.getEllipsisLoc() : SourceLocation(),
15375 I->getType(), /*Invalid*/false);
15376
15377 } else if (C.capturesThis()) {
15378 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
15379 C.getCaptureKind() == LCK_StarThis);
15380 } else {
15381 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
15382 I->getType());
15383 }
15384 ++I;
15385 }
15386 return LSI;
15387}
15388
15390 SkipBodyInfo *SkipBody,
15391 FnBodyKind BodyKind) {
15392 if (!D) {
15393 // Parsing the function declaration failed in some way. Push on a fake scope
15394 // anyway so we can try to parse the function body.
15397 return D;
15398 }
15399
15400 FunctionDecl *FD = nullptr;
15401
15402 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
15403 FD = FunTmpl->getTemplatedDecl();
15404 else
15405 FD = cast<FunctionDecl>(D);
15406
15407 // Do not push if it is a lambda because one is already pushed when building
15408 // the lambda in ActOnStartOfLambdaDefinition().
15409 if (!isLambdaCallOperator(FD))
15410 // [expr.const]/p14.1
15411 // An expression or conversion is in an immediate function context if it is
15412 // potentially evaluated and either: its innermost enclosing non-block scope
15413 // is a function parameter scope of an immediate function.
15416 : ExprEvalContexts.back().Context);
15417
15418 // Each ExpressionEvaluationContextRecord also keeps track of whether the
15419 // context is nested in an immediate function context, so smaller contexts
15420 // that appear inside immediate functions (like variable initializers) are
15421 // considered to be inside an immediate function context even though by
15422 // themselves they are not immediate function contexts. But when a new
15423 // function is entered, we need to reset this tracking, since the entered
15424 // function might be not an immediate function.
15425 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval();
15426 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
15427 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
15428
15429 // Check for defining attributes before the check for redefinition.
15430 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
15431 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
15432 FD->dropAttr<AliasAttr>();
15433 FD->setInvalidDecl();
15434 }
15435 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
15436 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
15437 FD->dropAttr<IFuncAttr>();
15438 FD->setInvalidDecl();
15439 }
15440 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
15441 if (!Context.getTargetInfo().hasFeature("fmv") &&
15442 !Attr->isDefaultVersion()) {
15443 // If function multi versioning disabled skip parsing function body
15444 // defined with non-default target_version attribute
15445 if (SkipBody)
15446 SkipBody->ShouldSkip = true;
15447 return nullptr;
15448 }
15449 }
15450
15451 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15452 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
15453 Ctor->isDefaultConstructor() &&
15455 // If this is an MS ABI dllexport default constructor, instantiate any
15456 // default arguments.
15458 }
15459 }
15460
15461 // See if this is a redefinition. If 'will have body' (or similar) is already
15462 // set, then these checks were already performed when it was set.
15463 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
15465 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
15466
15467 // If we're skipping the body, we're done. Don't enter the scope.
15468 if (SkipBody && SkipBody->ShouldSkip)
15469 return D;
15470 }
15471
15472 // Mark this function as "will have a body eventually". This lets users to
15473 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
15474 // this function.
15475 FD->setWillHaveBody();
15476
15477 // If we are instantiating a generic lambda call operator, push
15478 // a LambdaScopeInfo onto the function stack. But use the information
15479 // that's already been calculated (ActOnLambdaExpr) to prime the current
15480 // LambdaScopeInfo.
15481 // When the template operator is being specialized, the LambdaScopeInfo,
15482 // has to be properly restored so that tryCaptureVariable doesn't try
15483 // and capture any new variables. In addition when calculating potential
15484 // captures during transformation of nested lambdas, it is necessary to
15485 // have the LSI properly restored.
15487 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
15488 // instantiated, explicitly specialized.
15491 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
15492 FD->setInvalidDecl();
15494 } else {
15495 assert(inTemplateInstantiation() &&
15496 "There should be an active template instantiation on the stack "
15497 "when instantiating a generic lambda!");
15498 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D));
15499 }
15500 } else {
15501 // Enter a new function scope
15503 }
15504
15505 // Builtin functions cannot be defined.
15506 if (unsigned BuiltinID = FD->getBuiltinID()) {
15509 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
15510 FD->setInvalidDecl();
15511 }
15512 }
15513
15514 // The return type of a function definition must be complete (C99 6.9.1p3).
15515 // C++23 [dcl.fct.def.general]/p2
15516 // The type of [...] the return for a function definition
15517 // shall not be a (possibly cv-qualified) class type that is incomplete
15518 // or abstract within the function body unless the function is deleted.
15519 QualType ResultType = FD->getReturnType();
15520 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
15521 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
15522 (RequireCompleteType(FD->getLocation(), ResultType,
15523 diag::err_func_def_incomplete_result) ||
15525 diag::err_abstract_type_in_decl,
15527 FD->setInvalidDecl();
15528
15529 if (FnBodyScope)
15530 PushDeclContext(FnBodyScope, FD);
15531
15532 // Check the validity of our function parameters
15533 if (BodyKind != FnBodyKind::Delete)
15535 /*CheckParameterNames=*/true);
15536
15537 // Add non-parameter declarations already in the function to the current
15538 // scope.
15539 if (FnBodyScope) {
15540 for (Decl *NPD : FD->decls()) {
15541 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
15542 if (!NonParmDecl)
15543 continue;
15544 assert(!isa<ParmVarDecl>(NonParmDecl) &&
15545 "parameters should not be in newly created FD yet");
15546
15547 // If the decl has a name, make it accessible in the current scope.
15548 if (NonParmDecl->getDeclName())
15549 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
15550
15551 // Similarly, dive into enums and fish their constants out, making them
15552 // accessible in this scope.
15553 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
15554 for (auto *EI : ED->enumerators())
15555 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
15556 }
15557 }
15558 }
15559
15560 // Introduce our parameters into the function scope
15561 for (auto *Param : FD->parameters()) {
15562 Param->setOwningFunction(FD);
15563
15564 // If this has an identifier, add it to the scope stack.
15565 if (Param->getIdentifier() && FnBodyScope) {
15566 CheckShadow(FnBodyScope, Param);
15567
15568 PushOnScopeChains(Param, FnBodyScope);
15569 }
15570 }
15571
15572 // C++ [module.import/6] external definitions are not permitted in header
15573 // units. Deleted and Defaulted functions are implicitly inline (but the
15574 // inline state is not set at this point, so check the BodyKind explicitly).
15575 // FIXME: Consider an alternate location for the test where the inlined()
15576 // state is complete.
15577 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
15578 !FD->isInvalidDecl() && !FD->isInlined() &&
15579 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
15580 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
15581 !FD->isTemplateInstantiation()) {
15582 assert(FD->isThisDeclarationADefinition());
15583 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
15584 FD->setInvalidDecl();
15585 }
15586
15587 // Ensure that the function's exception specification is instantiated.
15588 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
15590
15591 // dllimport cannot be applied to non-inline function definitions.
15592 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
15593 !FD->isTemplateInstantiation()) {
15594 assert(!FD->hasAttr<DLLExportAttr>());
15595 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
15596 FD->setInvalidDecl();
15597 return D;
15598 }
15599
15600 // Some function attributes (like OptimizeNoneAttr) need actions before
15601 // parsing body started.
15603
15604 // We want to attach documentation to original Decl (which might be
15605 // a function template).
15607 if (getCurLexicalContext()->isObjCContainer() &&
15608 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
15609 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
15610 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
15611
15612 return D;
15613}
15614
15616 if (!FD || FD->isInvalidDecl())
15617 return;
15618 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
15619 FD = TD->getTemplatedDecl();
15620 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
15624 FpPragmaStack.CurrentValue =
15626 }
15627}
15628
15630 ReturnStmt **Returns = Scope->Returns.data();
15631
15632 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
15633 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
15634 if (!NRVOCandidate->isNRVOVariable())
15635 Returns[I]->setNRVOCandidate(nullptr);
15636 }
15637 }
15638}
15639
15641 // We can't delay parsing the body of a constexpr function template (yet).
15642 if (D.getDeclSpec().hasConstexprSpecifier())
15643 return false;
15644
15645 // We can't delay parsing the body of a function template with a deduced
15646 // return type (yet).
15647 if (D.getDeclSpec().hasAutoTypeSpec()) {
15648 // If the placeholder introduces a non-deduced trailing return type,
15649 // we can still delay parsing it.
15650 if (D.getNumTypeObjects()) {
15651 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
15652 if (Outer.Kind == DeclaratorChunk::Function &&
15653 Outer.Fun.hasTrailingReturnType()) {
15654 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
15655 return Ty.isNull() || !Ty->isUndeducedType();
15656 }
15657 }
15658 return false;
15659 }
15660
15661 return true;
15662}
15663
15665 // We cannot skip the body of a function (or function template) which is
15666 // constexpr, since we may need to evaluate its body in order to parse the
15667 // rest of the file.
15668 // We cannot skip the body of a function with an undeduced return type,
15669 // because any callers of that function need to know the type.
15670 if (const FunctionDecl *FD = D->getAsFunction()) {
15671 if (FD->isConstexpr())
15672 return false;
15673 // We can't simply call Type::isUndeducedType here, because inside template
15674 // auto can be deduced to a dependent type, which is not considered
15675 // "undeduced".
15676 if (FD->getReturnType()->getContainedDeducedType())
15677 return false;
15678 }
15680}
15681
15683 if (!Decl)
15684 return nullptr;
15685 if (FunctionDecl *FD = Decl->getAsFunction())
15686 FD->setHasSkippedBody();
15687 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
15688 MD->setHasSkippedBody();
15689 return Decl;
15690}
15691
15693 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false);
15694}
15695
15696/// RAII object that pops an ExpressionEvaluationContext when exiting a function
15697/// body.
15699public:
15700 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
15702 if (!IsLambda)
15704 }
15705
15706private:
15707 Sema &S;
15708 bool IsLambda = false;
15709};
15710
15712 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
15713
15714 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
15715 if (EscapeInfo.count(BD))
15716 return EscapeInfo[BD];
15717
15718 bool R = false;
15719 const BlockDecl *CurBD = BD;
15720
15721 do {
15722 R = !CurBD->doesNotEscape();
15723 if (R)
15724 break;
15725 CurBD = CurBD->getParent()->getInnermostBlockDecl();
15726 } while (CurBD);
15727
15728 return EscapeInfo[BD] = R;
15729 };
15730
15731 // If the location where 'self' is implicitly retained is inside a escaping
15732 // block, emit a diagnostic.
15733 for (const std::pair<SourceLocation, const BlockDecl *> &P :
15735 if (IsOrNestedInEscapingBlock(P.second))
15736 S.Diag(P.first, diag::warn_implicitly_retains_self)
15737 << FixItHint::CreateInsertion(P.first, "self->");
15738}
15739
15740static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
15741 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
15742 FD->getDeclName().isIdentifier() && FD->getName() == Name;
15743}
15744
15746 return methodHasName(FD, "get_return_object");
15747}
15748
15750 return FD->isStatic() &&
15751 methodHasName(FD, "get_return_object_on_allocation_failure");
15752}
15753
15756 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
15757 return;
15758 // Allow some_promise_type::get_return_object().
15760 return;
15761 if (!FD->hasAttr<CoroWrapperAttr>())
15762 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
15763}
15764
15766 bool IsInstantiation) {
15768 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
15769
15770 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
15771 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
15772
15774 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
15775
15776 // If we skip function body, we can't tell if a function is a coroutine.
15777 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
15778 if (FSI->isCoroutine())
15780 else
15782 }
15783
15784 {
15785 // Do not call PopExpressionEvaluationContext() if it is a lambda because
15786 // one is already popped when finishing the lambda in BuildLambdaExpr().
15787 // This is meant to pop the context added in ActOnStartOfFunctionDef().
15788 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
15789 if (FD) {
15790 // If this is called by Parser::ParseFunctionDefinition() after marking
15791 // the declaration as deleted, and if the deleted-function-body contains
15792 // a message (C++26), then a DefaultedOrDeletedInfo will have already been
15793 // added to store that message; do not overwrite it in that case.
15794 //
15795 // Since this would always set the body to 'nullptr' in that case anyway,
15796 // which is already done when the function decl is initially created,
15797 // always skipping this irrespective of whether there is a delete message
15798 // should not be a problem.
15799 if (!FD->isDeletedAsWritten())
15800 FD->setBody(Body);
15801 FD->setWillHaveBody(false);
15803
15804 if (getLangOpts().CPlusPlus14) {
15805 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
15806 FD->getReturnType()->isUndeducedType()) {
15807 // For a function with a deduced result type to return void,
15808 // the result type as written must be 'auto' or 'decltype(auto)',
15809 // possibly cv-qualified or constrained, but not ref-qualified.
15810 if (!FD->getReturnType()->getAs<AutoType>()) {
15811 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
15812 << FD->getReturnType();
15813 FD->setInvalidDecl();
15814 } else {
15815 // Falling off the end of the function is the same as 'return;'.
15816 Expr *Dummy = nullptr;
15818 FD, dcl->getLocation(), Dummy,
15819 FD->getReturnType()->getAs<AutoType>()))
15820 FD->setInvalidDecl();
15821 }
15822 }
15823 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
15824 // In C++11, we don't use 'auto' deduction rules for lambda call
15825 // operators because we don't support return type deduction.
15826 auto *LSI = getCurLambda();
15827 if (LSI->HasImplicitReturnType) {
15829
15830 // C++11 [expr.prim.lambda]p4:
15831 // [...] if there are no return statements in the compound-statement
15832 // [the deduced type is] the type void
15833 QualType RetType =
15834 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
15835
15836 // Update the return type to the deduced type.
15837 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
15838 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
15839 Proto->getExtProtoInfo()));
15840 }
15841 }
15842
15843 // If the function implicitly returns zero (like 'main') or is naked,
15844 // don't complain about missing return statements.
15845 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
15847
15848 // MSVC permits the use of pure specifier (=0) on function definition,
15849 // defined at class scope, warn about this non-standard construct.
15850 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
15851 !FD->isOutOfLine())
15852 Diag(FD->getLocation(), diag::ext_pure_function_definition);
15853
15854 if (!FD->isInvalidDecl()) {
15855 // Don't diagnose unused parameters of defaulted, deleted or naked
15856 // functions.
15857 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
15858 !FD->hasAttr<NakedAttr>())
15861 FD->getReturnType(), FD);
15862
15863 // If this is a structor, we need a vtable.
15864 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
15865 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
15866 else if (CXXDestructorDecl *Destructor =
15867 dyn_cast<CXXDestructorDecl>(FD))
15868 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
15869
15870 // Try to apply the named return value optimization. We have to check
15871 // if we can do this here because lambdas keep return statements around
15872 // to deduce an implicit return type.
15873 if (FD->getReturnType()->isRecordType() &&
15875 computeNRVO(Body, FSI);
15876 }
15877
15878 // GNU warning -Wmissing-prototypes:
15879 // Warn if a global function is defined without a previous
15880 // prototype declaration. This warning is issued even if the
15881 // definition itself provides a prototype. The aim is to detect
15882 // global functions that fail to be declared in header files.
15883 const FunctionDecl *PossiblePrototype = nullptr;
15884 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
15885 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
15886
15887 if (PossiblePrototype) {
15888 // We found a declaration that is not a prototype,
15889 // but that could be a zero-parameter prototype
15890 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
15891 TypeLoc TL = TI->getTypeLoc();
15893 Diag(PossiblePrototype->getLocation(),
15894 diag::note_declaration_not_a_prototype)
15895 << (FD->getNumParams() != 0)
15897 FTL.getRParenLoc(), "void")
15898 : FixItHint{});
15899 }
15900 } else {
15901 // Returns true if the token beginning at this Loc is `const`.
15902 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
15903 const LangOptions &LangOpts) {
15904 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
15905 if (LocInfo.first.isInvalid())
15906 return false;
15907
15908 bool Invalid = false;
15909 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
15910 if (Invalid)
15911 return false;
15912
15913 if (LocInfo.second > Buffer.size())
15914 return false;
15915
15916 const char *LexStart = Buffer.data() + LocInfo.second;
15917 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
15918
15919 return StartTok.consume_front("const") &&
15920 (StartTok.empty() || isWhitespace(StartTok[0]) ||
15921 StartTok.starts_with("/*") || StartTok.starts_with("//"));
15922 };
15923
15924 auto findBeginLoc = [&]() {
15925 // If the return type has `const` qualifier, we want to insert
15926 // `static` before `const` (and not before the typename).
15927 if ((FD->getReturnType()->isAnyPointerType() &&
15930 // But only do this if we can determine where the `const` is.
15931
15932 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
15933 getLangOpts()))
15934
15935 return FD->getBeginLoc();
15936 }
15937 return FD->getTypeSpecStartLoc();
15938 };
15940 diag::note_static_for_internal_linkage)
15941 << /* function */ 1
15942 << (FD->getStorageClass() == SC_None
15943 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
15944 : FixItHint{});
15945 }
15946 }
15947
15948 // We might not have found a prototype because we didn't wish to warn on
15949 // the lack of a missing prototype. Try again without the checks for
15950 // whether we want to warn on the missing prototype.
15951 if (!PossiblePrototype)
15952 (void)FindPossiblePrototype(FD, PossiblePrototype);
15953
15954 // If the function being defined does not have a prototype, then we may
15955 // need to diagnose it as changing behavior in C23 because we now know
15956 // whether the function accepts arguments or not. This only handles the
15957 // case where the definition has no prototype but does have parameters
15958 // and either there is no previous potential prototype, or the previous
15959 // potential prototype also has no actual prototype. This handles cases
15960 // like:
15961 // void f(); void f(a) int a; {}
15962 // void g(a) int a; {}
15963 // See MergeFunctionDecl() for other cases of the behavior change
15964 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
15965 // type without a prototype.
15966 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
15967 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
15968 !PossiblePrototype->isImplicit()))) {
15969 // The function definition has parameters, so this will change behavior
15970 // in C23. If there is a possible prototype, it comes before the
15971 // function definition.
15972 // FIXME: The declaration may have already been diagnosed as being
15973 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
15974 // there's no way to test for the "changes behavior" condition in
15975 // SemaType.cpp when forming the declaration's function type. So, we do
15976 // this awkward dance instead.
15977 //
15978 // If we have a possible prototype and it declares a function with a
15979 // prototype, we don't want to diagnose it; if we have a possible
15980 // prototype and it has no prototype, it may have already been
15981 // diagnosed in SemaType.cpp as deprecated depending on whether
15982 // -Wstrict-prototypes is enabled. If we already warned about it being
15983 // deprecated, add a note that it also changes behavior. If we didn't
15984 // warn about it being deprecated (because the diagnostic is not
15985 // enabled), warn now that it is deprecated and changes behavior.
15986
15987 // This K&R C function definition definitely changes behavior in C23,
15988 // so diagnose it.
15989 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
15990 << /*definition*/ 1 << /* not supported in C23 */ 0;
15991
15992 // If we have a possible prototype for the function which is a user-
15993 // visible declaration, we already tested that it has no prototype.
15994 // This will change behavior in C23. This gets a warning rather than a
15995 // note because it's the same behavior-changing problem as with the
15996 // definition.
15997 if (PossiblePrototype)
15998 Diag(PossiblePrototype->getLocation(),
15999 diag::warn_non_prototype_changes_behavior)
16000 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16001 << /*definition*/ 1;
16002 }
16003
16004 // Warn on CPUDispatch with an actual body.
16005 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16006 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16007 if (!CmpndBody->body_empty())
16008 Diag(CmpndBody->body_front()->getBeginLoc(),
16009 diag::warn_dispatch_body_ignored);
16010
16011 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16012 const CXXMethodDecl *KeyFunction;
16013 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16014 MD->isVirtual() &&
16015 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16016 MD == KeyFunction->getCanonicalDecl()) {
16017 // Update the key-function state if necessary for this ABI.
16018 if (FD->isInlined() &&
16021
16022 // If the newly-chosen key function is already defined, then we
16023 // need to mark the vtable as used retroactively.
16024 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16025 const FunctionDecl *Definition;
16026 if (KeyFunction && KeyFunction->isDefined(Definition))
16027 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16028 } else {
16029 // We just defined they key function; mark the vtable as used.
16030 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16031 }
16032 }
16033 }
16034
16035 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16036 "Function parsing confused");
16037 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16038 assert(MD == getCurMethodDecl() && "Method parsing confused");
16039 MD->setBody(Body);
16040 if (!MD->isInvalidDecl()) {
16042 MD->getReturnType(), MD);
16043
16044 if (Body)
16045 computeNRVO(Body, FSI);
16046 }
16047 if (FSI->ObjCShouldCallSuper) {
16048 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16049 << MD->getSelector().getAsString();
16050 FSI->ObjCShouldCallSuper = false;
16051 }
16053 const ObjCMethodDecl *InitMethod = nullptr;
16054 bool isDesignated =
16055 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16056 assert(isDesignated && InitMethod);
16057 (void)isDesignated;
16058
16059 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16060 auto IFace = MD->getClassInterface();
16061 if (!IFace)
16062 return false;
16063 auto SuperD = IFace->getSuperClass();
16064 if (!SuperD)
16065 return false;
16066 return SuperD->getIdentifier() ==
16067 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16068 };
16069 // Don't issue this warning for unavailable inits or direct subclasses
16070 // of NSObject.
16071 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16072 Diag(MD->getLocation(),
16073 diag::warn_objc_designated_init_missing_super_call);
16074 Diag(InitMethod->getLocation(),
16075 diag::note_objc_designated_init_marked_here);
16076 }
16078 }
16079 if (FSI->ObjCWarnForNoInitDelegation) {
16080 // Don't issue this warning for unavailable inits.
16081 if (!MD->isUnavailable())
16082 Diag(MD->getLocation(),
16083 diag::warn_objc_secondary_init_missing_init_call);
16084 FSI->ObjCWarnForNoInitDelegation = false;
16085 }
16086
16088 } else {
16089 // Parsing the function declaration failed in some way. Pop the fake scope
16090 // we pushed on.
16091 PopFunctionScopeInfo(ActivePolicy, dcl);
16092 return nullptr;
16093 }
16094
16095 if (Body && FSI->HasPotentialAvailabilityViolations)
16097
16098 assert(!FSI->ObjCShouldCallSuper &&
16099 "This should only be set for ObjC methods, which should have been "
16100 "handled in the block above.");
16101
16102 // Verify and clean out per-function state.
16103 if (Body && (!FD || !FD->isDefaulted())) {
16104 // C++ constructors that have function-try-blocks can't have return
16105 // statements in the handlers of that block. (C++ [except.handle]p14)
16106 // Verify this.
16107 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16108 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
16109
16110 // Verify that gotos and switch cases don't jump into scopes illegally.
16113
16114 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16115 if (!Destructor->getParent()->isDependentType())
16117
16119 Destructor->getParent());
16120 }
16121
16122 // If any errors have occurred, clear out any temporaries that may have
16123 // been leftover. This ensures that these temporaries won't be picked up
16124 // for deletion in some later function.
16127 getDiagnostics().getSuppressAllDiagnostics()) {
16129 }
16130 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
16131 // Since the body is valid, issue any analysis-based warnings that are
16132 // enabled.
16133 ActivePolicy = &WP;
16134 }
16135
16136 if (!IsInstantiation && FD &&
16137 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
16138 !FD->isInvalidDecl() &&
16140 FD->setInvalidDecl();
16141
16142 if (FD && FD->hasAttr<NakedAttr>()) {
16143 for (const Stmt *S : Body->children()) {
16144 // Allow local register variables without initializer as they don't
16145 // require prologue.
16146 bool RegisterVariables = false;
16147 if (auto *DS = dyn_cast<DeclStmt>(S)) {
16148 for (const auto *Decl : DS->decls()) {
16149 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
16150 RegisterVariables =
16151 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
16152 if (!RegisterVariables)
16153 break;
16154 }
16155 }
16156 }
16157 if (RegisterVariables)
16158 continue;
16159 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
16160 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
16161 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
16162 FD->setInvalidDecl();
16163 break;
16164 }
16165 }
16166 }
16167
16168 assert(ExprCleanupObjects.size() ==
16169 ExprEvalContexts.back().NumCleanupObjects &&
16170 "Leftover temporaries in function");
16171 assert(!Cleanup.exprNeedsCleanups() &&
16172 "Unaccounted cleanups in function");
16173 assert(MaybeODRUseExprs.empty() &&
16174 "Leftover expressions for odr-use checking");
16175 }
16176 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
16177 // the declaration context below. Otherwise, we're unable to transform
16178 // 'this' expressions when transforming immediate context functions.
16179
16180 if (!IsInstantiation)
16182
16183 PopFunctionScopeInfo(ActivePolicy, dcl);
16184 // If any errors have occurred, clear out any temporaries that may have
16185 // been leftover. This ensures that these temporaries won't be picked up for
16186 // deletion in some later function.
16189 }
16190
16191 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice ||
16192 !LangOpts.OMPTargetTriples.empty())) ||
16193 LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
16194 auto ES = getEmissionStatus(FD);
16197 DeclsToCheckForDeferredDiags.insert(FD);
16198 }
16199
16200 if (FD && !FD->isDeleted())
16201 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
16202
16203 return dcl;
16204}
16205
16206/// When we finish delayed parsing of an attribute, we must attach it to the
16207/// relevant Decl.
16209 ParsedAttributes &Attrs) {
16210 // Always attach attributes to the underlying decl.
16211 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
16212 D = TD->getTemplatedDecl();
16213 ProcessDeclAttributeList(S, D, Attrs);
16215
16216 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
16217 if (Method->isStatic())
16219}
16220
16222 IdentifierInfo &II, Scope *S) {
16223 // It is not valid to implicitly define a function in C23.
16225 "Implicit function declarations aren't allowed in this language mode");
16226
16227 // Find the scope in which the identifier is injected and the corresponding
16228 // DeclContext.
16229 // FIXME: C89 does not say what happens if there is no enclosing block scope.
16230 // In that case, we inject the declaration into the translation unit scope
16231 // instead.
16232 Scope *BlockScope = S;
16233 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
16234 BlockScope = BlockScope->getParent();
16235
16236 // Loop until we find a DeclContext that is either a function/method or the
16237 // translation unit, which are the only two valid places to implicitly define
16238 // a function. This avoids accidentally defining the function within a tag
16239 // declaration, for example.
16240 Scope *ContextScope = BlockScope;
16241 while (!ContextScope->getEntity() ||
16242 (!ContextScope->getEntity()->isFunctionOrMethod() &&
16243 !ContextScope->getEntity()->isTranslationUnit()))
16244 ContextScope = ContextScope->getParent();
16245 ContextRAII SavedContext(*this, ContextScope->getEntity());
16246
16247 // Before we produce a declaration for an implicitly defined
16248 // function, see whether there was a locally-scoped declaration of
16249 // this name as a function or variable. If so, use that
16250 // (non-visible) declaration, and complain about it.
16251 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
16252 if (ExternCPrev) {
16253 // We still need to inject the function into the enclosing block scope so
16254 // that later (non-call) uses can see it.
16255 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
16256
16257 // C89 footnote 38:
16258 // If in fact it is not defined as having type "function returning int",
16259 // the behavior is undefined.
16260 if (!isa<FunctionDecl>(ExternCPrev) ||
16262 cast<FunctionDecl>(ExternCPrev)->getType(),
16264 Diag(Loc, diag::ext_use_out_of_scope_declaration)
16265 << ExternCPrev << !getLangOpts().C99;
16266 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
16267 return ExternCPrev;
16268 }
16269 }
16270
16271 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
16272 unsigned diag_id;
16273 if (II.getName().starts_with("__builtin_"))
16274 diag_id = diag::warn_builtin_unknown;
16275 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
16276 else if (getLangOpts().C99)
16277 diag_id = diag::ext_implicit_function_decl_c99;
16278 else
16279 diag_id = diag::warn_implicit_function_decl;
16280
16281 TypoCorrection Corrected;
16282 // Because typo correction is expensive, only do it if the implicit
16283 // function declaration is going to be treated as an error.
16284 //
16285 // Perform the correction before issuing the main diagnostic, as some
16286 // consumers use typo-correction callbacks to enhance the main diagnostic.
16287 if (S && !ExternCPrev &&
16291 S, nullptr, CCC, CTK_NonError);
16292 }
16293
16294 Diag(Loc, diag_id) << &II;
16295 if (Corrected) {
16296 // If the correction is going to suggest an implicitly defined function,
16297 // skip the correction as not being a particularly good idea.
16298 bool Diagnose = true;
16299 if (const auto *D = Corrected.getCorrectionDecl())
16300 Diagnose = !D->isImplicit();
16301 if (Diagnose)
16302 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
16303 /*ErrorRecovery*/ false);
16304 }
16305
16306 // If we found a prior declaration of this function, don't bother building
16307 // another one. We've already pushed that one into scope, so there's nothing
16308 // more to do.
16309 if (ExternCPrev)
16310 return ExternCPrev;
16311
16312 // Set a Declarator for the implicit definition: int foo();
16313 const char *Dummy;
16314 AttributeFactory attrFactory;
16315 DeclSpec DS(attrFactory);
16316 unsigned DiagID;
16317 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
16319 (void)Error; // Silence warning.
16320 assert(!Error && "Error setting up implicit decl!");
16321 SourceLocation NoLoc;
16323 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
16324 /*IsAmbiguous=*/false,
16325 /*LParenLoc=*/NoLoc,
16326 /*Params=*/nullptr,
16327 /*NumParams=*/0,
16328 /*EllipsisLoc=*/NoLoc,
16329 /*RParenLoc=*/NoLoc,
16330 /*RefQualifierIsLvalueRef=*/true,
16331 /*RefQualifierLoc=*/NoLoc,
16332 /*MutableLoc=*/NoLoc, EST_None,
16333 /*ESpecRange=*/SourceRange(),
16334 /*Exceptions=*/nullptr,
16335 /*ExceptionRanges=*/nullptr,
16336 /*NumExceptions=*/0,
16337 /*NoexceptExpr=*/nullptr,
16338 /*ExceptionSpecTokens=*/nullptr,
16339 /*DeclsInPrototype=*/std::nullopt,
16340 Loc, Loc, D),
16341 std::move(DS.getAttributes()), SourceLocation());
16342 D.SetIdentifier(&II, Loc);
16343
16344 // Insert this function into the enclosing block scope.
16345 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
16346 FD->setImplicit();
16347
16349
16350 return FD;
16351}
16352
16354 FunctionDecl *FD) {
16355 if (FD->isInvalidDecl())
16356 return;
16357
16358 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
16359 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
16360 return;
16361
16362 std::optional<unsigned> AlignmentParam;
16363 bool IsNothrow = false;
16364 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
16365 return;
16366
16367 // C++2a [basic.stc.dynamic.allocation]p4:
16368 // An allocation function that has a non-throwing exception specification
16369 // indicates failure by returning a null pointer value. Any other allocation
16370 // function never returns a null pointer value and indicates failure only by
16371 // throwing an exception [...]
16372 //
16373 // However, -fcheck-new invalidates this possible assumption, so don't add
16374 // NonNull when that is enabled.
16375 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
16376 !getLangOpts().CheckNew)
16377 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
16378
16379 // C++2a [basic.stc.dynamic.allocation]p2:
16380 // An allocation function attempts to allocate the requested amount of
16381 // storage. [...] If the request succeeds, the value returned by a
16382 // replaceable allocation function is a [...] pointer value p0 different
16383 // from any previously returned value p1 [...]
16384 //
16385 // However, this particular information is being added in codegen,
16386 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
16387
16388 // C++2a [basic.stc.dynamic.allocation]p2:
16389 // An allocation function attempts to allocate the requested amount of
16390 // storage. If it is successful, it returns the address of the start of a
16391 // block of storage whose length in bytes is at least as large as the
16392 // requested size.
16393 if (!FD->hasAttr<AllocSizeAttr>()) {
16394 FD->addAttr(AllocSizeAttr::CreateImplicit(
16395 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
16396 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
16397 }
16398
16399 // C++2a [basic.stc.dynamic.allocation]p3:
16400 // For an allocation function [...], the pointer returned on a successful
16401 // call shall represent the address of storage that is aligned as follows:
16402 // (3.1) If the allocation function takes an argument of type
16403 // std​::​align_­val_­t, the storage will have the alignment
16404 // specified by the value of this argument.
16405 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
16406 FD->addAttr(AllocAlignAttr::CreateImplicit(
16407 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
16408 }
16409
16410 // FIXME:
16411 // C++2a [basic.stc.dynamic.allocation]p3:
16412 // For an allocation function [...], the pointer returned on a successful
16413 // call shall represent the address of storage that is aligned as follows:
16414 // (3.2) Otherwise, if the allocation function is named operator new[],
16415 // the storage is aligned for any object that does not have
16416 // new-extended alignment ([basic.align]) and is no larger than the
16417 // requested size.
16418 // (3.3) Otherwise, the storage is aligned for any object that does not
16419 // have new-extended alignment and is of the requested size.
16420}
16421
16423 if (FD->isInvalidDecl())
16424 return;
16425
16426 // If this is a built-in function, map its builtin attributes to
16427 // actual attributes.
16428 if (unsigned BuiltinID = FD->getBuiltinID()) {
16429 // Handle printf-formatting attributes.
16430 unsigned FormatIdx;
16431 bool HasVAListArg;
16432 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
16433 if (!FD->hasAttr<FormatAttr>()) {
16434 const char *fmt = "printf";
16435 unsigned int NumParams = FD->getNumParams();
16436 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
16437 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
16438 fmt = "NSString";
16439 FD->addAttr(FormatAttr::CreateImplicit(Context,
16440 &Context.Idents.get(fmt),
16441 FormatIdx+1,
16442 HasVAListArg ? 0 : FormatIdx+2,
16443 FD->getLocation()));
16444 }
16445 }
16446 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
16447 HasVAListArg)) {
16448 if (!FD->hasAttr<FormatAttr>())
16449 FD->addAttr(FormatAttr::CreateImplicit(Context,
16450 &Context.Idents.get("scanf"),
16451 FormatIdx+1,
16452 HasVAListArg ? 0 : FormatIdx+2,
16453 FD->getLocation()));
16454 }
16455
16456 // Handle automatically recognized callbacks.
16457 SmallVector<int, 4> Encoding;
16458 if (!FD->hasAttr<CallbackAttr>() &&
16459 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
16460 FD->addAttr(CallbackAttr::CreateImplicit(
16461 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
16462
16463 // Mark const if we don't care about errno and/or floating point exceptions
16464 // that are the only thing preventing the function from being const. This
16465 // allows IRgen to use LLVM intrinsics for such functions.
16466 bool NoExceptions =
16468 bool ConstWithoutErrnoAndExceptions =
16470 bool ConstWithoutExceptions =
16472 if (!FD->hasAttr<ConstAttr>() &&
16473 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
16474 (!ConstWithoutErrnoAndExceptions ||
16475 (!getLangOpts().MathErrno && NoExceptions)) &&
16476 (!ConstWithoutExceptions || NoExceptions))
16477 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16478
16479 // We make "fma" on GNU or Windows const because we know it does not set
16480 // errno in those environments even though it could set errno based on the
16481 // C standard.
16482 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
16483 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
16484 !FD->hasAttr<ConstAttr>()) {
16485 switch (BuiltinID) {
16486 case Builtin::BI__builtin_fma:
16487 case Builtin::BI__builtin_fmaf:
16488 case Builtin::BI__builtin_fmal:
16489 case Builtin::BIfma:
16490 case Builtin::BIfmaf:
16491 case Builtin::BIfmal:
16492 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16493 break;
16494 default:
16495 break;
16496 }
16497 }
16498
16499 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
16500 !FD->hasAttr<ReturnsTwiceAttr>())
16501 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
16502 FD->getLocation()));
16503 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
16504 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16505 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
16506 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
16507 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
16508 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
16509 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
16510 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
16511 // Add the appropriate attribute, depending on the CUDA compilation mode
16512 // and which target the builtin belongs to. For example, during host
16513 // compilation, aux builtins are __device__, while the rest are __host__.
16514 if (getLangOpts().CUDAIsDevice !=
16516 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
16517 else
16518 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
16519 }
16520
16521 // Add known guaranteed alignment for allocation functions.
16522 switch (BuiltinID) {
16523 case Builtin::BImemalign:
16524 case Builtin::BIaligned_alloc:
16525 if (!FD->hasAttr<AllocAlignAttr>())
16526 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
16527 FD->getLocation()));
16528 break;
16529 default:
16530 break;
16531 }
16532
16533 // Add allocsize attribute for allocation functions.
16534 switch (BuiltinID) {
16535 case Builtin::BIcalloc:
16536 FD->addAttr(AllocSizeAttr::CreateImplicit(
16537 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
16538 break;
16539 case Builtin::BImemalign:
16540 case Builtin::BIaligned_alloc:
16541 case Builtin::BIrealloc:
16542 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
16543 ParamIdx(), FD->getLocation()));
16544 break;
16545 case Builtin::BImalloc:
16546 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
16547 ParamIdx(), FD->getLocation()));
16548 break;
16549 default:
16550 break;
16551 }
16552
16553 // Add lifetime attribute to std::move, std::fowrard et al.
16554 switch (BuiltinID) {
16555 case Builtin::BIaddressof:
16556 case Builtin::BI__addressof:
16557 case Builtin::BI__builtin_addressof:
16558 case Builtin::BIas_const:
16559 case Builtin::BIforward:
16560 case Builtin::BIforward_like:
16561 case Builtin::BImove:
16562 case Builtin::BImove_if_noexcept:
16563 if (ParmVarDecl *P = FD->getParamDecl(0u);
16564 !P->hasAttr<LifetimeBoundAttr>())
16565 P->addAttr(
16566 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
16567 break;
16568 default:
16569 break;
16570 }
16571 }
16572
16574
16575 // If C++ exceptions are enabled but we are told extern "C" functions cannot
16576 // throw, add an implicit nothrow attribute to any extern "C" function we come
16577 // across.
16578 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
16579 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
16580 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
16581 if (!FPT || FPT->getExceptionSpecType() == EST_None)
16582 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
16583 }
16584
16585 IdentifierInfo *Name = FD->getIdentifier();
16586 if (!Name)
16587 return;
16589 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
16590 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
16592 // Okay: this could be a libc/libm/Objective-C function we know
16593 // about.
16594 } else
16595 return;
16596
16597 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
16598 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
16599 // target-specific builtins, perhaps?
16600 if (!FD->hasAttr<FormatAttr>())
16601 FD->addAttr(FormatAttr::CreateImplicit(Context,
16602 &Context.Idents.get("printf"), 2,
16603 Name->isStr("vasprintf") ? 0 : 3,
16604 FD->getLocation()));
16605 }
16606
16607 if (Name->isStr("__CFStringMakeConstantString")) {
16608 // We already have a __builtin___CFStringMakeConstantString,
16609 // but builds that use -fno-constant-cfstrings don't go through that.
16610 if (!FD->hasAttr<FormatArgAttr>())
16611 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
16612 FD->getLocation()));
16613 }
16614}
16615
16617 TypeSourceInfo *TInfo) {
16618 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
16619 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
16620
16621 if (!TInfo) {
16622 assert(D.isInvalidType() && "no declarator info for valid type");
16624 }
16625
16626 // Scope manipulation handled by caller.
16627 TypedefDecl *NewTD =
16629 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
16630
16631 // Bail out immediately if we have an invalid declaration.
16632 if (D.isInvalidType()) {
16633 NewTD->setInvalidDecl();
16634 return NewTD;
16635 }
16636
16637 if (D.getDeclSpec().isModulePrivateSpecified()) {
16639 Diag(NewTD->getLocation(), diag::err_module_private_local)
16640 << 2 << NewTD
16641 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
16643 D.getDeclSpec().getModulePrivateSpecLoc());
16644 else
16645 NewTD->setModulePrivate();
16646 }
16647
16648 // C++ [dcl.typedef]p8:
16649 // If the typedef declaration defines an unnamed class (or
16650 // enum), the first typedef-name declared by the declaration
16651 // to be that class type (or enum type) is used to denote the
16652 // class type (or enum type) for linkage purposes only.
16653 // We need to check whether the type was declared in the declaration.
16654 switch (D.getDeclSpec().getTypeSpecType()) {
16655 case TST_enum:
16656 case TST_struct:
16657 case TST_interface:
16658 case TST_union:
16659 case TST_class: {
16660 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
16661 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
16662 break;
16663 }
16664
16665 default:
16666 break;
16667 }
16668
16669 return NewTD;
16670}
16671
16673 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
16674 QualType T = TI->getType();
16675
16676 if (T->isDependentType())
16677 return false;
16678
16679 // This doesn't use 'isIntegralType' despite the error message mentioning
16680 // integral type because isIntegralType would also allow enum types in C.
16681 if (const BuiltinType *BT = T->getAs<BuiltinType>())
16682 if (BT->isInteger())
16683 return false;
16684
16685 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
16686 << T << T->isBitIntType();
16687}
16688
16690 QualType EnumUnderlyingTy, bool IsFixed,
16691 const EnumDecl *Prev) {
16692 if (IsScoped != Prev->isScoped()) {
16693 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
16694 << Prev->isScoped();
16695 Diag(Prev->getLocation(), diag::note_previous_declaration);
16696 return true;
16697 }
16698
16699 if (IsFixed && Prev->isFixed()) {
16700 if (!EnumUnderlyingTy->isDependentType() &&
16701 !Prev->getIntegerType()->isDependentType() &&
16702 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
16703 Prev->getIntegerType())) {
16704 // TODO: Highlight the underlying type of the redeclaration.
16705 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
16706 << EnumUnderlyingTy << Prev->getIntegerType();
16707 Diag(Prev->getLocation(), diag::note_previous_declaration)
16708 << Prev->getIntegerTypeRange();
16709 return true;
16710 }
16711 } else if (IsFixed != Prev->isFixed()) {
16712 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
16713 << Prev->isFixed();
16714 Diag(Prev->getLocation(), diag::note_previous_declaration);
16715 return true;
16716 }
16717
16718 return false;
16719}
16720
16721/// Get diagnostic %select index for tag kind for
16722/// redeclaration diagnostic message.
16723/// WARNING: Indexes apply to particular diagnostics only!
16724///
16725/// \returns diagnostic %select index.
16727 switch (Tag) {
16729 return 0;
16731 return 1;
16732 case TagTypeKind::Class:
16733 return 2;
16734 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
16735 }
16736}
16737
16738/// Determine if tag kind is a class-key compatible with
16739/// class for redeclaration (class, struct, or __interface).
16740///
16741/// \returns true iff the tag kind is compatible.
16743{
16744 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
16746}
16747
16749 TagTypeKind TTK) {
16750 if (isa<TypedefDecl>(PrevDecl))
16751 return NTK_Typedef;
16752 else if (isa<TypeAliasDecl>(PrevDecl))
16753 return NTK_TypeAlias;
16754 else if (isa<ClassTemplateDecl>(PrevDecl))
16755 return NTK_Template;
16756 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
16757 return NTK_TypeAliasTemplate;
16758 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
16760 switch (TTK) {
16763 case TagTypeKind::Class:
16764 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
16765 case TagTypeKind::Union:
16766 return NTK_NonUnion;
16767 case TagTypeKind::Enum:
16768 return NTK_NonEnum;
16769 }
16770 llvm_unreachable("invalid TTK");
16771}
16772
16774 TagTypeKind NewTag, bool isDefinition,
16775 SourceLocation NewTagLoc,
16776 const IdentifierInfo *Name) {
16777 // C++ [dcl.type.elab]p3:
16778 // The class-key or enum keyword present in the
16779 // elaborated-type-specifier shall agree in kind with the
16780 // declaration to which the name in the elaborated-type-specifier
16781 // refers. This rule also applies to the form of
16782 // elaborated-type-specifier that declares a class-name or
16783 // friend class since it can be construed as referring to the
16784 // definition of the class. Thus, in any
16785 // elaborated-type-specifier, the enum keyword shall be used to
16786 // refer to an enumeration (7.2), the union class-key shall be
16787 // used to refer to a union (clause 9), and either the class or
16788 // struct class-key shall be used to refer to a class (clause 9)
16789 // declared using the class or struct class-key.
16790 TagTypeKind OldTag = Previous->getTagKind();
16791 if (OldTag != NewTag &&
16792 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
16793 return false;
16794
16795 // Tags are compatible, but we might still want to warn on mismatched tags.
16796 // Non-class tags can't be mismatched at this point.
16797 if (!isClassCompatTagKind(NewTag))
16798 return true;
16799
16800 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
16801 // by our warning analysis. We don't want to warn about mismatches with (eg)
16802 // declarations in system headers that are designed to be specialized, but if
16803 // a user asks us to warn, we should warn if their code contains mismatched
16804 // declarations.
16805 auto IsIgnoredLoc = [&](SourceLocation Loc) {
16806 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
16807 Loc);
16808 };
16809 if (IsIgnoredLoc(NewTagLoc))
16810 return true;
16811
16812 auto IsIgnored = [&](const TagDecl *Tag) {
16813 return IsIgnoredLoc(Tag->getLocation());
16814 };
16815 while (IsIgnored(Previous)) {
16816 Previous = Previous->getPreviousDecl();
16817 if (!Previous)
16818 return true;
16819 OldTag = Previous->getTagKind();
16820 }
16821
16822 bool isTemplate = false;
16823 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
16824 isTemplate = Record->getDescribedClassTemplate();
16825
16827 if (OldTag != NewTag) {
16828 // In a template instantiation, do not offer fix-its for tag mismatches
16829 // since they usually mess up the template instead of fixing the problem.
16830 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16831 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16832 << getRedeclDiagFromTagKind(OldTag);
16833 // FIXME: Note previous location?
16834 }
16835 return true;
16836 }
16837
16838 if (isDefinition) {
16839 // On definitions, check all previous tags and issue a fix-it for each
16840 // one that doesn't match the current tag.
16841 if (Previous->getDefinition()) {
16842 // Don't suggest fix-its for redefinitions.
16843 return true;
16844 }
16845
16846 bool previousMismatch = false;
16847 for (const TagDecl *I : Previous->redecls()) {
16848 if (I->getTagKind() != NewTag) {
16849 // Ignore previous declarations for which the warning was disabled.
16850 if (IsIgnored(I))
16851 continue;
16852
16853 if (!previousMismatch) {
16854 previousMismatch = true;
16855 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
16856 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16857 << getRedeclDiagFromTagKind(I->getTagKind());
16858 }
16859 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
16860 << getRedeclDiagFromTagKind(NewTag)
16861 << FixItHint::CreateReplacement(I->getInnerLocStart(),
16863 }
16864 }
16865 return true;
16866 }
16867
16868 // Identify the prevailing tag kind: this is the kind of the definition (if
16869 // there is a non-ignored definition), or otherwise the kind of the prior
16870 // (non-ignored) declaration.
16871 const TagDecl *PrevDef = Previous->getDefinition();
16872 if (PrevDef && IsIgnored(PrevDef))
16873 PrevDef = nullptr;
16874 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
16875 if (Redecl->getTagKind() != NewTag) {
16876 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
16877 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
16878 << getRedeclDiagFromTagKind(OldTag);
16879 Diag(Redecl->getLocation(), diag::note_previous_use);
16880
16881 // If there is a previous definition, suggest a fix-it.
16882 if (PrevDef) {
16883 Diag(NewTagLoc, diag::note_struct_class_suggestion)
16887 }
16888 }
16889
16890 return true;
16891}
16892
16893/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
16894/// from an outer enclosing namespace or file scope inside a friend declaration.
16895/// This should provide the commented out code in the following snippet:
16896/// namespace N {
16897/// struct X;
16898/// namespace M {
16899/// struct Y { friend struct /*N::*/ X; };
16900/// }
16901/// }
16903 SourceLocation NameLoc) {
16904 // While the decl is in a namespace, do repeated lookup of that name and see
16905 // if we get the same namespace back. If we do not, continue until
16906 // translation unit scope, at which point we have a fully qualified NNS.
16909 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
16910 // This tag should be declared in a namespace, which can only be enclosed by
16911 // other namespaces. Bail if there's an anonymous namespace in the chain.
16912 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
16913 if (!Namespace || Namespace->isAnonymousNamespace())
16914 return FixItHint();
16915 IdentifierInfo *II = Namespace->getIdentifier();
16916 Namespaces.push_back(II);
16917 NamedDecl *Lookup = SemaRef.LookupSingleName(
16918 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
16919 if (Lookup == Namespace)
16920 break;
16921 }
16922
16923 // Once we have all the namespaces, reverse them to go outermost first, and
16924 // build an NNS.
16925 SmallString<64> Insertion;
16926 llvm::raw_svector_ostream OS(Insertion);
16927 if (DC->isTranslationUnit())
16928 OS << "::";
16929 std::reverse(Namespaces.begin(), Namespaces.end());
16930 for (auto *II : Namespaces)
16931 OS << II->getName() << "::";
16932 return FixItHint::CreateInsertion(NameLoc, Insertion);
16933}
16934
16935/// Determine whether a tag originally declared in context \p OldDC can
16936/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
16937/// found a declaration in \p OldDC as a previous decl, perhaps through a
16938/// using-declaration).
16940 DeclContext *NewDC) {
16941 OldDC = OldDC->getRedeclContext();
16942 NewDC = NewDC->getRedeclContext();
16943
16944 if (OldDC->Equals(NewDC))
16945 return true;
16946
16947 // In MSVC mode, we allow a redeclaration if the contexts are related (either
16948 // encloses the other).
16949 if (S.getLangOpts().MSVCCompat &&
16950 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
16951 return true;
16952
16953 return false;
16954}
16955
16957Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
16958 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
16959 const ParsedAttributesView &Attrs, AccessSpecifier AS,
16960 SourceLocation ModulePrivateLoc,
16961 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
16962 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
16963 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
16964 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
16965 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
16966 // If this is not a definition, it must have a name.
16967 IdentifierInfo *OrigName = Name;
16968 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
16969 "Nameless record must be a definition!");
16970 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
16971
16972 OwnedDecl = false;
16974 bool ScopedEnum = ScopedEnumKWLoc.isValid();
16975
16976 // FIXME: Check member specializations more carefully.
16977 bool isMemberSpecialization = false;
16978 bool Invalid = false;
16979
16980 // We only need to do this matching if we have template parameters
16981 // or a scope specifier, which also conveniently avoids this work
16982 // for non-C++ cases.
16983 if (TemplateParameterLists.size() > 0 ||
16984 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
16985 TemplateParameterList *TemplateParams =
16987 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
16988 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
16989
16990 // C++23 [dcl.type.elab] p2:
16991 // If an elaborated-type-specifier is the sole constituent of a
16992 // declaration, the declaration is ill-formed unless it is an explicit
16993 // specialization, an explicit instantiation or it has one of the
16994 // following forms: [...]
16995 // C++23 [dcl.enum] p1:
16996 // If the enum-head-name of an opaque-enum-declaration contains a
16997 // nested-name-specifier, the declaration shall be an explicit
16998 // specialization.
16999 //
17000 // FIXME: Class template partial specializations can be forward declared
17001 // per CWG2213, but the resolution failed to allow qualified forward
17002 // declarations. This is almost certainly unintentional, so we allow them.
17003 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17004 !isMemberSpecialization)
17005 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17007
17008 if (TemplateParams) {
17009 if (Kind == TagTypeKind::Enum) {
17010 Diag(KWLoc, diag::err_enum_template);
17011 return true;
17012 }
17013
17014 if (TemplateParams->size() > 0) {
17015 // This is a declaration or definition of a class template (which may
17016 // be a member of another template).
17017
17018 if (Invalid)
17019 return true;
17020
17021 OwnedDecl = false;
17023 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17024 AS, ModulePrivateLoc,
17025 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17026 TemplateParameterLists.data(), SkipBody);
17027 return Result.get();
17028 } else {
17029 // The "template<>" header is extraneous.
17030 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17031 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17032 isMemberSpecialization = true;
17033 }
17034 }
17035
17036 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17037 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17038 return true;
17039 }
17040
17041 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17042 // C++23 [dcl.type.elab]p4:
17043 // If an elaborated-type-specifier appears with the friend specifier as
17044 // an entire member-declaration, the member-declaration shall have one
17045 // of the following forms:
17046 // friend class-key nested-name-specifier(opt) identifier ;
17047 // friend class-key simple-template-id ;
17048 // friend class-key nested-name-specifier template(opt)
17049 // simple-template-id ;
17050 //
17051 // Since enum is not a class-key, so declarations like "friend enum E;"
17052 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17053 // invalid, most implementations accept so we issue a pedantic warning.
17054 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17055 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17056 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17057 Diag(KWLoc, diag::note_enum_friend)
17058 << (ScopedEnum + ScopedEnumUsesClassTag);
17059 }
17060
17061 // Figure out the underlying type if this a enum declaration. We need to do
17062 // this early, because it's needed to detect if this is an incompatible
17063 // redeclaration.
17064 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17065 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17066
17067 if (Kind == TagTypeKind::Enum) {
17068 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17069 // No underlying type explicitly specified, or we failed to parse the
17070 // type, default to int.
17071 EnumUnderlying = Context.IntTy.getTypePtr();
17072 } else if (UnderlyingType.get()) {
17073 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17074 // integral type; any cv-qualification is ignored.
17075 TypeSourceInfo *TI = nullptr;
17076 GetTypeFromParser(UnderlyingType.get(), &TI);
17077 EnumUnderlying = TI;
17078
17080 // Recover by falling back to int.
17081 EnumUnderlying = Context.IntTy.getTypePtr();
17082
17085 EnumUnderlying = Context.IntTy.getTypePtr();
17086
17087 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17088 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17089 // of 'int'. However, if this is an unfixed forward declaration, don't set
17090 // the underlying type unless the user enables -fms-compatibility. This
17091 // makes unfixed forward declared enums incomplete and is more conforming.
17092 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
17093 EnumUnderlying = Context.IntTy.getTypePtr();
17094 }
17095 }
17096
17097 DeclContext *SearchDC = CurContext;
17098 DeclContext *DC = CurContext;
17099 bool isStdBadAlloc = false;
17100 bool isStdAlignValT = false;
17101
17103 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
17104 Redecl = RedeclarationKind::NotForRedeclaration;
17105
17106 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
17107 /// implemented asks for structural equivalence checking, the returned decl
17108 /// here is passed back to the parser, allowing the tag body to be parsed.
17109 auto createTagFromNewDecl = [&]() -> TagDecl * {
17110 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
17111 // If there is an identifier, use the location of the identifier as the
17112 // location of the decl, otherwise use the location of the struct/union
17113 // keyword.
17114 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17115 TagDecl *New = nullptr;
17116
17117 if (Kind == TagTypeKind::Enum) {
17118 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
17119 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
17120 // If this is an undefined enum, bail.
17121 if (TUK != TagUseKind::Definition && !Invalid)
17122 return nullptr;
17123 if (EnumUnderlying) {
17124 EnumDecl *ED = cast<EnumDecl>(New);
17125 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
17127 else
17128 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17129 QualType EnumTy = ED->getIntegerType();
17132 : EnumTy);
17133 }
17134 } else { // struct/union
17135 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17136 nullptr);
17137 }
17138
17139 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17140 // Add alignment attributes if necessary; these attributes are checked
17141 // when the ASTContext lays out the structure.
17142 //
17143 // It is important for implementing the correct semantics that this
17144 // happen here (in ActOnTag). The #pragma pack stack is
17145 // maintained as a result of parser callbacks which can occur at
17146 // many points during the parsing of a struct declaration (because
17147 // the #pragma tokens are effectively skipped over during the
17148 // parsing of the struct).
17149 if (TUK == TagUseKind::Definition &&
17150 (!SkipBody || !SkipBody->ShouldSkip)) {
17153 }
17154 }
17156 return New;
17157 };
17158
17159 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
17160 if (Name && SS.isNotEmpty()) {
17161 // We have a nested-name tag ('struct foo::bar').
17162
17163 // Check for invalid 'foo::'.
17164 if (SS.isInvalid()) {
17165 Name = nullptr;
17166 goto CreateNewDecl;
17167 }
17168
17169 // If this is a friend or a reference to a class in a dependent
17170 // context, don't try to make a decl for it.
17171 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17172 DC = computeDeclContext(SS, false);
17173 if (!DC) {
17174 IsDependent = true;
17175 return true;
17176 }
17177 } else {
17178 DC = computeDeclContext(SS, true);
17179 if (!DC) {
17180 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
17181 << SS.getRange();
17182 return true;
17183 }
17184 }
17185
17186 if (RequireCompleteDeclContext(SS, DC))
17187 return true;
17188
17189 SearchDC = DC;
17190 // Look-up name inside 'foo::'.
17192
17193 if (Previous.isAmbiguous())
17194 return true;
17195
17196 if (Previous.empty()) {
17197 // Name lookup did not find anything. However, if the
17198 // nested-name-specifier refers to the current instantiation,
17199 // and that current instantiation has any dependent base
17200 // classes, we might find something at instantiation time: treat
17201 // this as a dependent elaborated-type-specifier.
17202 // But this only makes any sense for reference-like lookups.
17203 if (Previous.wasNotFoundInCurrentInstantiation() &&
17204 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
17205 IsDependent = true;
17206 return true;
17207 }
17208
17209 // A tag 'foo::bar' must already exist.
17210 Diag(NameLoc, diag::err_not_tag_in_scope)
17211 << llvm::to_underlying(Kind) << Name << DC << SS.getRange();
17212 Name = nullptr;
17213 Invalid = true;
17214 goto CreateNewDecl;
17215 }
17216 } else if (Name) {
17217 // C++14 [class.mem]p14:
17218 // If T is the name of a class, then each of the following shall have a
17219 // name different from T:
17220 // -- every member of class T that is itself a type
17221 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
17222 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
17223 return true;
17224
17225 // If this is a named struct, check to see if there was a previous forward
17226 // declaration or definition.
17227 // FIXME: We're looking into outer scopes here, even when we
17228 // shouldn't be. Doing so can result in ambiguities that we
17229 // shouldn't be diagnosing.
17230 LookupName(Previous, S);
17231
17232 // When declaring or defining a tag, ignore ambiguities introduced
17233 // by types using'ed into this scope.
17234 if (Previous.isAmbiguous() &&
17236 LookupResult::Filter F = Previous.makeFilter();
17237 while (F.hasNext()) {
17238 NamedDecl *ND = F.next();
17239 if (!ND->getDeclContext()->getRedeclContext()->Equals(
17240 SearchDC->getRedeclContext()))
17241 F.erase();
17242 }
17243 F.done();
17244 }
17245
17246 // C++11 [namespace.memdef]p3:
17247 // If the name in a friend declaration is neither qualified nor
17248 // a template-id and the declaration is a function or an
17249 // elaborated-type-specifier, the lookup to determine whether
17250 // the entity has been previously declared shall not consider
17251 // any scopes outside the innermost enclosing namespace.
17252 //
17253 // MSVC doesn't implement the above rule for types, so a friend tag
17254 // declaration may be a redeclaration of a type declared in an enclosing
17255 // scope. They do implement this rule for friend functions.
17256 //
17257 // Does it matter that this should be by scope instead of by
17258 // semantic context?
17259 if (!Previous.empty() && TUK == TagUseKind::Friend) {
17260 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
17261 LookupResult::Filter F = Previous.makeFilter();
17262 bool FriendSawTagOutsideEnclosingNamespace = false;
17263 while (F.hasNext()) {
17264 NamedDecl *ND = F.next();
17266 if (DC->isFileContext() &&
17267 !EnclosingNS->Encloses(ND->getDeclContext())) {
17268 if (getLangOpts().MSVCCompat)
17269 FriendSawTagOutsideEnclosingNamespace = true;
17270 else
17271 F.erase();
17272 }
17273 }
17274 F.done();
17275
17276 // Diagnose this MSVC extension in the easy case where lookup would have
17277 // unambiguously found something outside the enclosing namespace.
17278 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
17279 NamedDecl *ND = Previous.getFoundDecl();
17280 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
17281 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
17282 }
17283 }
17284
17285 // Note: there used to be some attempt at recovery here.
17286 if (Previous.isAmbiguous())
17287 return true;
17288
17289 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
17290 // FIXME: This makes sure that we ignore the contexts associated
17291 // with C structs, unions, and enums when looking for a matching
17292 // tag declaration or definition. See the similar lookup tweak
17293 // in Sema::LookupName; is there a better way to deal with this?
17294 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
17295 SearchDC = SearchDC->getParent();
17296 } else if (getLangOpts().CPlusPlus) {
17297 // Inside ObjCContainer want to keep it as a lexical decl context but go
17298 // past it (most often to TranslationUnit) to find the semantic decl
17299 // context.
17300 while (isa<ObjCContainerDecl>(SearchDC))
17301 SearchDC = SearchDC->getParent();
17302 }
17303 } else if (getLangOpts().CPlusPlus) {
17304 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
17305 // TagDecl the same way as we skip it for named TagDecl.
17306 while (isa<ObjCContainerDecl>(SearchDC))
17307 SearchDC = SearchDC->getParent();
17308 }
17309
17310 if (Previous.isSingleResult() &&
17311 Previous.getFoundDecl()->isTemplateParameter()) {
17312 // Maybe we will complain about the shadowed template parameter.
17313 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
17314 // Just pretend that we didn't see the previous declaration.
17315 Previous.clear();
17316 }
17317
17318 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
17319 DC->Equals(getStdNamespace())) {
17320 if (Name->isStr("bad_alloc")) {
17321 // This is a declaration of or a reference to "std::bad_alloc".
17322 isStdBadAlloc = true;
17323
17324 // If std::bad_alloc has been implicitly declared (but made invisible to
17325 // name lookup), fill in this implicit declaration as the previous
17326 // declaration, so that the declarations get chained appropriately.
17327 if (Previous.empty() && StdBadAlloc)
17328 Previous.addDecl(getStdBadAlloc());
17329 } else if (Name->isStr("align_val_t")) {
17330 isStdAlignValT = true;
17331 if (Previous.empty() && StdAlignValT)
17332 Previous.addDecl(getStdAlignValT());
17333 }
17334 }
17335
17336 // If we didn't find a previous declaration, and this is a reference
17337 // (or friend reference), move to the correct scope. In C++, we
17338 // also need to do a redeclaration lookup there, just in case
17339 // there's a shadow friend decl.
17340 if (Name && Previous.empty() &&
17341 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17342 IsTemplateParamOrArg)) {
17343 if (Invalid) goto CreateNewDecl;
17344 assert(SS.isEmpty());
17345
17346 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
17347 // C++ [basic.scope.pdecl]p5:
17348 // -- for an elaborated-type-specifier of the form
17349 //
17350 // class-key identifier
17351 //
17352 // if the elaborated-type-specifier is used in the
17353 // decl-specifier-seq or parameter-declaration-clause of a
17354 // function defined in namespace scope, the identifier is
17355 // declared as a class-name in the namespace that contains
17356 // the declaration; otherwise, except as a friend
17357 // declaration, the identifier is declared in the smallest
17358 // non-class, non-function-prototype scope that contains the
17359 // declaration.
17360 //
17361 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
17362 // C structs and unions.
17363 //
17364 // It is an error in C++ to declare (rather than define) an enum
17365 // type, including via an elaborated type specifier. We'll
17366 // diagnose that later; for now, declare the enum in the same
17367 // scope as we would have picked for any other tag type.
17368 //
17369 // GNU C also supports this behavior as part of its incomplete
17370 // enum types extension, while GNU C++ does not.
17371 //
17372 // Find the context where we'll be declaring the tag.
17373 // FIXME: We would like to maintain the current DeclContext as the
17374 // lexical context,
17375 SearchDC = getTagInjectionContext(SearchDC);
17376
17377 // Find the scope where we'll be declaring the tag.
17379 } else {
17380 assert(TUK == TagUseKind::Friend);
17381 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
17382
17383 // C++ [namespace.memdef]p3:
17384 // If a friend declaration in a non-local class first declares a
17385 // class or function, the friend class or function is a member of
17386 // the innermost enclosing namespace.
17387 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
17388 : SearchDC->getEnclosingNamespaceContext();
17389 }
17390
17391 // In C++, we need to do a redeclaration lookup to properly
17392 // diagnose some problems.
17393 // FIXME: redeclaration lookup is also used (with and without C++) to find a
17394 // hidden declaration so that we don't get ambiguity errors when using a
17395 // type declared by an elaborated-type-specifier. In C that is not correct
17396 // and we should instead merge compatible types found by lookup.
17397 if (getLangOpts().CPlusPlus) {
17398 // FIXME: This can perform qualified lookups into function contexts,
17399 // which are meaningless.
17400 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17401 LookupQualifiedName(Previous, SearchDC);
17402 } else {
17403 Previous.setRedeclarationKind(forRedeclarationInCurContext());
17404 LookupName(Previous, S);
17405 }
17406 }
17407
17408 // If we have a known previous declaration to use, then use it.
17409 if (Previous.empty() && SkipBody && SkipBody->Previous)
17410 Previous.addDecl(SkipBody->Previous);
17411
17412 if (!Previous.empty()) {
17413 NamedDecl *PrevDecl = Previous.getFoundDecl();
17414 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
17415
17416 // It's okay to have a tag decl in the same scope as a typedef
17417 // which hides a tag decl in the same scope. Finding this
17418 // with a redeclaration lookup can only actually happen in C++.
17419 //
17420 // This is also okay for elaborated-type-specifiers, which is
17421 // technically forbidden by the current standard but which is
17422 // okay according to the likely resolution of an open issue;
17423 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
17424 if (getLangOpts().CPlusPlus) {
17425 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17426 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
17427 TagDecl *Tag = TT->getDecl();
17428 if (Tag->getDeclName() == Name &&
17429 Tag->getDeclContext()->getRedeclContext()
17430 ->Equals(TD->getDeclContext()->getRedeclContext())) {
17431 PrevDecl = Tag;
17432 Previous.clear();
17433 Previous.addDecl(Tag);
17434 Previous.resolveKind();
17435 }
17436 }
17437 }
17438 }
17439
17440 // If this is a redeclaration of a using shadow declaration, it must
17441 // declare a tag in the same context. In MSVC mode, we allow a
17442 // redefinition if either context is within the other.
17443 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
17444 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
17445 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
17446 TUK != TagUseKind::Friend &&
17447 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
17448 !(OldTag && isAcceptableTagRedeclContext(
17449 *this, OldTag->getDeclContext(), SearchDC))) {
17450 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
17451 Diag(Shadow->getTargetDecl()->getLocation(),
17452 diag::note_using_decl_target);
17453 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
17454 << 0;
17455 // Recover by ignoring the old declaration.
17456 Previous.clear();
17457 goto CreateNewDecl;
17458 }
17459 }
17460
17461 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
17462 // If this is a use of a previous tag, or if the tag is already declared
17463 // in the same scope (so that the definition/declaration completes or
17464 // rementions the tag), reuse the decl.
17465 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
17466 isDeclInScope(DirectPrevDecl, SearchDC, S,
17467 SS.isNotEmpty() || isMemberSpecialization)) {
17468 // Make sure that this wasn't declared as an enum and now used as a
17469 // struct or something similar.
17470 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
17471 TUK == TagUseKind::Definition, KWLoc,
17472 Name)) {
17473 bool SafeToContinue =
17474 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
17475 Kind != TagTypeKind::Enum);
17476 if (SafeToContinue)
17477 Diag(KWLoc, diag::err_use_with_wrong_tag)
17478 << Name
17480 PrevTagDecl->getKindName());
17481 else
17482 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
17483 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
17484
17485 if (SafeToContinue)
17486 Kind = PrevTagDecl->getTagKind();
17487 else {
17488 // Recover by making this an anonymous redefinition.
17489 Name = nullptr;
17490 Previous.clear();
17491 Invalid = true;
17492 }
17493 }
17494
17495 if (Kind == TagTypeKind::Enum &&
17496 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
17497 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
17498 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
17499 return PrevTagDecl;
17500
17501 QualType EnumUnderlyingTy;
17502 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17503 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
17504 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
17505 EnumUnderlyingTy = QualType(T, 0);
17506
17507 // All conflicts with previous declarations are recovered by
17508 // returning the previous declaration, unless this is a definition,
17509 // in which case we want the caller to bail out.
17510 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
17511 ScopedEnum, EnumUnderlyingTy,
17512 IsFixed, PrevEnum))
17513 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
17514 }
17515
17516 // C++11 [class.mem]p1:
17517 // A member shall not be declared twice in the member-specification,
17518 // except that a nested class or member class template can be declared
17519 // and then later defined.
17520 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
17521 S->isDeclScope(PrevDecl)) {
17522 Diag(NameLoc, diag::ext_member_redeclared);
17523 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
17524 }
17525
17526 if (!Invalid) {
17527 // If this is a use, just return the declaration we found, unless
17528 // we have attributes.
17529 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17530 if (!Attrs.empty()) {
17531 // FIXME: Diagnose these attributes. For now, we create a new
17532 // declaration to hold them.
17533 } else if (TUK == TagUseKind::Reference &&
17534 (PrevTagDecl->getFriendObjectKind() ==
17536 PrevDecl->getOwningModule() != getCurrentModule()) &&
17537 SS.isEmpty()) {
17538 // This declaration is a reference to an existing entity, but
17539 // has different visibility from that entity: it either makes
17540 // a friend visible or it makes a type visible in a new module.
17541 // In either case, create a new declaration. We only do this if
17542 // the declaration would have meant the same thing if no prior
17543 // declaration were found, that is, if it was found in the same
17544 // scope where we would have injected a declaration.
17545 if (!getTagInjectionContext(CurContext)->getRedeclContext()
17546 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
17547 return PrevTagDecl;
17548 // This is in the injected scope, create a new declaration in
17549 // that scope.
17551 } else {
17552 return PrevTagDecl;
17553 }
17554 }
17555
17556 // Diagnose attempts to redefine a tag.
17557 if (TUK == TagUseKind::Definition) {
17558 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
17559 // If we're defining a specialization and the previous definition
17560 // is from an implicit instantiation, don't emit an error
17561 // here; we'll catch this in the general case below.
17562 bool IsExplicitSpecializationAfterInstantiation = false;
17563 if (isMemberSpecialization) {
17564 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
17565 IsExplicitSpecializationAfterInstantiation =
17566 RD->getTemplateSpecializationKind() !=
17568 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
17569 IsExplicitSpecializationAfterInstantiation =
17570 ED->getTemplateSpecializationKind() !=
17572 }
17573
17574 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
17575 // not keep more that one definition around (merge them). However,
17576 // ensure the decl passes the structural compatibility check in
17577 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
17578 NamedDecl *Hidden = nullptr;
17579 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
17580 // There is a definition of this tag, but it is not visible. We
17581 // explicitly make use of C++'s one definition rule here, and
17582 // assume that this definition is identical to the hidden one
17583 // we already have. Make the existing definition visible and
17584 // use it in place of this one.
17585 if (!getLangOpts().CPlusPlus) {
17586 // Postpone making the old definition visible until after we
17587 // complete parsing the new one and do the structural
17588 // comparison.
17589 SkipBody->CheckSameAsPrevious = true;
17590 SkipBody->New = createTagFromNewDecl();
17591 SkipBody->Previous = Def;
17592 return Def;
17593 } else {
17594 SkipBody->ShouldSkip = true;
17595 SkipBody->Previous = Def;
17597 // Carry on and handle it like a normal definition. We'll
17598 // skip starting the definition later.
17599 }
17600 } else if (!IsExplicitSpecializationAfterInstantiation) {
17601 // A redeclaration in function prototype scope in C isn't
17602 // visible elsewhere, so merely issue a warning.
17603 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
17604 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
17605 else
17606 Diag(NameLoc, diag::err_redefinition) << Name;
17608 NameLoc.isValid() ? NameLoc : KWLoc);
17609 // If this is a redefinition, recover by making this
17610 // struct be anonymous, which will make any later
17611 // references get the previous definition.
17612 Name = nullptr;
17613 Previous.clear();
17614 Invalid = true;
17615 }
17616 } else {
17617 // If the type is currently being defined, complain
17618 // about a nested redefinition.
17619 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
17620 if (TD->isBeingDefined()) {
17621 Diag(NameLoc, diag::err_nested_redefinition) << Name;
17622 Diag(PrevTagDecl->getLocation(),
17623 diag::note_previous_definition);
17624 Name = nullptr;
17625 Previous.clear();
17626 Invalid = true;
17627 }
17628 }
17629
17630 // Okay, this is definition of a previously declared or referenced
17631 // tag. We're going to create a new Decl for it.
17632 }
17633
17634 // Okay, we're going to make a redeclaration. If this is some kind
17635 // of reference, make sure we build the redeclaration in the same DC
17636 // as the original, and ignore the current access specifier.
17637 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
17638 SearchDC = PrevTagDecl->getDeclContext();
17639 AS = AS_none;
17640 }
17641 }
17642 // If we get here we have (another) forward declaration or we
17643 // have a definition. Just create a new decl.
17644
17645 } else {
17646 // If we get here, this is a definition of a new tag type in a nested
17647 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
17648 // new decl/type. We set PrevDecl to NULL so that the entities
17649 // have distinct types.
17650 Previous.clear();
17651 }
17652 // If we get here, we're going to create a new Decl. If PrevDecl
17653 // is non-NULL, it's a definition of the tag declared by
17654 // PrevDecl. If it's NULL, we have a new definition.
17655
17656 // Otherwise, PrevDecl is not a tag, but was found with tag
17657 // lookup. This is only actually possible in C++, where a few
17658 // things like templates still live in the tag namespace.
17659 } else {
17660 // Use a better diagnostic if an elaborated-type-specifier
17661 // found the wrong kind of type on the first
17662 // (non-redeclaration) lookup.
17663 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
17664 !Previous.isForRedeclaration()) {
17665 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17666 Diag(NameLoc, diag::err_tag_reference_non_tag)
17667 << PrevDecl << NTK << llvm::to_underlying(Kind);
17668 Diag(PrevDecl->getLocation(), diag::note_declared_at);
17669 Invalid = true;
17670
17671 // Otherwise, only diagnose if the declaration is in scope.
17672 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
17673 SS.isNotEmpty() || isMemberSpecialization)) {
17674 // do nothing
17675
17676 // Diagnose implicit declarations introduced by elaborated types.
17677 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
17678 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
17679 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
17680 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17681 Invalid = true;
17682
17683 // Otherwise it's a declaration. Call out a particularly common
17684 // case here.
17685 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
17686 unsigned Kind = 0;
17687 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
17688 Diag(NameLoc, diag::err_tag_definition_of_typedef)
17689 << Name << Kind << TND->getUnderlyingType();
17690 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
17691 Invalid = true;
17692
17693 // Otherwise, diagnose.
17694 } else {
17695 // The tag name clashes with something else in the target scope,
17696 // issue an error and recover by making this tag be anonymous.
17697 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
17698 notePreviousDefinition(PrevDecl, NameLoc);
17699 Name = nullptr;
17700 Invalid = true;
17701 }
17702
17703 // The existing declaration isn't relevant to us; we're in a
17704 // new scope, so clear out the previous declaration.
17705 Previous.clear();
17706 }
17707 }
17708
17709CreateNewDecl:
17710
17711 TagDecl *PrevDecl = nullptr;
17712 if (Previous.isSingleResult())
17713 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
17714
17715 // If there is an identifier, use the location of the identifier as the
17716 // location of the decl, otherwise use the location of the struct/union
17717 // keyword.
17718 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
17719
17720 // Otherwise, create a new declaration. If there is a previous
17721 // declaration of the same entity, the two will be linked via
17722 // PrevDecl.
17723 TagDecl *New;
17724
17725 if (Kind == TagTypeKind::Enum) {
17726 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17727 // enum X { A, B, C } D; D should chain to X.
17728 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
17729 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
17730 ScopedEnumUsesClassTag, IsFixed);
17731
17732 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
17733 StdAlignValT = cast<EnumDecl>(New);
17734
17735 // If this is an undefined enum, warn.
17736 if (TUK != TagUseKind::Definition && !Invalid) {
17737 TagDecl *Def;
17738 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
17739 // C++0x: 7.2p2: opaque-enum-declaration.
17740 // Conflicts are diagnosed above. Do nothing.
17741 }
17742 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
17743 Diag(Loc, diag::ext_forward_ref_enum_def)
17744 << New;
17745 Diag(Def->getLocation(), diag::note_previous_definition);
17746 } else {
17747 unsigned DiagID = diag::ext_forward_ref_enum;
17748 if (getLangOpts().MSVCCompat)
17749 DiagID = diag::ext_ms_forward_ref_enum;
17750 else if (getLangOpts().CPlusPlus)
17751 DiagID = diag::err_forward_ref_enum;
17752 Diag(Loc, DiagID);
17753 }
17754 }
17755
17756 if (EnumUnderlying) {
17757 EnumDecl *ED = cast<EnumDecl>(New);
17758 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
17760 else
17761 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
17762 QualType EnumTy = ED->getIntegerType();
17765 : EnumTy);
17766 assert(ED->isComplete() && "enum with type should be complete");
17767 }
17768 } else {
17769 // struct/union/class
17770
17771 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
17772 // struct X { int A; } D; D should chain to X.
17773 if (getLangOpts().CPlusPlus) {
17774 // FIXME: Look for a way to use RecordDecl for simple structs.
17775 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17776 cast_or_null<CXXRecordDecl>(PrevDecl));
17777
17778 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
17779 StdBadAlloc = cast<CXXRecordDecl>(New);
17780 } else
17781 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
17782 cast_or_null<RecordDecl>(PrevDecl));
17783 }
17784
17785 // Only C23 and later allow defining new types in 'offsetof()'.
17786 if (OOK != OOK_Outside && TUK == TagUseKind::Definition &&
17788 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
17789 << (OOK == OOK_Macro) << New->getSourceRange();
17790
17791 // C++11 [dcl.type]p3:
17792 // A type-specifier-seq shall not define a class or enumeration [...].
17793 if (!Invalid && getLangOpts().CPlusPlus &&
17794 (IsTypeSpecifier || IsTemplateParamOrArg) &&
17795 TUK == TagUseKind::Definition) {
17796 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
17797 << Context.getTagDeclType(New);
17798 Invalid = true;
17799 }
17800
17802 DC->getDeclKind() == Decl::Enum) {
17803 Diag(New->getLocation(), diag::err_type_defined_in_enum)
17804 << Context.getTagDeclType(New);
17805 Invalid = true;
17806 }
17807
17808 // Maybe add qualifier info.
17809 if (SS.isNotEmpty()) {
17810 if (SS.isSet()) {
17811 // If this is either a declaration or a definition, check the
17812 // nested-name-specifier against the current context.
17813 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
17814 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
17815 /*TemplateId=*/nullptr,
17816 isMemberSpecialization))
17817 Invalid = true;
17818
17820 if (TemplateParameterLists.size() > 0) {
17821 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
17822 }
17823 }
17824 else
17825 Invalid = true;
17826 }
17827
17828 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
17829 // Add alignment attributes if necessary; these attributes are checked when
17830 // the ASTContext lays out the structure.
17831 //
17832 // It is important for implementing the correct semantics that this
17833 // happen here (in ActOnTag). The #pragma pack stack is
17834 // maintained as a result of parser callbacks which can occur at
17835 // many points during the parsing of a struct declaration (because
17836 // the #pragma tokens are effectively skipped over during the
17837 // parsing of the struct).
17838 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
17841 }
17842 }
17843
17844 if (ModulePrivateLoc.isValid()) {
17845 if (isMemberSpecialization)
17846 Diag(New->getLocation(), diag::err_module_private_specialization)
17847 << 2
17848 << FixItHint::CreateRemoval(ModulePrivateLoc);
17849 // __module_private__ does not apply to local classes. However, we only
17850 // diagnose this as an error when the declaration specifiers are
17851 // freestanding. Here, we just ignore the __module_private__.
17852 else if (!SearchDC->isFunctionOrMethod())
17853 New->setModulePrivate();
17854 }
17855
17856 // If this is a specialization of a member class (of a class template),
17857 // check the specialization.
17858 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
17859 Invalid = true;
17860
17861 // If we're declaring or defining a tag in function prototype scope in C,
17862 // note that this type can only be used within the function and add it to
17863 // the list of decls to inject into the function definition scope.
17864 if ((Name || Kind == TagTypeKind::Enum) &&
17865 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
17866 if (getLangOpts().CPlusPlus) {
17867 // C++ [dcl.fct]p6:
17868 // Types shall not be defined in return or parameter types.
17869 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
17870 Diag(Loc, diag::err_type_defined_in_param_type)
17871 << Name;
17872 Invalid = true;
17873 }
17874 } else if (!PrevDecl) {
17875 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
17876 }
17877 }
17878
17879 if (Invalid)
17880 New->setInvalidDecl();
17881
17882 // Set the lexical context. If the tag has a C++ scope specifier, the
17883 // lexical context will be different from the semantic context.
17885
17886 // Mark this as a friend decl if applicable.
17887 // In Microsoft mode, a friend declaration also acts as a forward
17888 // declaration so we always pass true to setObjectOfFriendDecl to make
17889 // the tag name visible.
17890 if (TUK == TagUseKind::Friend)
17891 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
17892
17893 // Set the access specifier.
17894 if (!Invalid && SearchDC->isRecord())
17895 SetMemberAccessSpecifier(New, PrevDecl, AS);
17896
17897 if (PrevDecl)
17898 CheckRedeclarationInModule(New, PrevDecl);
17899
17900 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
17901 New->startDefinition();
17902
17903 ProcessDeclAttributeList(S, New, Attrs);
17904 AddPragmaAttributes(S, New);
17905
17906 // If this has an identifier, add it to the scope stack.
17907 if (TUK == TagUseKind::Friend) {
17908 // We might be replacing an existing declaration in the lookup tables;
17909 // if so, borrow its access specifier.
17910 if (PrevDecl)
17911 New->setAccess(PrevDecl->getAccess());
17912
17914 DC->makeDeclVisibleInContext(New);
17915 if (Name) // can be null along some error paths
17916 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17917 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
17918 } else if (Name) {
17919 S = getNonFieldDeclScope(S);
17920 PushOnScopeChains(New, S, true);
17921 } else {
17922 CurContext->addDecl(New);
17923 }
17924
17925 // If this is the C FILE type, notify the AST context.
17926 if (IdentifierInfo *II = New->getIdentifier())
17927 if (!New->isInvalidDecl() &&
17929 II->isStr("FILE"))
17930 Context.setFILEDecl(New);
17931
17932 if (PrevDecl)
17933 mergeDeclAttributes(New, PrevDecl);
17934
17935 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
17938 }
17939
17940 // If there's a #pragma GCC visibility in scope, set the visibility of this
17941 // record.
17943
17944 if (isMemberSpecialization && !New->isInvalidDecl())
17946
17947 OwnedDecl = true;
17948 // In C++, don't return an invalid declaration. We can't recover well from
17949 // the cases where we make the type anonymous.
17950 if (Invalid && getLangOpts().CPlusPlus) {
17951 if (New->isBeingDefined())
17952 if (auto RD = dyn_cast<RecordDecl>(New))
17953 RD->completeDefinition();
17954 return true;
17955 } else if (SkipBody && SkipBody->ShouldSkip) {
17956 return SkipBody->Previous;
17957 } else {
17958 return New;
17959 }
17960}
17961
17964 TagDecl *Tag = cast<TagDecl>(TagD);
17965
17966 // Enter the tag context.
17967 PushDeclContext(S, Tag);
17968
17970
17971 // If there's a #pragma GCC visibility in scope, set the visibility of this
17972 // record.
17974}
17975
17977 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
17978 return false;
17979
17980 // Make the previous decl visible.
17982 return true;
17983}
17984
17986 SourceLocation FinalLoc,
17987 bool IsFinalSpelledSealed,
17988 bool IsAbstract,
17989 SourceLocation LBraceLoc) {
17991 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
17992
17993 FieldCollector->StartClass();
17994
17995 if (!Record->getIdentifier())
17996 return;
17997
17998 if (IsAbstract)
17999 Record->markAbstract();
18000
18001 if (FinalLoc.isValid()) {
18002 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18003 IsFinalSpelledSealed
18004 ? FinalAttr::Keyword_sealed
18005 : FinalAttr::Keyword_final));
18006 }
18007 // C++ [class]p2:
18008 // [...] The class-name is also inserted into the scope of the
18009 // class itself; this is known as the injected-class-name. For
18010 // purposes of access checking, the injected-class-name is treated
18011 // as if it were a public member name.
18012 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18013 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18014 Record->getLocation(), Record->getIdentifier(),
18015 /*PrevDecl=*/nullptr,
18016 /*DelayTypeCreation=*/true);
18017 Context.getTypeDeclType(InjectedClassName, Record);
18018 InjectedClassName->setImplicit();
18019 InjectedClassName->setAccess(AS_public);
18020 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18021 InjectedClassName->setDescribedClassTemplate(Template);
18022 PushOnScopeChains(InjectedClassName, S);
18023 assert(InjectedClassName->isInjectedClassName() &&
18024 "Broken injected-class-name");
18025}
18026
18028 SourceRange BraceRange) {
18030 TagDecl *Tag = cast<TagDecl>(TagD);
18031 Tag->setBraceRange(BraceRange);
18032
18033 // Make sure we "complete" the definition even it is invalid.
18034 if (Tag->isBeingDefined()) {
18035 assert(Tag->isInvalidDecl() && "We should already have completed it");
18036 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18037 RD->completeDefinition();
18038 }
18039
18040 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18041 FieldCollector->FinishClass();
18042 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
18043 auto *Def = RD->getDefinition();
18044 assert(Def && "The record is expected to have a completed definition");
18045 unsigned NumInitMethods = 0;
18046 for (auto *Method : Def->methods()) {
18047 if (!Method->getIdentifier())
18048 continue;
18049 if (Method->getName() == "__init")
18050 NumInitMethods++;
18051 }
18052 if (NumInitMethods > 1 || !Def->hasInitMethod())
18053 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
18054 }
18055 }
18056
18057 // Exit this scope of this tag's definition.
18059
18060 if (getCurLexicalContext()->isObjCContainer() &&
18061 Tag->getDeclContext()->isFileContext())
18062 Tag->setTopLevelDeclInObjCContainer();
18063
18064 // Notify the consumer that we've defined a tag.
18065 if (!Tag->isInvalidDecl())
18067
18068 // Clangs implementation of #pragma align(packed) differs in bitfield layout
18069 // from XLs and instead matches the XL #pragma pack(1) behavior.
18070 if (Context.getTargetInfo().getTriple().isOSAIX() &&
18071 AlignPackStack.hasValue()) {
18072 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
18073 // Only diagnose #pragma align(packed).
18074 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
18075 return;
18076 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
18077 if (!RD)
18078 return;
18079 // Only warn if there is at least 1 bitfield member.
18080 if (llvm::any_of(RD->fields(),
18081 [](const FieldDecl *FD) { return FD->isBitField(); }))
18082 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
18083 }
18084}
18085
18088 TagDecl *Tag = cast<TagDecl>(TagD);
18089 Tag->setInvalidDecl();
18090
18091 // Make sure we "complete" the definition even it is invalid.
18092 if (Tag->isBeingDefined()) {
18093 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18094 RD->completeDefinition();
18095 }
18096
18097 // We're undoing ActOnTagStartDefinition here, not
18098 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
18099 // the FieldCollector.
18100
18102}
18103
18104// Note that FieldName may be null for anonymous bitfields.
18106 const IdentifierInfo *FieldName,
18107 QualType FieldTy, bool IsMsStruct,
18108 Expr *BitWidth) {
18109 assert(BitWidth);
18110 if (BitWidth->containsErrors())
18111 return ExprError();
18112
18113 // C99 6.7.2.1p4 - verify the field type.
18114 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
18115 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
18116 // Handle incomplete and sizeless types with a specific error.
18117 if (RequireCompleteSizedType(FieldLoc, FieldTy,
18118 diag::err_field_incomplete_or_sizeless))
18119 return ExprError();
18120 if (FieldName)
18121 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
18122 << FieldName << FieldTy << BitWidth->getSourceRange();
18123 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
18124 << FieldTy << BitWidth->getSourceRange();
18125 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
18127 return ExprError();
18128
18129 // If the bit-width is type- or value-dependent, don't try to check
18130 // it now.
18131 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
18132 return BitWidth;
18133
18134 llvm::APSInt Value;
18136 if (ICE.isInvalid())
18137 return ICE;
18138 BitWidth = ICE.get();
18139
18140 // Zero-width bitfield is ok for anonymous field.
18141 if (Value == 0 && FieldName)
18142 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
18143 << FieldName << BitWidth->getSourceRange();
18144
18145 if (Value.isSigned() && Value.isNegative()) {
18146 if (FieldName)
18147 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
18148 << FieldName << toString(Value, 10);
18149 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
18150 << toString(Value, 10);
18151 }
18152
18153 // The size of the bit-field must not exceed our maximum permitted object
18154 // size.
18155 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
18156 return Diag(FieldLoc, diag::err_bitfield_too_wide)
18157 << !FieldName << FieldName << toString(Value, 10);
18158 }
18159
18160 if (!FieldTy->isDependentType()) {
18161 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
18162 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
18163 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
18164
18165 // Over-wide bitfields are an error in C or when using the MSVC bitfield
18166 // ABI.
18167 bool CStdConstraintViolation =
18168 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
18169 bool MSBitfieldViolation =
18170 Value.ugt(TypeStorageSize) &&
18171 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
18172 if (CStdConstraintViolation || MSBitfieldViolation) {
18173 unsigned DiagWidth =
18174 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
18175 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
18176 << (bool)FieldName << FieldName << toString(Value, 10)
18177 << !CStdConstraintViolation << DiagWidth;
18178 }
18179
18180 // Warn on types where the user might conceivably expect to get all
18181 // specified bits as value bits: that's all integral types other than
18182 // 'bool'.
18183 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
18184 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
18185 << FieldName << toString(Value, 10)
18186 << (unsigned)TypeWidth;
18187 }
18188 }
18189
18190 return BitWidth;
18191}
18192
18194 Declarator &D, Expr *BitfieldWidth) {
18195 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
18196 D, BitfieldWidth,
18197 /*InitStyle=*/ICIS_NoInit, AS_public);
18198 return Res;
18199}
18200
18202 SourceLocation DeclStart,
18203 Declarator &D, Expr *BitWidth,
18204 InClassInitStyle InitStyle,
18205 AccessSpecifier AS) {
18206 if (D.isDecompositionDeclarator()) {
18207 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
18208 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
18209 << Decomp.getSourceRange();
18210 return nullptr;
18211 }
18212
18213 const IdentifierInfo *II = D.getIdentifier();
18214 SourceLocation Loc = DeclStart;
18215 if (II) Loc = D.getIdentifierLoc();
18216
18218 QualType T = TInfo->getType();
18219 if (getLangOpts().CPlusPlus) {
18221
18222 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18224 D.setInvalidType();
18225 T = Context.IntTy;
18227 }
18228 }
18229
18230 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18231
18232 if (D.getDeclSpec().isInlineSpecified())
18233 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18234 << getLangOpts().CPlusPlus17;
18235 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18236 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18237 diag::err_invalid_thread)
18239
18240 // Check to see if this name was declared as a member previously
18241 NamedDecl *PrevDecl = nullptr;
18243 RedeclarationKind::ForVisibleRedeclaration);
18244 LookupName(Previous, S);
18245 switch (Previous.getResultKind()) {
18248 PrevDecl = Previous.getAsSingle<NamedDecl>();
18249 break;
18250
18252 PrevDecl = Previous.getRepresentativeDecl();
18253 break;
18254
18258 break;
18259 }
18260 Previous.suppressDiagnostics();
18261
18262 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18263 // Maybe we will complain about the shadowed template parameter.
18264 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18265 // Just pretend that we didn't see the previous declaration.
18266 PrevDecl = nullptr;
18267 }
18268
18269 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18270 PrevDecl = nullptr;
18271
18272 bool Mutable
18273 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
18274 SourceLocation TSSL = D.getBeginLoc();
18275 FieldDecl *NewFD
18276 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
18277 TSSL, AS, PrevDecl, &D);
18278
18279 if (NewFD->isInvalidDecl())
18280 Record->setInvalidDecl();
18281
18282 if (D.getDeclSpec().isModulePrivateSpecified())
18283 NewFD->setModulePrivate();
18284
18285 if (NewFD->isInvalidDecl() && PrevDecl) {
18286 // Don't introduce NewFD into scope; there's already something
18287 // with the same name in the same scope.
18288 } else if (II) {
18289 PushOnScopeChains(NewFD, S);
18290 } else
18291 Record->addDecl(NewFD);
18292
18293 return NewFD;
18294}
18295
18297 TypeSourceInfo *TInfo,
18299 bool Mutable, Expr *BitWidth,
18300 InClassInitStyle InitStyle,
18301 SourceLocation TSSL,
18302 AccessSpecifier AS, NamedDecl *PrevDecl,
18303 Declarator *D) {
18304 const IdentifierInfo *II = Name.getAsIdentifierInfo();
18305 bool InvalidDecl = false;
18306 if (D) InvalidDecl = D->isInvalidType();
18307
18308 // If we receive a broken type, recover by assuming 'int' and
18309 // marking this declaration as invalid.
18310 if (T.isNull() || T->containsErrors()) {
18311 InvalidDecl = true;
18312 T = Context.IntTy;
18313 }
18314
18316 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
18317 if (RequireCompleteSizedType(Loc, EltTy,
18318 diag::err_field_incomplete_or_sizeless)) {
18319 // Fields of incomplete type force their record to be invalid.
18320 Record->setInvalidDecl();
18321 InvalidDecl = true;
18322 } else {
18323 NamedDecl *Def;
18324 EltTy->isIncompleteType(&Def);
18325 if (Def && Def->isInvalidDecl()) {
18326 Record->setInvalidDecl();
18327 InvalidDecl = true;
18328 }
18329 }
18330 }
18331
18332 // TR 18037 does not allow fields to be declared with address space
18333 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
18335 Diag(Loc, diag::err_field_with_address_space);
18336 Record->setInvalidDecl();
18337 InvalidDecl = true;
18338 }
18339
18340 if (LangOpts.OpenCL) {
18341 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
18342 // used as structure or union field: image, sampler, event or block types.
18343 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
18344 T->isBlockPointerType()) {
18345 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
18346 Record->setInvalidDecl();
18347 InvalidDecl = true;
18348 }
18349 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
18350 // is enabled.
18351 if (BitWidth && !getOpenCLOptions().isAvailableOption(
18352 "__cl_clang_bitfields", LangOpts)) {
18353 Diag(Loc, diag::err_opencl_bitfields);
18354 InvalidDecl = true;
18355 }
18356 }
18357
18358 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
18359 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
18360 T.hasQualifiers()) {
18361 InvalidDecl = true;
18362 Diag(Loc, diag::err_anon_bitfield_qualifiers);
18363 }
18364
18365 // C99 6.7.2.1p8: A member of a structure or union may have any type other
18366 // than a variably modified type.
18367 if (!InvalidDecl && T->isVariablyModifiedType()) {
18369 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
18370 InvalidDecl = true;
18371 }
18372
18373 // Fields can not have abstract class types
18374 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
18375 diag::err_abstract_type_in_decl,
18377 InvalidDecl = true;
18378
18379 if (InvalidDecl)
18380 BitWidth = nullptr;
18381 // If this is declared as a bit-field, check the bit-field.
18382 if (BitWidth) {
18383 BitWidth =
18384 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
18385 if (!BitWidth) {
18386 InvalidDecl = true;
18387 BitWidth = nullptr;
18388 }
18389 }
18390
18391 // Check that 'mutable' is consistent with the type of the declaration.
18392 if (!InvalidDecl && Mutable) {
18393 unsigned DiagID = 0;
18394 if (T->isReferenceType())
18395 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
18396 : diag::err_mutable_reference;
18397 else if (T.isConstQualified())
18398 DiagID = diag::err_mutable_const;
18399
18400 if (DiagID) {
18401 SourceLocation ErrLoc = Loc;
18402 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
18403 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
18404 Diag(ErrLoc, DiagID);
18405 if (DiagID != diag::ext_mutable_reference) {
18406 Mutable = false;
18407 InvalidDecl = true;
18408 }
18409 }
18410 }
18411
18412 // C++11 [class.union]p8 (DR1460):
18413 // At most one variant member of a union may have a
18414 // brace-or-equal-initializer.
18415 if (InitStyle != ICIS_NoInit)
18416 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
18417
18418 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
18419 BitWidth, Mutable, InitStyle);
18420 if (InvalidDecl)
18421 NewFD->setInvalidDecl();
18422
18423 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
18424 !PrevDecl->isPlaceholderVar(getLangOpts())) {
18425 Diag(Loc, diag::err_duplicate_member) << II;
18426 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
18427 NewFD->setInvalidDecl();
18428 }
18429
18430 if (!InvalidDecl && getLangOpts().CPlusPlus) {
18431 if (Record->isUnion()) {
18432 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18433 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
18434 if (RDecl->getDefinition()) {
18435 // C++ [class.union]p1: An object of a class with a non-trivial
18436 // constructor, a non-trivial copy constructor, a non-trivial
18437 // destructor, or a non-trivial copy assignment operator
18438 // cannot be a member of a union, nor can an array of such
18439 // objects.
18440 if (CheckNontrivialField(NewFD))
18441 NewFD->setInvalidDecl();
18442 }
18443 }
18444
18445 // C++ [class.union]p1: If a union contains a member of reference type,
18446 // the program is ill-formed, except when compiling with MSVC extensions
18447 // enabled.
18448 if (EltTy->isReferenceType()) {
18449 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
18450 diag::ext_union_member_of_reference_type :
18451 diag::err_union_member_of_reference_type)
18452 << NewFD->getDeclName() << EltTy;
18453 if (!getLangOpts().MicrosoftExt)
18454 NewFD->setInvalidDecl();
18455 }
18456 }
18457 }
18458
18459 // FIXME: We need to pass in the attributes given an AST
18460 // representation, not a parser representation.
18461 if (D) {
18462 // FIXME: The current scope is almost... but not entirely... correct here.
18464
18465 if (NewFD->hasAttrs())
18467 }
18468
18469 // In auto-retain/release, infer strong retension for fields of
18470 // retainable type.
18471 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
18472 NewFD->setInvalidDecl();
18473
18474 if (T.isObjCGCWeak())
18475 Diag(Loc, diag::warn_attribute_weak_on_field);
18476
18477 // PPC MMA non-pointer types are not allowed as field types.
18478 if (Context.getTargetInfo().getTriple().isPPC64() &&
18479 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
18480 NewFD->setInvalidDecl();
18481
18482 NewFD->setAccess(AS);
18483 return NewFD;
18484}
18485
18487 assert(FD);
18488 assert(getLangOpts().CPlusPlus && "valid check only for C++");
18489
18490 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
18491 return false;
18492
18494 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
18495 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
18496 if (RDecl->getDefinition()) {
18497 // We check for copy constructors before constructors
18498 // because otherwise we'll never get complaints about
18499 // copy constructors.
18500
18502 // We're required to check for any non-trivial constructors. Since the
18503 // implicit default constructor is suppressed if there are any
18504 // user-declared constructors, we just need to check that there is a
18505 // trivial default constructor and a trivial copy constructor. (We don't
18506 // worry about move constructors here, since this is a C++98 check.)
18507 if (RDecl->hasNonTrivialCopyConstructor())
18509 else if (!RDecl->hasTrivialDefaultConstructor())
18511 else if (RDecl->hasNonTrivialCopyAssignment())
18513 else if (RDecl->hasNonTrivialDestructor())
18515
18516 if (member != CXXSpecialMemberKind::Invalid) {
18517 if (!getLangOpts().CPlusPlus11 &&
18518 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
18519 // Objective-C++ ARC: it is an error to have a non-trivial field of
18520 // a union. However, system headers in Objective-C programs
18521 // occasionally have Objective-C lifetime objects within unions,
18522 // and rather than cause the program to fail, we make those
18523 // members unavailable.
18525 if (getSourceManager().isInSystemHeader(Loc)) {
18526 if (!FD->hasAttr<UnavailableAttr>())
18527 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
18528 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
18529 return false;
18530 }
18531 }
18532
18533 Diag(
18534 FD->getLocation(),
18536 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
18537 : diag::err_illegal_union_or_anon_struct_member)
18538 << FD->getParent()->isUnion() << FD->getDeclName()
18539 << llvm::to_underlying(member);
18540 DiagnoseNontrivial(RDecl, member);
18541 return !getLangOpts().CPlusPlus11;
18542 }
18543 }
18544 }
18545
18546 return false;
18547}
18548
18550 SmallVectorImpl<Decl *> &AllIvarDecls) {
18551 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
18552 return;
18553
18554 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
18555 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
18556
18557 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
18558 return;
18559 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
18560 if (!ID) {
18561 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
18562 if (!CD->IsClassExtension())
18563 return;
18564 }
18565 // No need to add this to end of @implementation.
18566 else
18567 return;
18568 }
18569 // All conditions are met. Add a new bitfield to the tail end of ivars.
18570 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
18571 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
18572
18573 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
18574 DeclLoc, DeclLoc, nullptr,
18577 DeclLoc),
18579 true);
18580 AllIvarDecls.push_back(Ivar);
18581}
18582
18583/// [class.dtor]p4:
18584/// At the end of the definition of a class, overload resolution is
18585/// performed among the prospective destructors declared in that class with
18586/// an empty argument list to select the destructor for the class, also
18587/// known as the selected destructor.
18588///
18589/// We do the overload resolution here, then mark the selected constructor in the AST.
18590/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
18592 if (!Record->hasUserDeclaredDestructor()) {
18593 return;
18594 }
18595
18596 SourceLocation Loc = Record->getLocation();
18598
18599 for (auto *Decl : Record->decls()) {
18600 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
18601 if (DD->isInvalidDecl())
18602 continue;
18603 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
18604 OCS);
18605 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
18606 }
18607 }
18608
18609 if (OCS.empty()) {
18610 return;
18611 }
18613 unsigned Msg = 0;
18614 OverloadCandidateDisplayKind DisplayKind;
18615
18616 switch (OCS.BestViableFunction(S, Loc, Best)) {
18617 case OR_Success:
18618 case OR_Deleted:
18619 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
18620 break;
18621
18622 case OR_Ambiguous:
18623 Msg = diag::err_ambiguous_destructor;
18624 DisplayKind = OCD_AmbiguousCandidates;
18625 break;
18626
18628 Msg = diag::err_no_viable_destructor;
18629 DisplayKind = OCD_AllCandidates;
18630 break;
18631 }
18632
18633 if (Msg) {
18634 // OpenCL have got their own thing going with destructors. It's slightly broken,
18635 // but we allow it.
18636 if (!S.LangOpts.OpenCL) {
18637 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
18638 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
18639 Record->setInvalidDecl();
18640 }
18641 // It's a bit hacky: At this point we've raised an error but we want the
18642 // rest of the compiler to continue somehow working. However almost
18643 // everything we'll try to do with the class will depend on there being a
18644 // destructor. So let's pretend the first one is selected and hope for the
18645 // best.
18646 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
18647 }
18648}
18649
18650/// [class.mem.special]p5
18651/// Two special member functions are of the same kind if:
18652/// - they are both default constructors,
18653/// - they are both copy or move constructors with the same first parameter
18654/// type, or
18655/// - they are both copy or move assignment operators with the same first
18656/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
18658 CXXMethodDecl *M1,
18659 CXXMethodDecl *M2,
18661 // We don't want to compare templates to non-templates: See
18662 // https://github.com/llvm/llvm-project/issues/59206
18664 return bool(M1->getDescribedFunctionTemplate()) ==
18666 // FIXME: better resolve CWG
18667 // https://cplusplus.github.io/CWG/issues/2787.html
18668 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
18669 M2->getNonObjectParameter(0)->getType()))
18670 return false;
18673 return false;
18674
18675 return true;
18676}
18677
18678/// [class.mem.special]p6:
18679/// An eligible special member function is a special member function for which:
18680/// - the function is not deleted,
18681/// - the associated constraints, if any, are satisfied, and
18682/// - no special member function of the same kind whose associated constraints
18683/// [CWG2595], if any, are satisfied is more constrained.
18687 SmallVector<bool, 4> SatisfactionStatus;
18688
18689 for (CXXMethodDecl *Method : Methods) {
18690 const Expr *Constraints = Method->getTrailingRequiresClause();
18691 if (!Constraints)
18692 SatisfactionStatus.push_back(true);
18693 else {
18694 ConstraintSatisfaction Satisfaction;
18695 if (S.CheckFunctionConstraints(Method, Satisfaction))
18696 SatisfactionStatus.push_back(false);
18697 else
18698 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
18699 }
18700 }
18701
18702 for (size_t i = 0; i < Methods.size(); i++) {
18703 if (!SatisfactionStatus[i])
18704 continue;
18705 CXXMethodDecl *Method = Methods[i];
18706 CXXMethodDecl *OrigMethod = Method;
18707 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
18708 OrigMethod = cast<CXXMethodDecl>(MF);
18709
18710 const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
18711 bool AnotherMethodIsMoreConstrained = false;
18712 for (size_t j = 0; j < Methods.size(); j++) {
18713 if (i == j || !SatisfactionStatus[j])
18714 continue;
18715 CXXMethodDecl *OtherMethod = Methods[j];
18716 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
18717 OtherMethod = cast<CXXMethodDecl>(MF);
18718
18719 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
18720 CSM))
18721 continue;
18722
18723 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
18724 if (!OtherConstraints)
18725 continue;
18726 if (!Constraints) {
18727 AnotherMethodIsMoreConstrained = true;
18728 break;
18729 }
18730 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
18731 {Constraints},
18732 AnotherMethodIsMoreConstrained)) {
18733 // There was an error with the constraints comparison. Exit the loop
18734 // and don't consider this function eligible.
18735 AnotherMethodIsMoreConstrained = true;
18736 }
18737 if (AnotherMethodIsMoreConstrained)
18738 break;
18739 }
18740 // FIXME: Do not consider deleted methods as eligible after implementing
18741 // DR1734 and DR1496.
18742 if (!AnotherMethodIsMoreConstrained) {
18743 Method->setIneligibleOrNotSelected(false);
18744 Record->addedEligibleSpecialMemberFunction(Method,
18745 1 << llvm::to_underlying(CSM));
18746 }
18747 }
18748}
18749
18752 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
18753 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
18754 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
18755 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
18756 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
18757
18758 for (auto *Decl : Record->decls()) {
18759 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
18760 if (!MD) {
18761 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
18762 if (FTD)
18763 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
18764 }
18765 if (!MD)
18766 continue;
18767 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
18768 if (CD->isInvalidDecl())
18769 continue;
18770 if (CD->isDefaultConstructor())
18771 DefaultConstructors.push_back(MD);
18772 else if (CD->isCopyConstructor())
18773 CopyConstructors.push_back(MD);
18774 else if (CD->isMoveConstructor())
18775 MoveConstructors.push_back(MD);
18776 } else if (MD->isCopyAssignmentOperator()) {
18777 CopyAssignmentOperators.push_back(MD);
18778 } else if (MD->isMoveAssignmentOperator()) {
18779 MoveAssignmentOperators.push_back(MD);
18780 }
18781 }
18782
18783 SetEligibleMethods(S, Record, DefaultConstructors,
18785 SetEligibleMethods(S, Record, CopyConstructors,
18787 SetEligibleMethods(S, Record, MoveConstructors,
18789 SetEligibleMethods(S, Record, CopyAssignmentOperators,
18791 SetEligibleMethods(S, Record, MoveAssignmentOperators,
18793}
18794
18795void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
18796 ArrayRef<Decl *> Fields, SourceLocation LBrac,
18797 SourceLocation RBrac,
18798 const ParsedAttributesView &Attrs) {
18799 assert(EnclosingDecl && "missing record or interface decl");
18800
18801 // If this is an Objective-C @implementation or category and we have
18802 // new fields here we should reset the layout of the interface since
18803 // it will now change.
18804 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
18805 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
18806 switch (DC->getKind()) {
18807 default: break;
18808 case Decl::ObjCCategory:
18809 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
18810 break;
18811 case Decl::ObjCImplementation:
18812 Context.
18813 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
18814 break;
18815 }
18816 }
18817
18818 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
18819 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
18820
18821 // Start counting up the number of named members; make sure to include
18822 // members of anonymous structs and unions in the total.
18823 unsigned NumNamedMembers = 0;
18824 if (Record) {
18825 for (const auto *I : Record->decls()) {
18826 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
18827 if (IFD->getDeclName())
18828 ++NumNamedMembers;
18829 }
18830 }
18831
18832 // Verify that all the fields are okay.
18834
18835 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
18836 i != end; ++i) {
18837 FieldDecl *FD = cast<FieldDecl>(*i);
18838
18839 // Get the type for the field.
18840 const Type *FDTy = FD->getType().getTypePtr();
18841
18842 if (!FD->isAnonymousStructOrUnion()) {
18843 // Remember all fields written by the user.
18844 RecFields.push_back(FD);
18845 }
18846
18847 // If the field is already invalid for some reason, don't emit more
18848 // diagnostics about it.
18849 if (FD->isInvalidDecl()) {
18850 EnclosingDecl->setInvalidDecl();
18851 continue;
18852 }
18853
18854 // C99 6.7.2.1p2:
18855 // A structure or union shall not contain a member with
18856 // incomplete or function type (hence, a structure shall not
18857 // contain an instance of itself, but may contain a pointer to
18858 // an instance of itself), except that the last member of a
18859 // structure with more than one named member may have incomplete
18860 // array type; such a structure (and any union containing,
18861 // possibly recursively, a member that is such a structure)
18862 // shall not be a member of a structure or an element of an
18863 // array.
18864 bool IsLastField = (i + 1 == Fields.end());
18865 if (FDTy->isFunctionType()) {
18866 // Field declared as a function.
18867 Diag(FD->getLocation(), diag::err_field_declared_as_function)
18868 << FD->getDeclName();
18869 FD->setInvalidDecl();
18870 EnclosingDecl->setInvalidDecl();
18871 continue;
18872 } else if (FDTy->isIncompleteArrayType() &&
18873 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
18874 if (Record) {
18875 // Flexible array member.
18876 // Microsoft and g++ is more permissive regarding flexible array.
18877 // It will accept flexible array in union and also
18878 // as the sole element of a struct/class.
18879 unsigned DiagID = 0;
18880 if (!Record->isUnion() && !IsLastField) {
18881 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
18882 << FD->getDeclName() << FD->getType()
18883 << llvm::to_underlying(Record->getTagKind());
18884 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
18885 FD->setInvalidDecl();
18886 EnclosingDecl->setInvalidDecl();
18887 continue;
18888 } else if (Record->isUnion())
18889 DiagID = getLangOpts().MicrosoftExt
18890 ? diag::ext_flexible_array_union_ms
18891 : diag::ext_flexible_array_union_gnu;
18892 else if (NumNamedMembers < 1)
18893 DiagID = getLangOpts().MicrosoftExt
18894 ? diag::ext_flexible_array_empty_aggregate_ms
18895 : diag::ext_flexible_array_empty_aggregate_gnu;
18896
18897 if (DiagID)
18898 Diag(FD->getLocation(), DiagID)
18899 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18900 // While the layout of types that contain virtual bases is not specified
18901 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
18902 // virtual bases after the derived members. This would make a flexible
18903 // array member declared at the end of an object not adjacent to the end
18904 // of the type.
18905 if (CXXRecord && CXXRecord->getNumVBases() != 0)
18906 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
18907 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18908 if (!getLangOpts().C99)
18909 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
18910 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind());
18911
18912 // If the element type has a non-trivial destructor, we would not
18913 // implicitly destroy the elements, so disallow it for now.
18914 //
18915 // FIXME: GCC allows this. We should probably either implicitly delete
18916 // the destructor of the containing class, or just allow this.
18917 QualType BaseElem = Context.getBaseElementType(FD->getType());
18918 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
18919 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
18920 << FD->getDeclName() << FD->getType();
18921 FD->setInvalidDecl();
18922 EnclosingDecl->setInvalidDecl();
18923 continue;
18924 }
18925 // Okay, we have a legal flexible array member at the end of the struct.
18926 Record->setHasFlexibleArrayMember(true);
18927 } else {
18928 // In ObjCContainerDecl ivars with incomplete array type are accepted,
18929 // unless they are followed by another ivar. That check is done
18930 // elsewhere, after synthesized ivars are known.
18931 }
18932 } else if (!FDTy->isDependentType() &&
18934 FD->getLocation(), FD->getType(),
18935 diag::err_field_incomplete_or_sizeless)) {
18936 // Incomplete type
18937 FD->setInvalidDecl();
18938 EnclosingDecl->setInvalidDecl();
18939 continue;
18940 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
18941 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
18942 // A type which contains a flexible array member is considered to be a
18943 // flexible array member.
18944 Record->setHasFlexibleArrayMember(true);
18945 if (!Record->isUnion()) {
18946 // If this is a struct/class and this is not the last element, reject
18947 // it. Note that GCC supports variable sized arrays in the middle of
18948 // structures.
18949 if (!IsLastField)
18950 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
18951 << FD->getDeclName() << FD->getType();
18952 else {
18953 // We support flexible arrays at the end of structs in
18954 // other structs as an extension.
18955 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
18956 << FD->getDeclName();
18957 }
18958 }
18959 }
18960 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
18962 diag::err_abstract_type_in_decl,
18964 // Ivars can not have abstract class types
18965 FD->setInvalidDecl();
18966 }
18967 if (Record && FDTTy->getDecl()->hasObjectMember())
18968 Record->setHasObjectMember(true);
18969 if (Record && FDTTy->getDecl()->hasVolatileMember())
18970 Record->setHasVolatileMember(true);
18971 } else if (FDTy->isObjCObjectType()) {
18972 /// A field cannot be an Objective-c object
18973 Diag(FD->getLocation(), diag::err_statically_allocated_object)
18976 FD->setType(T);
18977 } else if (Record && Record->isUnion() &&
18979 getSourceManager().isInSystemHeader(FD->getLocation()) &&
18980 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
18983 // For backward compatibility, fields of C unions declared in system
18984 // headers that have non-trivial ObjC ownership qualifications are marked
18985 // as unavailable unless the qualifier is explicit and __strong. This can
18986 // break ABI compatibility between programs compiled with ARC and MRR, but
18987 // is a better option than rejecting programs using those unions under
18988 // ARC.
18989 FD->addAttr(UnavailableAttr::CreateImplicit(
18990 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
18991 FD->getLocation()));
18992 } else if (getLangOpts().ObjC &&
18993 getLangOpts().getGC() != LangOptions::NonGC && Record &&
18994 !Record->hasObjectMember()) {
18995 if (FD->getType()->isObjCObjectPointerType() ||
18996 FD->getType().isObjCGCStrong())
18997 Record->setHasObjectMember(true);
18998 else if (Context.getAsArrayType(FD->getType())) {
18999 QualType BaseType = Context.getBaseElementType(FD->getType());
19000 if (BaseType->isRecordType() &&
19001 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
19002 Record->setHasObjectMember(true);
19003 else if (BaseType->isObjCObjectPointerType() ||
19004 BaseType.isObjCGCStrong())
19005 Record->setHasObjectMember(true);
19006 }
19007 }
19008
19009 if (Record && !getLangOpts().CPlusPlus &&
19010 !shouldIgnoreForRecordTriviality(FD)) {
19011 QualType FT = FD->getType();
19013 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
19015 Record->isUnion())
19016 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
19017 }
19020 Record->setNonTrivialToPrimitiveCopy(true);
19021 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
19022 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
19023 }
19024 if (FT.isDestructedType()) {
19025 Record->setNonTrivialToPrimitiveDestroy(true);
19026 Record->setParamDestroyedInCallee(true);
19027 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
19028 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
19029 }
19030
19031 if (const auto *RT = FT->getAs<RecordType>()) {
19032 if (RT->getDecl()->getArgPassingRestrictions() ==
19034 Record->setArgPassingRestrictions(
19037 Record->setArgPassingRestrictions(
19039 }
19040
19041 if (Record && FD->getType().isVolatileQualified())
19042 Record->setHasVolatileMember(true);
19043 // Keep track of the number of named members.
19044 if (FD->getIdentifier())
19045 ++NumNamedMembers;
19046 }
19047
19048 // Okay, we successfully defined 'Record'.
19049 if (Record) {
19050 bool Completed = false;
19051 if (S) {
19052 Scope *Parent = S->getParent();
19053 if (Parent && Parent->isTypeAliasScope() &&
19054 Parent->isTemplateParamScope())
19055 Record->setInvalidDecl();
19056 }
19057
19058 if (CXXRecord) {
19059 if (!CXXRecord->isInvalidDecl()) {
19060 // Set access bits correctly on the directly-declared conversions.
19062 I = CXXRecord->conversion_begin(),
19063 E = CXXRecord->conversion_end(); I != E; ++I)
19064 I.setAccess((*I)->getAccess());
19065 }
19066
19067 // Add any implicitly-declared members to this class.
19069
19070 if (!CXXRecord->isDependentType()) {
19071 if (!CXXRecord->isInvalidDecl()) {
19072 // If we have virtual base classes, we may end up finding multiple
19073 // final overriders for a given virtual function. Check for this
19074 // problem now.
19075 if (CXXRecord->getNumVBases()) {
19076 CXXFinalOverriderMap FinalOverriders;
19077 CXXRecord->getFinalOverriders(FinalOverriders);
19078
19079 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
19080 MEnd = FinalOverriders.end();
19081 M != MEnd; ++M) {
19082 for (OverridingMethods::iterator SO = M->second.begin(),
19083 SOEnd = M->second.end();
19084 SO != SOEnd; ++SO) {
19085 assert(SO->second.size() > 0 &&
19086 "Virtual function without overriding functions?");
19087 if (SO->second.size() == 1)
19088 continue;
19089
19090 // C++ [class.virtual]p2:
19091 // In a derived class, if a virtual member function of a base
19092 // class subobject has more than one final overrider the
19093 // program is ill-formed.
19094 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
19095 << (const NamedDecl *)M->first << Record;
19096 Diag(M->first->getLocation(),
19097 diag::note_overridden_virtual_function);
19099 OM = SO->second.begin(),
19100 OMEnd = SO->second.end();
19101 OM != OMEnd; ++OM)
19102 Diag(OM->Method->getLocation(), diag::note_final_overrider)
19103 << (const NamedDecl *)M->first << OM->Method->getParent();
19104
19105 Record->setInvalidDecl();
19106 }
19107 }
19108 CXXRecord->completeDefinition(&FinalOverriders);
19109 Completed = true;
19110 }
19111 }
19112 ComputeSelectedDestructor(*this, CXXRecord);
19114 }
19115 }
19116
19117 if (!Completed)
19118 Record->completeDefinition();
19119
19120 // Handle attributes before checking the layout.
19122
19123 // Check to see if a FieldDecl is a pointer to a function.
19124 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19125 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19126 if (!FD) {
19127 // Check whether this is a forward declaration that was inserted by
19128 // Clang. This happens when a non-forward declared / defined type is
19129 // used, e.g.:
19130 //
19131 // struct foo {
19132 // struct bar *(*f)();
19133 // struct bar *(*g)();
19134 // };
19135 //
19136 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19137 // incomplete definition.
19138 if (const auto *TD = dyn_cast<TagDecl>(D))
19139 return !TD->isCompleteDefinition();
19140 return false;
19141 }
19142 QualType FieldType = FD->getType().getDesugaredType(Context);
19143 if (isa<PointerType>(FieldType)) {
19144 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19145 return PointeeType.getDesugaredType(Context)->isFunctionType();
19146 }
19147 return false;
19148 };
19149
19150 // Maybe randomize the record's decls. We automatically randomize a record
19151 // of function pointers, unless it has the "no_randomize_layout" attribute.
19152 if (!getLangOpts().CPlusPlus &&
19153 (Record->hasAttr<RandomizeLayoutAttr>() ||
19154 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
19155 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
19156 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
19157 !Record->isRandomized()) {
19158 SmallVector<Decl *, 32> NewDeclOrdering;
19160 NewDeclOrdering))
19161 Record->reorderDecls(NewDeclOrdering);
19162 }
19163
19164 // We may have deferred checking for a deleted destructor. Check now.
19165 if (CXXRecord) {
19166 auto *Dtor = CXXRecord->getDestructor();
19167 if (Dtor && Dtor->isImplicit() &&
19169 CXXRecord->setImplicitDestructorIsDeleted();
19170 SetDeclDeleted(Dtor, CXXRecord->getLocation());
19171 }
19172 }
19173
19174 if (Record->hasAttrs()) {
19176
19177 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
19178 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
19179 IA->getRange(), IA->getBestCase(),
19180 IA->getInheritanceModel());
19181 }
19182
19183 // Check if the structure/union declaration is a type that can have zero
19184 // size in C. For C this is a language extension, for C++ it may cause
19185 // compatibility problems.
19186 bool CheckForZeroSize;
19187 if (!getLangOpts().CPlusPlus) {
19188 CheckForZeroSize = true;
19189 } else {
19190 // For C++ filter out types that cannot be referenced in C code.
19191 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
19192 CheckForZeroSize =
19193 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
19194 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
19195 CXXRecord->isCLike();
19196 }
19197 if (CheckForZeroSize) {
19198 bool ZeroSize = true;
19199 bool IsEmpty = true;
19200 unsigned NonBitFields = 0;
19201 for (RecordDecl::field_iterator I = Record->field_begin(),
19202 E = Record->field_end();
19203 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
19204 IsEmpty = false;
19205 if (I->isUnnamedBitField()) {
19206 if (!I->isZeroLengthBitField(Context))
19207 ZeroSize = false;
19208 } else {
19209 ++NonBitFields;
19210 QualType FieldType = I->getType();
19211 if (FieldType->isIncompleteType() ||
19212 !Context.getTypeSizeInChars(FieldType).isZero())
19213 ZeroSize = false;
19214 }
19215 }
19216
19217 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
19218 // allowed in C++, but warn if its declaration is inside
19219 // extern "C" block.
19220 if (ZeroSize) {
19221 Diag(RecLoc, getLangOpts().CPlusPlus ?
19222 diag::warn_zero_size_struct_union_in_extern_c :
19223 diag::warn_zero_size_struct_union_compat)
19224 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
19225 }
19226
19227 // Structs without named members are extension in C (C99 6.7.2.1p7),
19228 // but are accepted by GCC.
19229 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
19230 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
19231 diag::ext_no_named_members_in_struct_union)
19232 << Record->isUnion();
19233 }
19234 }
19235 } else {
19236 ObjCIvarDecl **ClsFields =
19237 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
19238 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
19239 ID->setEndOfDefinitionLoc(RBrac);
19240 // Add ivar's to class's DeclContext.
19241 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19242 ClsFields[i]->setLexicalDeclContext(ID);
19243 ID->addDecl(ClsFields[i]);
19244 }
19245 // Must enforce the rule that ivars in the base classes may not be
19246 // duplicates.
19247 if (ID->getSuperClass())
19248 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
19249 } else if (ObjCImplementationDecl *IMPDecl =
19250 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
19251 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
19252 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
19253 // Ivar declared in @implementation never belongs to the implementation.
19254 // Only it is in implementation's lexical context.
19255 ClsFields[I]->setLexicalDeclContext(IMPDecl);
19256 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
19257 RBrac);
19258 IMPDecl->setIvarLBraceLoc(LBrac);
19259 IMPDecl->setIvarRBraceLoc(RBrac);
19260 } else if (ObjCCategoryDecl *CDecl =
19261 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
19262 // case of ivars in class extension; all other cases have been
19263 // reported as errors elsewhere.
19264 // FIXME. Class extension does not have a LocEnd field.
19265 // CDecl->setLocEnd(RBrac);
19266 // Add ivar's to class extension's DeclContext.
19267 // Diagnose redeclaration of private ivars.
19268 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
19269 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
19270 if (IDecl) {
19271 if (const ObjCIvarDecl *ClsIvar =
19272 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
19273 Diag(ClsFields[i]->getLocation(),
19274 diag::err_duplicate_ivar_declaration);
19275 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
19276 continue;
19277 }
19278 for (const auto *Ext : IDecl->known_extensions()) {
19279 if (const ObjCIvarDecl *ClsExtIvar
19280 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
19281 Diag(ClsFields[i]->getLocation(),
19282 diag::err_duplicate_ivar_declaration);
19283 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
19284 continue;
19285 }
19286 }
19287 }
19288 ClsFields[i]->setLexicalDeclContext(CDecl);
19289 CDecl->addDecl(ClsFields[i]);
19290 }
19291 CDecl->setIvarLBraceLoc(LBrac);
19292 CDecl->setIvarRBraceLoc(RBrac);
19293 }
19294 }
19296}
19297
19298/// Determine whether the given integral value is representable within
19299/// the given type T.
19301 llvm::APSInt &Value,
19302 QualType T) {
19303 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
19304 "Integral type required!");
19305 unsigned BitWidth = Context.getIntWidth(T);
19306
19307 if (Value.isUnsigned() || Value.isNonNegative()) {
19309 --BitWidth;
19310 return Value.getActiveBits() <= BitWidth;
19311 }
19312 return Value.getSignificantBits() <= BitWidth;
19313}
19314
19315// Given an integral type, return the next larger integral type
19316// (or a NULL type of no such type exists).
19318 // FIXME: Int128/UInt128 support, which also needs to be introduced into
19319 // enum checking below.
19320 assert((T->isIntegralType(Context) ||
19321 T->isEnumeralType()) && "Integral type required!");
19322 const unsigned NumTypes = 4;
19323 QualType SignedIntegralTypes[NumTypes] = {
19324 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
19325 };
19326 QualType UnsignedIntegralTypes[NumTypes] = {
19327 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
19328 Context.UnsignedLongLongTy
19329 };
19330
19331 unsigned BitWidth = Context.getTypeSize(T);
19332 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
19333 : UnsignedIntegralTypes;
19334 for (unsigned I = 0; I != NumTypes; ++I)
19335 if (Context.getTypeSize(Types[I]) > BitWidth)
19336 return Types[I];
19337
19338 return QualType();
19339}
19340
19342 EnumConstantDecl *LastEnumConst,
19343 SourceLocation IdLoc,
19345 Expr *Val) {
19346 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19347 llvm::APSInt EnumVal(IntWidth);
19348 QualType EltTy;
19349
19351 Val = nullptr;
19352
19353 if (Val)
19354 Val = DefaultLvalueConversion(Val).get();
19355
19356 if (Val) {
19357 if (Enum->isDependentType() || Val->isTypeDependent() ||
19358 Val->containsErrors())
19359 EltTy = Context.DependentTy;
19360 else {
19361 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
19362 // underlying type, but do allow it in all other contexts.
19363 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
19364 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
19365 // constant-expression in the enumerator-definition shall be a converted
19366 // constant expression of the underlying type.
19367 EltTy = Enum->getIntegerType();
19368 ExprResult Converted =
19369 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
19371 if (Converted.isInvalid())
19372 Val = nullptr;
19373 else
19374 Val = Converted.get();
19375 } else if (!Val->isValueDependent() &&
19376 !(Val =
19378 .get())) {
19379 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
19380 } else {
19381 if (Enum->isComplete()) {
19382 EltTy = Enum->getIntegerType();
19383
19384 // In Obj-C and Microsoft mode, require the enumeration value to be
19385 // representable in the underlying type of the enumeration. In C++11,
19386 // we perform a non-narrowing conversion as part of converted constant
19387 // expression checking.
19388 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19390 .getTriple()
19391 .isWindowsMSVCEnvironment()) {
19392 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
19393 } else {
19394 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
19395 }
19396 }
19397
19398 // Cast to the underlying type.
19399 Val = ImpCastExprToType(Val, EltTy,
19400 EltTy->isBooleanType() ? CK_IntegralToBoolean
19401 : CK_IntegralCast)
19402 .get();
19403 } else if (getLangOpts().CPlusPlus) {
19404 // C++11 [dcl.enum]p5:
19405 // If the underlying type is not fixed, the type of each enumerator
19406 // is the type of its initializing value:
19407 // - If an initializer is specified for an enumerator, the
19408 // initializing value has the same type as the expression.
19409 EltTy = Val->getType();
19410 } else {
19411 // C99 6.7.2.2p2:
19412 // The expression that defines the value of an enumeration constant
19413 // shall be an integer constant expression that has a value
19414 // representable as an int.
19415
19416 // Complain if the value is not representable in an int.
19418 Diag(IdLoc, diag::ext_enum_value_not_int)
19419 << toString(EnumVal, 10) << Val->getSourceRange()
19420 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
19421 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
19422 // Force the type of the expression to 'int'.
19423 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
19424 }
19425 EltTy = Val->getType();
19426 }
19427 }
19428 }
19429 }
19430
19431 if (!Val) {
19432 if (Enum->isDependentType())
19433 EltTy = Context.DependentTy;
19434 else if (!LastEnumConst) {
19435 // C++0x [dcl.enum]p5:
19436 // If the underlying type is not fixed, the type of each enumerator
19437 // is the type of its initializing value:
19438 // - If no initializer is specified for the first enumerator, the
19439 // initializing value has an unspecified integral type.
19440 //
19441 // GCC uses 'int' for its unspecified integral type, as does
19442 // C99 6.7.2.2p3.
19443 if (Enum->isFixed()) {
19444 EltTy = Enum->getIntegerType();
19445 }
19446 else {
19447 EltTy = Context.IntTy;
19448 }
19449 } else {
19450 // Assign the last value + 1.
19451 EnumVal = LastEnumConst->getInitVal();
19452 ++EnumVal;
19453 EltTy = LastEnumConst->getType();
19454
19455 // Check for overflow on increment.
19456 if (EnumVal < LastEnumConst->getInitVal()) {
19457 // C++0x [dcl.enum]p5:
19458 // If the underlying type is not fixed, the type of each enumerator
19459 // is the type of its initializing value:
19460 //
19461 // - Otherwise the type of the initializing value is the same as
19462 // the type of the initializing value of the preceding enumerator
19463 // unless the incremented value is not representable in that type,
19464 // in which case the type is an unspecified integral type
19465 // sufficient to contain the incremented value. If no such type
19466 // exists, the program is ill-formed.
19468 if (T.isNull() || Enum->isFixed()) {
19469 // There is no integral type larger enough to represent this
19470 // value. Complain, then allow the value to wrap around.
19471 EnumVal = LastEnumConst->getInitVal();
19472 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
19473 ++EnumVal;
19474 if (Enum->isFixed())
19475 // When the underlying type is fixed, this is ill-formed.
19476 Diag(IdLoc, diag::err_enumerator_wrapped)
19477 << toString(EnumVal, 10)
19478 << EltTy;
19479 else
19480 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
19481 << toString(EnumVal, 10);
19482 } else {
19483 EltTy = T;
19484 }
19485
19486 // Retrieve the last enumerator's value, extent that type to the
19487 // type that is supposed to be large enough to represent the incremented
19488 // value, then increment.
19489 EnumVal = LastEnumConst->getInitVal();
19490 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19491 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
19492 ++EnumVal;
19493
19494 // If we're not in C++, diagnose the overflow of enumerator values,
19495 // which in C99 means that the enumerator value is not representable in
19496 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
19497 // permits enumerator values that are representable in some larger
19498 // integral type.
19499 if (!getLangOpts().CPlusPlus && !T.isNull())
19500 Diag(IdLoc, diag::warn_enum_value_overflow);
19501 } else if (!getLangOpts().CPlusPlus &&
19502 !EltTy->isDependentType() &&
19503 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
19504 // Enforce C99 6.7.2.2p2 even when we compute the next value.
19505 Diag(IdLoc, diag::ext_enum_value_not_int)
19506 << toString(EnumVal, 10) << 1;
19507 }
19508 }
19509 }
19510
19511 if (!EltTy->isDependentType()) {
19512 // Make the enumerator value match the signedness and size of the
19513 // enumerator's type.
19514 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
19515 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
19516 }
19517
19518 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
19519 Val, EnumVal);
19520}
19521
19523 SourceLocation IILoc) {
19524 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
19526 return SkipBodyInfo();
19527
19528 // We have an anonymous enum definition. Look up the first enumerator to
19529 // determine if we should merge the definition with an existing one and
19530 // skip the body.
19531 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
19533 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
19534 if (!PrevECD)
19535 return SkipBodyInfo();
19536
19537 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
19538 NamedDecl *Hidden;
19539 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
19540 SkipBodyInfo Skip;
19541 Skip.Previous = Hidden;
19542 return Skip;
19543 }
19544
19545 return SkipBodyInfo();
19546}
19547
19548Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
19550 const ParsedAttributesView &Attrs,
19551 SourceLocation EqualLoc, Expr *Val) {
19552 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
19553 EnumConstantDecl *LastEnumConst =
19554 cast_or_null<EnumConstantDecl>(lastEnumConst);
19555
19556 // The scope passed in may not be a decl scope. Zip up the scope tree until
19557 // we find one that is.
19558 S = getNonFieldDeclScope(S);
19559
19560 // Verify that there isn't already something declared with this name in this
19561 // scope.
19562 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
19563 RedeclarationKind::ForVisibleRedeclaration);
19564 LookupName(R, S);
19565 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
19566
19567 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19568 // Maybe we will complain about the shadowed template parameter.
19569 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
19570 // Just pretend that we didn't see the previous declaration.
19571 PrevDecl = nullptr;
19572 }
19573
19574 // C++ [class.mem]p15:
19575 // If T is the name of a class, then each of the following shall have a name
19576 // different from T:
19577 // - every enumerator of every member of class T that is an unscoped
19578 // enumerated type
19579 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
19581 DeclarationNameInfo(Id, IdLoc));
19582
19583 EnumConstantDecl *New =
19584 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
19585 if (!New)
19586 return nullptr;
19587
19588 if (PrevDecl) {
19589 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
19590 // Check for other kinds of shadowing not already handled.
19591 CheckShadow(New, PrevDecl, R);
19592 }
19593
19594 // When in C++, we may get a TagDecl with the same name; in this case the
19595 // enum constant will 'hide' the tag.
19596 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
19597 "Received TagDecl when not in C++!");
19598 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
19599 if (isa<EnumConstantDecl>(PrevDecl))
19600 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
19601 else
19602 Diag(IdLoc, diag::err_redefinition) << Id;
19603 notePreviousDefinition(PrevDecl, IdLoc);
19604 return nullptr;
19605 }
19606 }
19607
19608 // Process attributes.
19609 ProcessDeclAttributeList(S, New, Attrs);
19610 AddPragmaAttributes(S, New);
19611 ProcessAPINotes(New);
19612
19613 // Register this decl in the current scope stack.
19614 New->setAccess(TheEnumDecl->getAccess());
19615 PushOnScopeChains(New, S);
19616
19618
19619 return New;
19620}
19621
19622// Returns true when the enum initial expression does not trigger the
19623// duplicate enum warning. A few common cases are exempted as follows:
19624// Element2 = Element1
19625// Element2 = Element1 + 1
19626// Element2 = Element1 - 1
19627// Where Element2 and Element1 are from the same enum.
19629 Expr *InitExpr = ECD->getInitExpr();
19630 if (!InitExpr)
19631 return true;
19632 InitExpr = InitExpr->IgnoreImpCasts();
19633
19634 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
19635 if (!BO->isAdditiveOp())
19636 return true;
19637 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
19638 if (!IL)
19639 return true;
19640 if (IL->getValue() != 1)
19641 return true;
19642
19643 InitExpr = BO->getLHS();
19644 }
19645
19646 // This checks if the elements are from the same enum.
19647 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
19648 if (!DRE)
19649 return true;
19650
19651 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
19652 if (!EnumConstant)
19653 return true;
19654
19655 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
19656 Enum)
19657 return true;
19658
19659 return false;
19660}
19661
19662// Emits a warning when an element is implicitly set a value that
19663// a previous element has already been set to.
19666 // Avoid anonymous enums
19667 if (!Enum->getIdentifier())
19668 return;
19669
19670 // Only check for small enums.
19671 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
19672 return;
19673
19674 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
19675 return;
19676
19677 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
19678 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
19679
19680 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
19681
19682 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
19683 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
19684
19685 // Use int64_t as a key to avoid needing special handling for map keys.
19686 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
19687 llvm::APSInt Val = D->getInitVal();
19688 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
19689 };
19690
19691 DuplicatesVector DupVector;
19692 ValueToVectorMap EnumMap;
19693
19694 // Populate the EnumMap with all values represented by enum constants without
19695 // an initializer.
19696 for (auto *Element : Elements) {
19697 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
19698
19699 // Null EnumConstantDecl means a previous diagnostic has been emitted for
19700 // this constant. Skip this enum since it may be ill-formed.
19701 if (!ECD) {
19702 return;
19703 }
19704
19705 // Constants with initializers are handled in the next loop.
19706 if (ECD->getInitExpr())
19707 continue;
19708
19709 // Duplicate values are handled in the next loop.
19710 EnumMap.insert({EnumConstantToKey(ECD), ECD});
19711 }
19712
19713 if (EnumMap.size() == 0)
19714 return;
19715
19716 // Create vectors for any values that has duplicates.
19717 for (auto *Element : Elements) {
19718 // The last loop returned if any constant was null.
19719 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
19720 if (!ValidDuplicateEnum(ECD, Enum))
19721 continue;
19722
19723 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
19724 if (Iter == EnumMap.end())
19725 continue;
19726
19727 DeclOrVector& Entry = Iter->second;
19728 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
19729 // Ensure constants are different.
19730 if (D == ECD)
19731 continue;
19732
19733 // Create new vector and push values onto it.
19734 auto Vec = std::make_unique<ECDVector>();
19735 Vec->push_back(D);
19736 Vec->push_back(ECD);
19737
19738 // Update entry to point to the duplicates vector.
19739 Entry = Vec.get();
19740
19741 // Store the vector somewhere we can consult later for quick emission of
19742 // diagnostics.
19743 DupVector.emplace_back(std::move(Vec));
19744 continue;
19745 }
19746
19747 ECDVector *Vec = Entry.get<ECDVector*>();
19748 // Make sure constants are not added more than once.
19749 if (*Vec->begin() == ECD)
19750 continue;
19751
19752 Vec->push_back(ECD);
19753 }
19754
19755 // Emit diagnostics.
19756 for (const auto &Vec : DupVector) {
19757 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
19758
19759 // Emit warning for one enum constant.
19760 auto *FirstECD = Vec->front();
19761 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
19762 << FirstECD << toString(FirstECD->getInitVal(), 10)
19763 << FirstECD->getSourceRange();
19764
19765 // Emit one note for each of the remaining enum constants with
19766 // the same value.
19767 for (auto *ECD : llvm::drop_begin(*Vec))
19768 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
19769 << ECD << toString(ECD->getInitVal(), 10)
19770 << ECD->getSourceRange();
19771 }
19772}
19773
19774bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
19775 bool AllowMask) const {
19776 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
19777 assert(ED->isCompleteDefinition() && "expected enum definition");
19778
19779 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
19780 llvm::APInt &FlagBits = R.first->second;
19781
19782 if (R.second) {
19783 for (auto *E : ED->enumerators()) {
19784 const auto &EVal = E->getInitVal();
19785 // Only single-bit enumerators introduce new flag values.
19786 if (EVal.isPowerOf2())
19787 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
19788 }
19789 }
19790
19791 // A value is in a flag enum if either its bits are a subset of the enum's
19792 // flag bits (the first condition) or we are allowing masks and the same is
19793 // true of its complement (the second condition). When masks are allowed, we
19794 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
19795 //
19796 // While it's true that any value could be used as a mask, the assumption is
19797 // that a mask will have all of the insignificant bits set. Anything else is
19798 // likely a logic error.
19799 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
19800 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
19801}
19802
19804 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
19805 const ParsedAttributesView &Attrs) {
19806 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
19808
19809 ProcessDeclAttributeList(S, Enum, Attrs);
19811
19812 if (Enum->isDependentType()) {
19813 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19814 EnumConstantDecl *ECD =
19815 cast_or_null<EnumConstantDecl>(Elements[i]);
19816 if (!ECD) continue;
19817
19818 ECD->setType(EnumType);
19819 }
19820
19821 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
19822 return;
19823 }
19824
19825 // TODO: If the result value doesn't fit in an int, it must be a long or long
19826 // long value. ISO C does not support this, but GCC does as an extension,
19827 // emit a warning.
19828 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
19829 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
19830 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
19831
19832 // Verify that all the values are okay, compute the size of the values, and
19833 // reverse the list.
19834 unsigned NumNegativeBits = 0;
19835 unsigned NumPositiveBits = 0;
19836
19837 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
19838 EnumConstantDecl *ECD =
19839 cast_or_null<EnumConstantDecl>(Elements[i]);
19840 if (!ECD) continue; // Already issued a diagnostic.
19841
19842 const llvm::APSInt &InitVal = ECD->getInitVal();
19843
19844 // Keep track of the size of positive and negative values.
19845 if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
19846 // If the enumerator is zero that should still be counted as a positive
19847 // bit since we need a bit to store the value zero.
19848 unsigned ActiveBits = InitVal.getActiveBits();
19849 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
19850 } else {
19851 NumNegativeBits =
19852 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
19853 }
19854 }
19855
19856 // If we have an empty set of enumerators we still need one bit.
19857 // From [dcl.enum]p8
19858 // If the enumerator-list is empty, the values of the enumeration are as if
19859 // the enumeration had a single enumerator with value 0
19860 if (!NumPositiveBits && !NumNegativeBits)
19861 NumPositiveBits = 1;
19862
19863 // Figure out the type that should be used for this enum.
19864 QualType BestType;
19865 unsigned BestWidth;
19866
19867 // C++0x N3000 [conv.prom]p3:
19868 // An rvalue of an unscoped enumeration type whose underlying
19869 // type is not fixed can be converted to an rvalue of the first
19870 // of the following types that can represent all the values of
19871 // the enumeration: int, unsigned int, long int, unsigned long
19872 // int, long long int, or unsigned long long int.
19873 // C99 6.4.4.3p2:
19874 // An identifier declared as an enumeration constant has type int.
19875 // The C99 rule is modified by a gcc extension
19876 QualType BestPromotionType;
19877
19878 bool Packed = Enum->hasAttr<PackedAttr>();
19879 // -fshort-enums is the equivalent to specifying the packed attribute on all
19880 // enum definitions.
19881 if (LangOpts.ShortEnums)
19882 Packed = true;
19883
19884 // If the enum already has a type because it is fixed or dictated by the
19885 // target, promote that type instead of analyzing the enumerators.
19886 if (Enum->isComplete()) {
19887 BestType = Enum->getIntegerType();
19888 if (Context.isPromotableIntegerType(BestType))
19889 BestPromotionType = Context.getPromotedIntegerType(BestType);
19890 else
19891 BestPromotionType = BestType;
19892
19893 BestWidth = Context.getIntWidth(BestType);
19894 }
19895 else if (NumNegativeBits) {
19896 // If there is a negative value, figure out the smallest integer type (of
19897 // int/long/longlong) that fits.
19898 // If it's packed, check also if it fits a char or a short.
19899 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
19900 BestType = Context.SignedCharTy;
19901 BestWidth = CharWidth;
19902 } else if (Packed && NumNegativeBits <= ShortWidth &&
19903 NumPositiveBits < ShortWidth) {
19904 BestType = Context.ShortTy;
19905 BestWidth = ShortWidth;
19906 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
19907 BestType = Context.IntTy;
19908 BestWidth = IntWidth;
19909 } else {
19910 BestWidth = Context.getTargetInfo().getLongWidth();
19911
19912 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
19913 BestType = Context.LongTy;
19914 } else {
19915 BestWidth = Context.getTargetInfo().getLongLongWidth();
19916
19917 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
19918 Diag(Enum->getLocation(), diag::ext_enum_too_large);
19919 BestType = Context.LongLongTy;
19920 }
19921 }
19922 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
19923 } else {
19924 // If there is no negative value, figure out the smallest type that fits
19925 // all of the enumerator values.
19926 // If it's packed, check also if it fits a char or a short.
19927 if (Packed && NumPositiveBits <= CharWidth) {
19928 BestType = Context.UnsignedCharTy;
19929 BestPromotionType = Context.IntTy;
19930 BestWidth = CharWidth;
19931 } else if (Packed && NumPositiveBits <= ShortWidth) {
19932 BestType = Context.UnsignedShortTy;
19933 BestPromotionType = Context.IntTy;
19934 BestWidth = ShortWidth;
19935 } else if (NumPositiveBits <= IntWidth) {
19936 BestType = Context.UnsignedIntTy;
19937 BestWidth = IntWidth;
19938 BestPromotionType
19939 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19941 } else if (NumPositiveBits <=
19942 (BestWidth = Context.getTargetInfo().getLongWidth())) {
19943 BestType = Context.UnsignedLongTy;
19944 BestPromotionType
19945 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19947 } else {
19948 BestWidth = Context.getTargetInfo().getLongLongWidth();
19949 if (NumPositiveBits > BestWidth) {
19950 // This can happen with bit-precise integer types, but those are not
19951 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
19952 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
19953 // a 128-bit integer, we should consider doing the same.
19954 Diag(Enum->getLocation(), diag::ext_enum_too_large);
19955 }
19956 BestType = Context.UnsignedLongLongTy;
19957 BestPromotionType
19958 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
19960 }
19961 }
19962
19963 // Loop over all of the enumerator constants, changing their types to match
19964 // the type of the enum if needed.
19965 for (auto *D : Elements) {
19966 auto *ECD = cast_or_null<EnumConstantDecl>(D);
19967 if (!ECD) continue; // Already issued a diagnostic.
19968
19969 // Standard C says the enumerators have int type, but we allow, as an
19970 // extension, the enumerators to be larger than int size. If each
19971 // enumerator value fits in an int, type it as an int, otherwise type it the
19972 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
19973 // that X has type 'int', not 'unsigned'.
19974
19975 // Determine whether the value fits into an int.
19976 llvm::APSInt InitVal = ECD->getInitVal();
19977
19978 // If it fits into an integer type, force it. Otherwise force it to match
19979 // the enum decl type.
19980 QualType NewTy;
19981 unsigned NewWidth;
19982 bool NewSign;
19983 if (!getLangOpts().CPlusPlus &&
19984 !Enum->isFixed() &&
19986 NewTy = Context.IntTy;
19987 NewWidth = IntWidth;
19988 NewSign = true;
19989 } else if (ECD->getType() == BestType) {
19990 // Already the right type!
19991 if (getLangOpts().CPlusPlus)
19992 // C++ [dcl.enum]p4: Following the closing brace of an
19993 // enum-specifier, each enumerator has the type of its
19994 // enumeration.
19995 ECD->setType(EnumType);
19996 continue;
19997 } else {
19998 NewTy = BestType;
19999 NewWidth = BestWidth;
20000 NewSign = BestType->isSignedIntegerOrEnumerationType();
20001 }
20002
20003 // Adjust the APSInt value.
20004 InitVal = InitVal.extOrTrunc(NewWidth);
20005 InitVal.setIsSigned(NewSign);
20006 ECD->setInitVal(Context, InitVal);
20007
20008 // Adjust the Expr initializer and type.
20009 if (ECD->getInitExpr() &&
20010 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20011 ECD->setInitExpr(ImplicitCastExpr::Create(
20012 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20013 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20014 if (getLangOpts().CPlusPlus)
20015 // C++ [dcl.enum]p4: Following the closing brace of an
20016 // enum-specifier, each enumerator has the type of its
20017 // enumeration.
20018 ECD->setType(EnumType);
20019 else
20020 ECD->setType(NewTy);
20021 }
20022
20023 Enum->completeDefinition(BestType, BestPromotionType,
20024 NumPositiveBits, NumNegativeBits);
20025
20026 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
20027
20028 if (Enum->isClosedFlag()) {
20029 for (Decl *D : Elements) {
20030 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
20031 if (!ECD) continue; // Already issued a diagnostic.
20032
20033 llvm::APSInt InitVal = ECD->getInitVal();
20034 if (InitVal != 0 && !InitVal.isPowerOf2() &&
20035 !IsValueInFlagEnum(Enum, InitVal, true))
20036 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
20037 << ECD << Enum;
20038 }
20039 }
20040
20041 // Now that the enum type is defined, ensure it's not been underaligned.
20042 if (Enum->hasAttrs())
20044}
20045
20047 SourceLocation StartLoc,
20048 SourceLocation EndLoc) {
20049 StringLiteral *AsmString = cast<StringLiteral>(expr);
20050
20052 AsmString, StartLoc,
20053 EndLoc);
20054 CurContext->addDecl(New);
20055 return New;
20056}
20057
20059 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
20060 CurContext->addDecl(New);
20061 PushDeclContext(S, New);
20063 PushCompoundScope(false);
20064 return New;
20065}
20066
20068 D->setStmt(Statement);
20072}
20073
20075 IdentifierInfo* AliasName,
20076 SourceLocation PragmaLoc,
20077 SourceLocation NameLoc,
20078 SourceLocation AliasNameLoc) {
20079 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
20081 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
20083 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
20084 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
20085
20086 // If a declaration that:
20087 // 1) declares a function or a variable
20088 // 2) has external linkage
20089 // already exists, add a label attribute to it.
20090 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20091 if (isDeclExternC(PrevDecl))
20092 PrevDecl->addAttr(Attr);
20093 else
20094 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
20095 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
20096 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
20097 } else
20098 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
20099}
20100
20102 SourceLocation PragmaLoc,
20103 SourceLocation NameLoc) {
20104 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
20105
20106 if (PrevDecl) {
20107 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
20108 } else {
20109 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
20110 }
20111}
20112
20114 IdentifierInfo* AliasName,
20115 SourceLocation PragmaLoc,
20116 SourceLocation NameLoc,
20117 SourceLocation AliasNameLoc) {
20118 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
20120 WeakInfo W = WeakInfo(Name, NameLoc);
20121
20122 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
20123 if (!PrevDecl->hasAttr<AliasAttr>())
20124 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
20126 } else {
20127 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
20128 }
20129}
20130
20132 bool Final) {
20133 assert(FD && "Expected non-null FunctionDecl");
20134
20135 // SYCL functions can be template, so we check if they have appropriate
20136 // attribute prior to checking if it is a template.
20137 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
20139
20140 // Templates are emitted when they're instantiated.
20141 if (FD->isDependentContext())
20143
20144 // Check whether this function is an externally visible definition.
20145 auto IsEmittedForExternalSymbol = [this, FD]() {
20146 // We have to check the GVA linkage of the function's *definition* -- if we
20147 // only have a declaration, we don't know whether or not the function will
20148 // be emitted, because (say) the definition could include "inline".
20149 const FunctionDecl *Def = FD->getDefinition();
20150
20151 return Def && !isDiscardableGVALinkage(
20152 getASTContext().GetGVALinkageForFunction(Def));
20153 };
20154
20155 if (LangOpts.OpenMPIsTargetDevice) {
20156 // In OpenMP device mode we will not emit host only functions, or functions
20157 // we don't need due to their linkage.
20158 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20159 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20160 // DevTy may be changed later by
20161 // #pragma omp declare target to(*) device_type(*).
20162 // Therefore DevTy having no value does not imply host. The emission status
20163 // will be checked again at the end of compilation unit with Final = true.
20164 if (DevTy)
20165 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
20167 // If we have an explicit value for the device type, or we are in a target
20168 // declare context, we need to emit all extern and used symbols.
20169 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
20170 if (IsEmittedForExternalSymbol())
20172 // Device mode only emits what it must, if it wasn't tagged yet and needed,
20173 // we'll omit it.
20174 if (Final)
20176 } else if (LangOpts.OpenMP > 45) {
20177 // In OpenMP host compilation prior to 5.0 everything was an emitted host
20178 // function. In 5.0, no_host was introduced which might cause a function to
20179 // be omitted.
20180 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
20181 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
20182 if (DevTy)
20183 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
20185 }
20186
20187 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
20189
20190 if (LangOpts.CUDA) {
20191 // When compiling for device, host functions are never emitted. Similarly,
20192 // when compiling for host, device and global functions are never emitted.
20193 // (Technically, we do emit a host-side stub for global functions, but this
20194 // doesn't count for our purposes here.)
20196 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
20198 if (!LangOpts.CUDAIsDevice &&
20201
20202 if (IsEmittedForExternalSymbol())
20204 }
20205
20206 // Otherwise, the function is known-emitted if it's in our set of
20207 // known-emitted functions.
20209}
20210
20212 // Host-side references to a __global__ function refer to the stub, so the
20213 // function itself is never emitted and therefore should not be marked.
20214 // If we have host fn calls kernel fn calls host+device, the HD function
20215 // does not get instantiated on the host. We model this by omitting at the
20216 // call to the kernel from the callgraph. This ensures that, when compiling
20217 // for host, only HD functions actually called from the host get marked as
20218 // known-emitted.
20219 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
20221}
20222
20224 const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc,
20225 SourceLocation OldLoc) {
20226 for (const FunctionEffectSet::Conflict &Conflict : Errs) {
20227 Diag(NewLoc, diag::warn_conflicting_func_effects)
20228 << Conflict.Kept.description() << Conflict.Rejected.description();
20229 Diag(OldLoc, diag::note_previous_declaration);
20230 }
20231}
20232
20234 const FunctionEffectsRef &FX, const FunctionEffectWithCondition &NewEC,
20235 SourceLocation NewAttrLoc) {
20236 // If the new effect has a condition, we can't detect conflicts until the
20237 // condition is resolved.
20238 if (NewEC.Cond.getCondition() != nullptr)
20239 return false;
20240
20241 // Diagnose the new attribute as incompatible with a previous one.
20242 auto Incompatible = [&](const FunctionEffectWithCondition &PrevEC) {
20243 Diag(NewAttrLoc, diag::err_attributes_are_not_compatible)
20244 << ("'" + NewEC.description() + "'")
20245 << ("'" + PrevEC.description() + "'") << false;
20246 // We don't necessarily have the location of the previous attribute,
20247 // so no note.
20248 return true;
20249 };
20250
20251 // Compare against previous attributes.
20252 FunctionEffect::Kind NewKind = NewEC.Effect.kind();
20253
20254 for (const FunctionEffectWithCondition &PrevEC : FX) {
20255 // Again, can't check yet when the effect is conditional.
20256 if (PrevEC.Cond.getCondition() != nullptr)
20257 continue;
20258
20259 FunctionEffect::Kind PrevKind = PrevEC.Effect.kind();
20260 // Note that we allow PrevKind == NewKind; it's redundant and ignored.
20261
20262 if (PrevEC.Effect.oppositeKind() == NewKind)
20263 return Incompatible(PrevEC);
20264
20265 // A new allocating is incompatible with a previous nonblocking.
20266 if (PrevKind == FunctionEffect::Kind::NonBlocking &&
20268 return Incompatible(PrevEC);
20269
20270 // A new nonblocking is incompatible with a previous allocating.
20271 if (PrevKind == FunctionEffect::Kind::Allocating &&
20273 return Incompatible(PrevEC);
20274 }
20275
20276 return false;
20277}
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:83
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::@1651::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:2211
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines helper utilities for supporting the HLSL runtime environment.
unsigned Iter
Definition: HTMLLogger.cpp:154
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:58
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:1143
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:15711
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6806
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:152
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15226
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:11251
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:207
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3328
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:3495
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:794
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6504
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:1469
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:6542
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2268
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:9090
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:3442
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2782
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:8098
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:9439
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3226
void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
Definition: SemaDecl.cpp:7324
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
Definition: SemaDecl.cpp:8466
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:11655
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:2671
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4430
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
Definition: SemaDecl.cpp:11745
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:15210
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
Definition: SemaDecl.cpp:11371
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:2035
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
Definition: SemaDecl.cpp:14858
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:560
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
Definition: SemaDecl.cpp:11260
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:7093
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:19300
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:19664
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
Definition: SemaDecl.cpp:4974
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:2910
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:16742
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3477
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6853
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:5906
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:4844
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:9126
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:9622
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
Definition: SemaDecl.cpp:15740
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3384
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8435
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2640
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:9311
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:3025
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:8123
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:16902
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:5257
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:8352
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
Definition: SemaDecl.cpp:1911
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
Definition: SemaDecl.cpp:9633
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:5333
OpenCLParamType
Definition: SemaDecl.cpp:9302
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:9306
@ ValidKernelParam
Definition: SemaDecl.cpp:9303
@ InvalidKernelParam
Definition: SemaDecl.cpp:9307
@ RecordKernelParam
Definition: SemaDecl.cpp:9308
@ PtrKernelParam
Definition: SemaDecl.cpp:9305
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:9304
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:6015
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:18657
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:580
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:18591
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:7138
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5417
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11176
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:9613
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
Definition: SemaDecl.cpp:3289
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3421
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:16726
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
Definition: SemaDecl.cpp:2162
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4327
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:8938
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
Definition: SemaDecl.cpp:5941
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:18684
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:809
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:7165
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:8087
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:8094
@ SDK_Field
Definition: SemaDecl.cpp:8091
@ SDK_Global
Definition: SemaDecl.cpp:8089
@ SDK_Local
Definition: SemaDecl.cpp:8088
@ SDK_Typedef
Definition: SemaDecl.cpp:8092
@ SDK_StaticMember
Definition: SemaDecl.cpp:8090
@ SDK_Using
Definition: SemaDecl.cpp:8093
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4790
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3405
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:9333
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5431
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:12351
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:7216
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
Definition: SemaDecl.cpp:1780
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
Definition: SemaDecl.cpp:18750
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11005
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
Definition: SemaDecl.cpp:1769
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2884
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:6426
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:14666
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7312
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:5888
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1822
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:10955
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6767
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5396
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:249
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:11402
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:8114
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:11222
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:6944
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:11020
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:2395
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:19628
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:19317
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:7124
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2659
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:10862
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:11274
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1796
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:16939
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
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
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
Definition: SemaDecl.cpp:15698
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:15700
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:186
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
SourceManager & getSourceManager()
Definition: ASTContext.h:720
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1100
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2822
QualType getParenType(QualType NamedType) const
CanQualType LongTy
Definition: ASTContext.h:1127
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
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:663
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2136
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:1922
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2625
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2641
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:2026
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:1948
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:2004
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:2828
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:1146
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:1634
IdentifierTable & Idents
Definition: ASTContext.h:659
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:661
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:796
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:498
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:2124
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:2038
CanQualType UnsignedLongTy
Definition: ASTContext.h:1128
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:2921
CanQualType CharTy
Definition: ASTContext.h:1120
CanQualType IntTy
Definition: ASTContext.h:1127
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:2207
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1127
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:712
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:2114
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2672
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:2391
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:1118
CanQualType UnsignedCharTy
Definition: ASTContext.h:1128
CanQualType UnsignedIntTy
Definition: ASTContext.h:1128
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
CanQualType UnknownAnyTy
Definition: ASTContext.h:1147
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1129
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1128
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:1612
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1464
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:2825
CanQualType ShortTy
Definition: ASTContext.h:1127
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1935
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:778
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:2230
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:2014
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:1127
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:2293
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2299
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2296
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2305
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2302
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:2422
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:3320
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1563
Expr * getSizeExpr() const
Definition: TypeLoc.h:1583
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1591
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1571
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3540
QualType getElementType() const
Definition: Type.h:3552
Attr - This represents one attribute.
Definition: Attr.h:42
attr::Kind getKind() const
Definition: Attr.h:88
bool isInherited() const
Definition: Attr.h:97
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition: Attr.h:102
SourceLocation getLocation() const
Definition: Attr.h:95
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:639
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:735
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:5991
QualType getModifiedType() const
Definition: Type.h:6013
bool isCallingConv() const
Definition: Type.cpp:4140
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:6046
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6368
AutoTypeKeyword getKeyword() const
Definition: Type.h:6399
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4265
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4467
bool doesNotEscape() const
Definition: Decl.h:4618
This class is used for builtin types like 'int'.
Definition: Type.h:3000
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:212
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
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:222
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:137
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:284
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:247
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:202
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:111
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:167
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:207
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:182
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:160
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:202
bool isConstWithoutExceptions(unsigned ID) const
Definition: Builtins.h:251
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:174
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:116
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:127
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:122
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:2535
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:2725
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
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:2892
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)
Definition: DeclCXX.cpp:2159
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
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:2859
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:2060
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:2457
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2511
bool isVirtual() const
Definition: DeclCXX.h:2115
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2578
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2490
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:2276
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
bool isConst() const
Definition: DeclCXX.h:2112
bool isStatic() const
Definition: DeclCXX.cpp:2188
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2468
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2156
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:1335
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1241
base_class_iterator bases_end()
Definition: DeclCXX.h:628
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1367
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1548
base_class_range bases()
Definition: DeclCXX.h:619
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1377
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
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:132
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1933
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:626
capture_const_range captures() const
Definition: DeclCXX.h:1101
bool hasDefinition() const
Definition: DeclCXX.h:571
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1900
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1063
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1904
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1289
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
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:126
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:152
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:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
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:4203
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:178
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:218
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3634
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:1358
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2359
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2079
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2208
bool isFileContext() const
Definition: DeclBase.h:2150
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2019
bool isObjCContainer() const
Definition: DeclBase.h:2118
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1309
bool isClosure() const
Definition: DeclBase.h:2112
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2095
bool isNamespace() const
Definition: DeclBase.h:2168
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1828
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1276
bool isTranslationUnit() const
Definition: DeclBase.h:2155
bool isRecord() const
Definition: DeclBase.h:2159
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1964
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1661
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1742
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1611
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1982
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1399
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2339
bool isFunctionOrMethod() const
Definition: DeclBase.h:2131
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1260
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1379
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2072
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1390
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:645
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:826
static const TST TST_typeof_unqualType
Definition: DeclSpec.h:309
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:592
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:642
bool isNoreturnSpecified() const
Definition: DeclSpec.h:658
TST getTypeSpecType() const
Definition: DeclSpec.h:534
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:507
SCS getStorageClassSpec() const
Definition: DeclSpec.h:498
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:857
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:572
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:571
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:706
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:613
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:705
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:659
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:502
static const TST TST_union
Definition: DeclSpec.h:302
SCS
storage-class-specifier
Definition: DeclSpec.h:251
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:651
static const TST TST_int
Definition: DeclSpec.h:285
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:827
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1498
ParsedType getRepAsType() const
Definition: DeclSpec.h:544
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:785
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:499
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:870
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:623
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:614
Expr * getRepAsExpr() const
Definition: DeclSpec.h:552
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:466
bool isInlineSpecified() const
Definition: DeclSpec.h:634
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:615
static const TST TST_typeof_unqualExpr
Definition: DeclSpec.h:310
static const TST TST_class
Definition: DeclSpec.h:305
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:559
static const TST TST_atomic
Definition: DeclSpec.h:321
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:508
Decl * getRepAsDecl() const
Definition: DeclSpec.h:548
static const TST TST_unspecified
Definition: DeclSpec.h:278
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:617
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:646
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:833
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:579
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:789
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:267
static const TST TST_error
Definition: DeclSpec.h:325
bool isTypeSpecOwned() const
Definition: DeclSpec.h:538
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:637
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:618
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:616
FriendSpecified isFriendSpecified() const
Definition: DeclSpec.h:818
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:648
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:834
static const TST TST_typeofType
Definition: DeclSpec.h:307
static const TST TST_auto
Definition: DeclSpec.h:318
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:829
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:1040
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1055
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:317
bool isInStdNamespace() const
Definition: DeclBase.cpp:425
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1205
T * getAttr() const
Definition: DeclBase.h:579
bool hasAttrs() const
Definition: DeclBase.h:524
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
void addAttr(Attr *A)
Definition: DeclBase.cpp:1014
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:526
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:754
bool isInNamedModule() const
Whether this declaration comes from a named module.
Definition: DeclBase.cpp:1148
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1130
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:638
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:872
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1198
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1196
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1197
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:284
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:1113
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:577
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:825
bool isFromExplicitGlobalModule() const
Whether this declaration comes from explicit global module.
Definition: DeclBase.cpp:1144
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
void dropAttrs()
Definition: DeclBase.cpp:1007
@ 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:1159
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2756
bool isInvalidDecl() const
Definition: DeclBase.h:594
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1148
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:812
void setImplicit(bool I=true)
Definition: DeclBase.h:600
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:614
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:552
DeclContext * getDeclContext()
Definition: DeclBase.h:454
attr_range attrs() const
Definition: DeclBase.h:541
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
void dropAttr()
Definition: DeclBase.h:562
AttrVec & getAttrs()
Definition: DeclBase.h:530
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:358
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:897
bool hasAttr() const
Definition: DeclBase.h:583
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1214
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:362
Kind getKind() const
Definition: DeclBase.h:448
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:433
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:731
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:789
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:774
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2032
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2072
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1970
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:819
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:766
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1982
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:807
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2016
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2398
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2047
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2683
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2339
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2394
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2686
A decomposition declaration.
Definition: DeclCXX.h:4166
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3339
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1789
SourceRange getSourceRange() const
Definition: DeclSpec.h:1836
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1834
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6334
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:6355
bool isDeduced() const
Definition: Type.h:6356
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:931
Expr * getCondition() const
Definition: Type.h:4781
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3270
llvm::APSInt getInitVal() const
Definition: Decl.h:3290
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5441
const Expr * getInitExpr() const
Definition: Decl.h:3288
Represents an enum.
Definition: Decl.h:3840
enumerator_range enumerators() const
Definition: Decl.h:3973
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4045
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4009
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:4012
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4059
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4840
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4885
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4054
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4860
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:3995
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4000
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5962
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
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:3070
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:3066
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3050
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:919
void applyChanges(FPOptionsOverride FPO)
Definition: LangOptions.h:1032
bool isFPConstrained() const
Definition: LangOptions.h:847
FPOptionsOverride getChangesFrom(const FPOptions &Base) const
Return difference with the given option set.
Definition: LangOptions.h:1026
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3121
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4548
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:4585
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3243
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:4533
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5574
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
Represents a function declaration or definition.
Definition: Decl.h:1932
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2562
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2401
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4042
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3591
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4035
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4030
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3243
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2246
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2574
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2553
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3861
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3620
param_iterator param_end()
Definition: Decl.h:2659
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2793
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2568
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3564
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2314
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2302
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3476
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4150
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2373
void setWillHaveBody(bool V=true)
Definition: Decl.h:2559
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2368
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4160
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3605
param_iterator param_begin()
Definition: Decl.h:2658
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition: Decl.h:2695
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
FunctionEffectsRef getFunctionEffects() const
Definition: Decl.h:3006
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3302
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4094
@ TK_MemberSpecialization
Definition: Decl.h:1944
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2760
bool isStatic() const
Definition: Decl.h:2801
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4360
void setTrivial(bool IT)
Definition: Decl.h:2303
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3981
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isDeletedAsWritten() const
Definition: Decl.h:2469
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2390
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2285
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3480
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2289
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2353
bool isImmediateEscalating() const
Definition: Decl.cpp:3256
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2281
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2552
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2214
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3294
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2788
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:3354
bool param_empty() const
Definition: Decl.h:2657
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:2121
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3168
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2150
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3560
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
void setIneligibleOrNotSelected(bool II)
Definition: Decl.h:2346
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4383
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2805
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3975
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3967
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2398
void setDefaulted(bool D=true)
Definition: Decl.h:2311
bool isConsteval() const
Definition: Decl.h:2407
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:2734
void setBody(Stmt *B)
Definition: Decl.cpp:3236
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3494
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3114
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition: Decl.h:2384
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4002
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3680
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2143
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3144
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2360
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:3191
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2771
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3546
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2558
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4910
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5280
Kind kind() const
The kind of the effect.
Definition: Type.h:4714
Kind
Identifies the particular effect.
Definition: Type.h:4676
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4853
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4973
unsigned getNumParams() const
Definition: Type.h:5226
QualType getParamType(unsigned i) const
Definition: Type.h:5228
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5259
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5350
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5237
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5233
ArrayRef< QualType > param_types() const
Definition: Type.h:5382
Declaration of a template function.
Definition: DeclTemplate.h:957
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:536
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4389
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4504
CallingConv getCC() const
Definition: Type.h:4451
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:4470
unsigned getRegParm() const
Definition: Type.h:4444
bool getNoCallerSavedRegs() const
Definition: Type.h:4440
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4463
bool getHasRegParm() const
Definition: Type.h:4442
bool getNoReturn() const
Definition: Type.h:4437
bool getProducesResult() const
Definition: Type.h:4438
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:4484
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:4498
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4278
ExtInfo getExtInfo() const
Definition: Type.h:4612
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3485
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4570
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4566
unsigned getRegParmType() const
Definition: Type.h:4603
CallingConv getCallConv() const
Definition: Type.h:4611
QualType getReturnType() const
Definition: Type.h:4600
bool getCmseNSCallAttr() const
Definition: Type.h:4610
@ SME_PStateSMEnabledMask
Definition: Type.h:4544
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:3675
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
Represents a C array with an unspecified size.
Definition: Type.h:3725
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3314
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5469
void setInherited(bool I)
Definition: Attr.h:154
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2506
Describes an C or C++ initializer list.
Definition: Expr.h:5029
child_range children()
Definition: Expr.h:5221
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:7482
@ 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:977
Represents the declaration of a label.
Definition: Decl.h:499
bool isResolvedMSAsmLabel() const
Definition: Decl.h:534
LabelStmt * getStmt() const
Definition: Decl.h:523
bool isMSAsmLabel() const
Definition: Decl.h:533
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Definition: LangOptions.h:278
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:629
FPExceptionModeKind getDefaultExceptionMode() const
Definition: LangOptions.h:757
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
Definition: LangOptions.h:662
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
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:553
bool implicitFunctionsAllowed() const
Returns true if implicit function declarations are allowed in the current language mode.
Definition: LangOptions.h:668
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:535
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:1358
Represents a linkage specification.
Definition: DeclCXX.h:2934
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2922
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:3187
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3482
Describes a module or submodule.
Definition: Module.h:105
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:111
Module * Parent
The parent of this module.
Definition: Module.h:154
bool isPrivateModule() const
Definition: Module.h:210
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition: Module.h:592
bool isModuleImplementation() const
Is this a module implementation.
Definition: Module.h:608
bool isModulePartition() const
Is this a module partition.
Definition: Module.h:597
bool isImplicitGlobalModule() const
Definition: Module.h:206
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:244
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:185
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:666
@ ClassId_NSObject
Definition: NSAPI.h:30
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
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:276
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:454
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:404
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
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:689
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1912
bool isExternallyVisible() const
Definition: Decl.h:408
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:372
Represent a C++ namespace.
Definition: Decl.h:547
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:598
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:2326
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2772
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:81
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2594
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1760
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
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:1833
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
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:250
Expr ** getExprs()
Definition: Expr.h:5846
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5835
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1203
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1216
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1199
Sugar for parentheses used when specifying types.
Definition: Type.h:3135
Represents a parameter to a function.
Definition: Decl.h:1722
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1782
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1786
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1755
QualType getOriginalType() const
Definition: Decl.cpp:2912
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:2903
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:838
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:918
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:958
AttributePool & getPool() const
Definition: ParsedAttr.h:965
PipeType - OpenCL20.
Definition: Type.h:7592
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1282
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1307
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3161
QualType getPointeeType() const
Definition: Type.h:3171
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:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7827
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7821
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:7890
@ DK_nontrivial_c_struct
Definition: Type.h:1535
PrimitiveDefaultInitializeKind
Definition: Type.h:1463
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2819
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:75
QualType withoutLocalFastQualifiers() const
Definition: Type.h:1221
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1303
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
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:2867
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7743
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7869
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:7884
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7783
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
QualType getCanonicalType() const
Definition: Type.h:7795
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7837
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2851
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1439
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7816
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
bool isCanonical() const
Definition: Type.h:7800
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1316
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1448
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2593
NonConstantStorageReason
Definition: Type.h:1025
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1493
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1498
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:7878
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7683
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7690
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4349
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:337
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:354
bool hasConst() const
Definition: Type.h:444
void removeConst()
Definition: Type.h:446
void addConst()
Definition: Type.h:447
ObjCLifetime getObjCLifetime() const
Definition: Type.h:532
bool empty() const
Definition: Type.h:634
Represents a struct/union/class.
Definition: Decl.h:4141
bool hasObjectMember() const
Definition: Decl.h:4201
field_range fields() const
Definition: Decl.h:4347
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5003
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5023
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5069
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4332
field_iterator field_begin() const
Definition: Decl.cpp:5057
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
RecordDecl * getDecl() const
Definition: Type.h:5946
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:7091
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:865
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
redecl_iterator redecls_end() const
Definition: Redeclarable.h:303
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4974
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:223
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3402
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3024
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:3072
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:381
void RemoveDecl(Decl *D)
Definition: Scope.h:353
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:384
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:581
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
@ 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:658
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
Definition: SemaCUDA.cpp:1070
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
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:740
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
Definition: SemaCUDA.cpp:1005
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition: SemaCUDA.cpp:805
void CheckEntryPoint(FunctionDecl *FD)
Definition: SemaHLSL.cpp:214
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:133
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition: SemaHLSL.cpp:181
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition: SemaHLSL.cpp:148
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:1160
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:1446
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:599
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:1374
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:1573
Mode getAlignMode() const
Definition: Sema.h:1575
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:1078
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:1090
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition: Sema.h:3254
static NameClassification VarTemplate(TemplateName Name)
Definition: Sema.h:3264
static NameClassification Unknown()
Definition: Sema.h:3234
static NameClassification OverloadSet(ExprResult E)
Definition: Sema.h:3238
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition: Sema.h:3282
static NameClassification FunctionTemplate(TemplateName Name)
Definition: Sema.h:3270
static NameClassification NonType(NamedDecl *D)
Definition: Sema.h:3244
static NameClassification Concept(TemplateName Name)
Definition: Sema.h:3276
static NameClassification UndeclaredNonType()
Definition: Sema.h:3250
static NameClassification TypeTemplate(TemplateName Name)
Definition: Sema.h:3258
static NameClassification Error()
Definition: Sema.h:3232
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12080
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12110
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:14123
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:10888
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6321
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:3102
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6661
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12637
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:803
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:2467
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
Definition: SemaType.cpp:8899
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:6581
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:9660
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:1557
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:15001
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:7857
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition: Sema.h:5830
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:8995
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8999
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:9018
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:9034
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition: Sema.h:9031
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9007
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:9002
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6597
void ActOnPopScope(SourceLocation Loc, Scope *S)
Definition: SemaDecl.cpp:2178
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
Definition: SemaDecl.cpp:5290
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:15682
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12769
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:37
NonTrivialCUnionContext
Definition: Sema.h:3622
@ NTCUC_CopyInit
Definition: Sema.h:3632
@ NTCUC_AutoVar
Definition: Sema.h:3630
@ NTCUC_DefaultInitializedObject
Definition: Sema.h:3628
@ NTCUC_FunctionReturn
Definition: Sema.h:3626
@ NTCUC_FunctionParam
Definition: Sema.h:3624
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:3535
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:6074
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
Definition: SemaLookup.cpp:991
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:18086
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
SemaOpenMP & OpenMP()
Definition: Sema.h:1219
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:6059
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:958
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:18027
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:4322
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:3084
PragmaClangSection PragmaClangRodataSection
Definition: Sema.h:1499
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:16221
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:6026
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:14880
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:1094
SemaCUDA & CUDA()
Definition: Sema.h:1164
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:17159
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:1453
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:2276
Preprocessor & getPreprocessor() const
Definition: Sema.h:599
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6812
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1730
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:1724
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:1162
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:6202
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:16917
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:4796
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:12191
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:16422
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:2097
@ 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:18105
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:18201
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:14496
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:1429
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15336
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:1547
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3413
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:639
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:1655
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:20046
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:14988
ASTContext & Context
Definition: Sema.h:1002
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:14516
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5766
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:597
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
Definition: SemaDecl.cpp:20067
bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX, const FunctionEffectWithCondition &EC, SourceLocation NewAttrLoc)
Warn and return true if adding an effect to a set would create a conflict.
Definition: SemaDecl.cpp:20233
void * SkippedDefinitionContext
Definition: Sema.h:3946
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:917
SemaObjC & ObjC()
Definition: Sema.h:1204
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
Definition: SemaDecl.cpp:5295
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4906
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:71
@ AllowFold
Definition: Sema.h:7249
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1495
PragmaStack< bool > StrictGuardStackCheckStack
Definition: Sema.h:1727
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:3092
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:2329
ASTContext & getASTContext() const
Definition: Sema.h:600
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:15754
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:1711
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:17580
PragmaStack< StringLiteral * > ConstSegStack
Definition: Sema.h:1723
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:694
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:663
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3075
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:4753
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9252
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20211
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:908
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:5448
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1552
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:16773
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:8925
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:11786
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7971
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:694
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:4343
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2164
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:1245
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:4161
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:16672
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition: Sema.h:595
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2182
void PopCompoundScope()
Definition: Sema.cpp:2314
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:19522
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition: Sema.h:13889
@ UPPC_EnumeratorValue
The enumerator value.
Definition: Sema.h:13892
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13904
@ UPPC_FriendDeclaration
A friend declaration.
Definition: Sema.h:13898
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13877
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13916
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition: Sema.h:13901
@ UPPC_DataMemberType
The type of a data member.
Definition: Sema.h:13880
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition: Sema.h:13883
const LangOptions & getLangOpts() const
Definition: Sema.h:593
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:1763
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition: Sema.h:3109
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1386
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:6557
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:6591
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1596
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:1001
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:8147
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:1964
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
const LangOptions & LangOpts
Definition: Sema.h:1000
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2389
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition: Sema.h:14966
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
Definition: SemaDecl.cpp:15176
SemaHLSL & HLSL()
Definition: Sema.h:1169
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1828
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11771
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:18296
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:1500
SemaRISCV & RISCV()
Definition: Sema.h:1234
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
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:3625
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:204
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:19790
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:1244
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:1206
PragmaStack< AlignPackInfo > AlignPackStack
Definition: Sema.h:1712
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:15640
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6471
PragmaStack< StringLiteral * > BSSSegStack
Definition: Sema.h:1722
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition: Sema.h:807
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:9348
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:7983
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:858
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:16748
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1373
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8286
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:12370
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:19548
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1033
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2309
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:14746
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2285
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2260
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:20101
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:18486
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6468
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1216
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:17985
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:9686
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8800
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:635
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:3163
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:14960
StringLiteral * CurInitSeg
Last section used with #pragma init_seg.
Definition: Sema.h:1762
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20131
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9597
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:8820
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:15282
bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:17976
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:15206
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1137
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:14786
SemaOpenCL & OpenCL()
Definition: Sema.h:1214
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5771
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
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:15043
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 ...
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7664
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:8327
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1287
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4698
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
Definition: SemaDecl.cpp:15615
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition: Sema.h:3106
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9007
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:15664
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:10900
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13471
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3839
@ NTK_Typedef
Definition: Sema.h:3844
@ NTK_NonUnion
Definition: Sema.h:3842
@ NTK_TypeAlias
Definition: Sema.h:3845
@ NTK_NonClass
Definition: Sema.h:3841
@ NTK_NonEnum
Definition: Sema.h:3843
@ NTK_NonStruct
Definition: Sema.h:3840
@ NTK_TemplateTemplateArgument
Definition: Sema.h:3848
@ NTK_TypeAliasTemplate
Definition: Sema.h:3847
@ NTK_Template
Definition: Sema.h:3846
SourceManager & getSourceManager() const
Definition: Sema.h:598
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams)
Handle a friend type declaration.
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_bits attribute.
Definition: Sema.h:3059
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:4268
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:19803
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:1338
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:11063
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:17962
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:1501
@ NTCUK_Destruct
Definition: Sema.h:3652
@ NTCUK_Init
Definition: Sema.h:3651
@ NTCUK_Copy
Definition: Sema.h:3653
PragmaClangSection PragmaClangDataSection
Definition: Sema.h:1498
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:19978
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15692
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=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13742
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:1226
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:20074
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:6281
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:215
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:20058
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8170
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:9392
@ CTK_ErrorRecovery
Definition: Sema.h:9393
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14152
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14671
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2330
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:4459
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:6048
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:590
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
@ CCEK_Enumerator
Enumerator value with fixed underlying type.
Definition: Sema.h:10009
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:18549
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3077
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:1891
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition: Sema.h:3080
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:287
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:19341
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12405
ASTConsumer & Consumer
Definition: Sema.h:1003
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4224
@ Ovl_NonFunction
This is not an overload because the lookup results contain a non-function.
Definition: Sema.h:9796
@ Ovl_Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition: Sema.h:9788
@ Ovl_Match
This is not an overload because the signature exactly matches an existing declaration.
Definition: Sema.h:9792
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6475
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:2048
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:1038
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1670
@ 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:16353
@ 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:4040
@ AMK_None
Don't merge availability attributes at all.
Definition: Sema.h:4042
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:4048
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:4051
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:4054
@ AMK_Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition: Sema.h:4045
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:14790
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5645
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:14459
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:16957
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:4776
SemaPPC & PPC()
Definition: Sema.h:1224
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:79
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8885
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:15128
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:963
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1334
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20624
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18795
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:1185
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:10924
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:3099
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17658
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7930
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1306
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:1005
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:5724
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15749
DiagnosticsEngine & Diags
Definition: Sema.h:1004
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:594
FPOptions CurFPFeatures
Definition: Sema.h:998
static bool CanBeGetReturnObject(const FunctionDecl *FD)
Definition: SemaDecl.cpp:15745
NamespaceDecl * getStdNamespace() const
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6614
PragmaStack< StringLiteral * > DataSegStack
Definition: Sema.h:1721
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:690
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:7183
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:14821
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11284
@ TPC_ClassTemplateMember
Definition: Sema.h:11282
@ TPC_FunctionTemplate
Definition: Sema.h:11281
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11285
@ TPC_VarTemplate
Definition: Sema.h:11280
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:6698
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:16208
void DiagnoseUnusedDecl(const NamedDecl *ND)
Definition: SemaDecl.cpp:2066
void PopDeclContext()
Definition: SemaDecl.cpp:1313
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:6060
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:1577
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:8794
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:13784
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:12951
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:1562
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:16616
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2372
OffsetOfKind
Definition: Sema.h:3863
@ OOK_Outside
Definition: Sema.h:3865
@ OOK_Macro
Definition: Sema.h:3870
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13224
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:18193
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:4304
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:14069
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:281
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
Definition: SemaDecl.cpp:20223
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:3074
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1947
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:20889
PragmaClangSection PragmaClangBSSSection
Definition: Sema.h:1497
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:6033
@ AbstractVariableType
Definition: Sema.h:5754
@ AbstractReturnType
Definition: Sema.h:5752
@ AbstractFieldType
Definition: Sema.h:5755
@ AbstractIvarType
Definition: Sema.h:5756
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:1701
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7975
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:1235
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:7997
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:20113
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8498
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:1320
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12917
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:2433
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2723
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:3055
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
Definition: SemaAttr.cpp:1169
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:15629
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:13203
SemaWasm & Wasm()
Definition: Sema.h:1254
IdentifierResolver IdResolver
Definition: Sema.h:3003
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:19774
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2321
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:679
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:15017
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:7938
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:3375
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6020
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:16689
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:219
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=std::nullopt)
Definition: SemaDecl.cpp:7351
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:8277
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:1262
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:287
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
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:3557
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3832
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3680
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3655
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3641
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3660
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4725
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4716
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4708
bool isUnion() const
Definition: Decl.h:3763
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4771
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4808
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3781
TagKind getTagKind() const
Definition: Decl.h:3752
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:218
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1533
unsigned getShortWidth() const
Return the size of 'signed short' and 'unsigned short' for this target, in bits.
Definition: TargetInfo.h:501
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:509
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1812
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:519
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1576
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1584
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1519
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1393
unsigned getCharWidth() const
Definition: TargetInfo.h:496
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:548
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:514
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1498
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1294
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1487
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:639
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:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
TemplateDecl * getAsTemplateDecl() 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:203
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6473
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:4270
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:4430
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5589
Represents a declaration of a type.
Definition: Decl.h:3363
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3388
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:1225
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:742
SourceLocation getTemplateKeywordLoc() const
Get the SourceLocation of the template keyword (if any).
Definition: TypeLoc.cpp:749
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:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7714
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:7725
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:6736
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3130
The base class of the type hierarchy.
Definition: Type.h:1829
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:2474
bool isStructureType() const
Definition: Type.cpp:629
bool isDecltypeType() const
Definition: Type.h:8189
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isDependentSizedArrayType() const
Definition: Type.h:8084
bool isBlockPointerType() const
Definition: Type.h:8006
bool isVoidType() const
Definition: Type.h:8295
bool isBooleanType() const
Definition: Type.h:8423
bool isFunctionReferenceType() const
Definition: Type.h:8039
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2167
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8473
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2889
bool isIncompleteArrayType() const
Definition: Type.h:8072
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8592
bool isDependentAddressSpaceType() const
Definition: Type.h:8130
bool isConstantArrayType() const
Definition: Type.h:8068
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8453
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isArrayType() const
Definition: Type.h:8064
bool isFunctionPointerType() const
Definition: Type.h:8032
bool isPointerType() const
Definition: Type.h:7996
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2480
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8583
bool isReferenceType() const
Definition: Type.h:8010
bool isEnumeralType() const
Definition: Type.h:8096
bool isScalarType() const
Definition: Type.h:8394
bool isVariableArrayType() const
Definition: Type.h:8076
bool isClkEventT() const
Definition: Type.h:8207
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8410
bool isImageType() const
Definition: Type.h:8219
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2777
bool isPipeType() const
Definition: Type.h:8226
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2680
bool isBitIntType() const
Definition: Type.h:8230
bool isOpenCLSpecificType() const
Definition: Type.h:8255
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2672
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2338
bool isHalfType() const
Definition: Type.h:8299
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2011
const RecordType * getAsStructureType() const
Definition: Type.cpp:721
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2464
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2666
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8466
bool isAtomicType() const
Definition: Type.h:8147
bool isFunctionProtoType() const
Definition: Type.h:2510
bool isObjCIdType() const
Definition: Type.h:8167
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2690
bool isObjCObjectType() const
Definition: Type.h:8138
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4961
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8429
bool isEventT() const
Definition: Type.h:8203
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4904
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:8533
bool isFunctionType() const
Definition: Type.h:7992
bool isObjCObjectPointerType() const
Definition: Type.h:8134
bool isMemberFunctionPointerType() const
Definition: Type.h:8050
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2494
bool isFloatingType() const
Definition: Type.cpp:2249
bool isAnyPointerType() const
Definition: Type.h:8000
TypeClass getTypeClass() const
Definition: Type.h:2316
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:2016
bool isSamplerT() const
Definition: Type.h:8199
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:605
bool isNullPtrType() const
Definition: Type.h:8328
bool isRecordType() const
Definition: Type.h:8092
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4686
bool isUnionType() const
Definition: Type.cpp:671
bool isFunctionNoProtoType() const
Definition: Type.h:2509
bool isReserveIDT() const
Definition: Type.h:8215
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:1890
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2476
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3507
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5491
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3405
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3455
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3471
QualType getUnderlyingType() const
Definition: Decl.h:3460
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3467
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5500
TypedefNameDecl * getDecl() const
Definition: Type.h:5611
QualType desugar() const
Definition: Type.cpp:3868
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:2188
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1025
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
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:3320
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3384
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:3092
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5359
Represents a variable declaration or definition.
Definition: Decl.h:879
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2775
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2133
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1466
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1510
TLSKind getTLSKind() const
Definition: Decl.cpp:2150
bool hasInit() const
Definition: Decl.cpp:2380
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1393
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2242
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2172
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:2426
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2239
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1519
bool isCXXCondDecl() const
Definition: Decl.h:1556
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:890
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition: Decl.h:893
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:887
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2145
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1538
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1231
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1174
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2348
void setInlineSpecified()
Definition: Decl.h:1499
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1156
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2737
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1290
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1121
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1492
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1125
const Expr * getInit() const
Definition: Decl.h:1316
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1165
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1132
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2411
void setConstexpr(bool IC)
Definition: Decl.h:1513
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:902
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:905
void setInit(Expr *I)
Definition: Decl.cpp:2442
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2327
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1246
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1243
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1249
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2780
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2227
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1201
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1116
void setImplicitlyInline()
Definition: Decl.h:1504
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1417
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1533
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2671
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1210
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:2744
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1427
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2651
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:3769
Expr * getSizeExpr() const
Definition: Type.h:3788
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:739
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
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:749
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:731
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:878
ParmVarDecl * ExplicitObjectParameter
Definition: ScopeInfo.h:875
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:948
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:890
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:175
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:1883
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ GNUMode
Definition: LangStandard.h:64
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus14
Definition: LangStandard.h:58
@ CPlusPlus17
Definition: LangStandard.h:59
@ 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:28
CUDAFunctionTarget
Definition: Cuda.h:140
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:268
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
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:245
@ SC_Auto
Definition: Specifiers.h:253
@ SC_PrivateExtern
Definition: Specifiers.h:250
@ SC_Extern
Definition: Specifiers.h:248
@ SC_Register
Definition: Specifiers.h:254
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:232
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:238
@ TSCS_unspecified
Definition: Specifiers.h:233
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:241
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:235
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:304
TagUseKind
Definition: Sema.h:469
TagTypeKind
The kind of a tag type.
Definition: Type.h:6683
@ 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:1542
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:1039
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:31
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:445
@ 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:132
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:1911
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1264
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:387
@ 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:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_C
Definition: Specifiers.h:276
@ CC_X86StdCall
Definition: Specifiers.h:277
@ 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:5748
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:120
@ AS_public
Definition: Specifiers.h:121
@ AS_protected
Definition: Specifiers.h:122
@ AS_none
Definition: Specifiers.h:124
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
#define bool
Definition: stdbool.h:24
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:1425
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1576
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1400
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1359
const IdentifierInfo * Ident
Definition: DeclSpec.h:1331
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1248
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1660
enum clang::DeclaratorChunk::@225 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:161
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1641
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1684
RetTy visit(QualType FT, Ts &&... Args)
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition: Type.h:4791
EffectConditionExpr Cond
Definition: Type.h:4793
std::string description() const
Return a textual description of the effect, and its condition, if any.
Definition: Type.cpp:5323
Extra information about a function prototype.
Definition: Type.h:5058
FunctionEffectsRef FunctionEffects
Definition: Type.h:5068
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:5078
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:57
std::vector< std::string > Features
Definition: TargetInfo.h:58
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
SourceLocation PragmaLocation
Definition: Sema.h:1494
ValueType CurrentValue
Definition: Sema.h:1697
bool CheckSameAsPrevious
Definition: Sema.h:373
NamedDecl * Previous
Definition: Sema.h:374
NamedDecl * New
Definition: Sema.h:375
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.