clang 24.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
37#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
38#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
39#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
40#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42#include "clang/Sema/DeclSpec.h"
45#include "clang/Sema/Lookup.h"
47#include "clang/Sema/Scope.h"
50#include "clang/Sema/SemaARM.h"
51#include "clang/Sema/SemaCUDA.h"
52#include "clang/Sema/SemaHLSL.h"
54#include "clang/Sema/SemaObjC.h"
57#include "clang/Sema/SemaPPC.h"
59#include "clang/Sema/SemaSYCL.h"
61#include "clang/Sema/SemaWasm.h"
62#include "clang/Sema/Template.h"
63#include "llvm/ADT/ArrayRef.h"
64#include "llvm/ADT/STLForwardCompat.h"
65#include "llvm/ADT/ScopeExit.h"
66#include "llvm/ADT/SmallPtrSet.h"
67#include "llvm/ADT/SmallString.h"
68#include "llvm/ADT/StringExtras.h"
69#include "llvm/ADT/StringRef.h"
70#include "llvm/Support/SaveAndRestore.h"
71#include "llvm/TargetParser/Triple.h"
72#include <algorithm>
73#include <cstring>
74#include <optional>
75#include <unordered_map>
76
77using namespace clang;
78using namespace sema;
79
81 if (OwnedType) {
82 Decl *Group[2] = { OwnedType, Ptr };
84 }
85
87}
88
89namespace {
90
91class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
92 public:
93 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
94 bool AllowTemplates = false,
95 bool AllowNonTemplates = true)
96 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
97 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
98 WantExpressionKeywords = false;
99 WantCXXNamedCasts = false;
100 WantRemainingKeywords = false;
101 }
102
103 bool ValidateCandidate(const TypoCorrection &candidate) override {
104 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
105 if (!AllowInvalidDecl && ND->isInvalidDecl())
106 return false;
107
108 if (getAsTypeTemplateDecl(ND))
109 return AllowTemplates;
110
111 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
112 if (!IsType)
113 return false;
114
115 if (AllowNonTemplates)
116 return true;
117
118 // An injected-class-name of a class template (specialization) is valid
119 // as a template or as a non-template.
120 if (AllowTemplates) {
121 auto *RD = dyn_cast<CXXRecordDecl>(ND);
122 if (!RD || !RD->isInjectedClassName())
123 return false;
124 RD = cast<CXXRecordDecl>(RD->getDeclContext());
125 return RD->getDescribedClassTemplate() ||
127 }
128
129 return false;
130 }
131
132 return !WantClassName && candidate.isKeyword();
133 }
134
135 std::unique_ptr<CorrectionCandidateCallback> clone() override {
136 return std::make_unique<TypeNameValidatorCCC>(*this);
137 }
138
139 private:
140 bool AllowInvalidDecl;
141 bool WantClassName;
142 bool AllowTemplates;
143 bool AllowNonTemplates;
144};
145
146} // end anonymous namespace
147
149 TypeDecl *TD, SourceLocation NameLoc) {
150 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
151 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
152 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
153 FoundRD->isInjectedClassName() &&
154 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
155 Diag(NameLoc,
157 ? diag::ext_out_of_line_qualified_id_type_names_constructor
158 : diag::err_out_of_line_qualified_id_type_names_constructor)
159 << TD->getIdentifier() << /*Type=*/1
160 << 0 /*if any keyword was present, it was 'typename'*/;
161 }
162
163 DiagnoseUseOfDecl(TD, NameLoc);
164 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
165}
166
167namespace {
168enum class UnqualifiedTypeNameLookupResult {
169 NotFound,
170 FoundNonType,
171 FoundType
172};
173} // end anonymous namespace
174
175/// Tries to perform unqualified lookup of the type decls in bases for
176/// dependent class.
177/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
178/// type decl, \a FoundType if only type decls are found.
179static UnqualifiedTypeNameLookupResult
181 SourceLocation NameLoc,
182 const CXXRecordDecl *RD) {
183 if (!RD->hasDefinition())
184 return UnqualifiedTypeNameLookupResult::NotFound;
185 // Look for type decls in base classes.
186 UnqualifiedTypeNameLookupResult FoundTypeDecl =
187 UnqualifiedTypeNameLookupResult::NotFound;
188 for (const auto &Base : RD->bases()) {
189 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
190 if (BaseRD) {
191 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
192 Base.getType().getCanonicalType())) {
193 // Look for type decls in dependent base classes that have known primary
194 // templates.
195 if (!TST->isDependentType())
196 continue;
197 auto *TD = TST->getTemplateName().getAsTemplateDecl();
198 if (!TD)
199 continue;
200 if (auto *BasePrimaryTemplate =
201 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
202 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
203 BaseRD = BasePrimaryTemplate;
204 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206 CTD->findPartialSpecialization(Base.getType()))
207 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
208 BaseRD = PS;
209 }
210 }
211 }
212 if (BaseRD) {
213 for (NamedDecl *ND : BaseRD->lookup(&II)) {
214 if (!isa<TypeDecl>(ND))
215 return UnqualifiedTypeNameLookupResult::FoundNonType;
216 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
217 }
218 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
219 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
220 case UnqualifiedTypeNameLookupResult::FoundNonType:
221 return UnqualifiedTypeNameLookupResult::FoundNonType;
222 case UnqualifiedTypeNameLookupResult::FoundType:
223 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
224 break;
225 case UnqualifiedTypeNameLookupResult::NotFound:
226 break;
227 }
228 }
229 }
230 }
231
232 return FoundTypeDecl;
233}
234
236 const IdentifierInfo &II,
237 SourceLocation NameLoc) {
238 // Lookup in the parent class template context, if any.
239 const CXXRecordDecl *RD = nullptr;
240 UnqualifiedTypeNameLookupResult FoundTypeDecl =
241 UnqualifiedTypeNameLookupResult::NotFound;
242 for (DeclContext *DC = S.CurContext;
243 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
244 DC = DC->getParent()) {
245 // Look for type decls in dependent base classes that have known primary
246 // templates.
247 RD = dyn_cast<CXXRecordDecl>(DC);
248 if (RD && RD->getDescribedClassTemplate())
249 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
250 }
251 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
252 return nullptr;
253
254 // We found some types in dependent base classes. Recover as if the user
255 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
256 // allowed. We'll fully resolve the lookup during template instantiation.
257 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
258
259 ASTContext &Context = S.Context;
260 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
261 QualType T =
262 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
263
264 CXXScopeSpec SS;
265 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
266
267 TypeLocBuilder Builder;
268 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
269 DepTL.setNameLoc(NameLoc);
271 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
272 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
273}
274
276 Scope *S, CXXScopeSpec *SS, bool isClassName,
277 bool HasTrailingDot, ParsedType ObjectTypePtr,
278 bool IsCtorOrDtorName,
279 bool WantNontrivialTypeSourceInfo,
280 bool IsClassTemplateDeductionContext,
281 ImplicitTypenameContext AllowImplicitTypename,
282 IdentifierInfo **CorrectedII) {
283 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
284 // FIXME: Consider allowing this outside C++1z mode as an extension.
285 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
286 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
287 !HasTrailingDot;
288
289 // Determine where we will perform name lookup.
290 DeclContext *LookupCtx = nullptr;
291 if (ObjectTypePtr) {
292 QualType ObjectType = ObjectTypePtr.get();
293 if (ObjectType->isRecordType())
294 LookupCtx = computeDeclContext(ObjectType);
295 } else if (SS && SS->isNotEmpty()) {
296 LookupCtx = computeDeclContext(*SS, false);
297
298 if (!LookupCtx) {
299 if (isDependentScopeSpecifier(*SS)) {
300 // C++ [temp.res]p3:
301 // A qualified-id that refers to a type and in which the
302 // nested-name-specifier depends on a template-parameter (14.6.2)
303 // shall be prefixed by the keyword typename to indicate that the
304 // qualified-id denotes a type, forming an
305 // elaborated-type-specifier (7.1.5.3).
306 //
307 // We therefore do not perform any name lookup if the result would
308 // refer to a member of an unknown specialization.
309 // In C++2a, in several contexts a 'typename' is not required. Also
310 // allow this as an extension.
311 if (IsImplicitTypename) {
312 if (AllowImplicitTypename == ImplicitTypenameContext::No)
313 return nullptr;
314 SourceLocation QualifiedLoc = SS->getRange().getBegin();
315 // FIXME: Defer the diagnostic after we build the type and use it.
316 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
317 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
318 SS->getScopeRep(), &II);
320 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
321 }
322
323 // We know from the grammar that this name refers to a type,
324 // so build a dependent node to describe the type.
325 if (WantNontrivialTypeSourceInfo)
326 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
327 (ImplicitTypenameContext)IsImplicitTypename)
328 .get();
329
332 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
334 SourceLocation(), QualifierLoc, II, NameLoc);
335 return ParsedType::make(T);
336 }
337
338 return nullptr;
339 }
340
341 if (!LookupCtx->isDependentContext() &&
342 RequireCompleteDeclContext(*SS, LookupCtx))
343 return nullptr;
344 }
345
346 // In the case where we know that the identifier is a class name, we know that
347 // it is a type declaration (struct, class, union or enum) so we can use tag
348 // name lookup.
349 //
350 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
351 // the component name of the type-name or simple-template-id is type-only.
352 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
353 LookupResult Result(*this, &II, NameLoc, Kind);
354 if (LookupCtx) {
355 // Perform "qualified" name lookup into the declaration context we
356 // computed, which is either the type of the base of a member access
357 // expression or the declaration context associated with a prior
358 // nested-name-specifier.
359 LookupQualifiedName(Result, LookupCtx);
360
361 if (ObjectTypePtr && Result.empty()) {
362 // C++ [basic.lookup.classref]p3:
363 // If the unqualified-id is ~type-name, the type-name is looked up
364 // in the context of the entire postfix-expression. If the type T of
365 // the object expression is of a class type C, the type-name is also
366 // looked up in the scope of class C. At least one of the lookups shall
367 // find a name that refers to (possibly cv-qualified) T.
368 LookupName(Result, S);
369 }
370 } else {
371 // Perform unqualified name lookup.
372 LookupName(Result, S);
373
374 // For unqualified lookup in a class template in MSVC mode, look into
375 // dependent base classes where the primary class template is known.
376 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
377 if (ParsedType TypeInBase =
378 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
379 return TypeInBase;
380 }
381 }
382
383 NamedDecl *IIDecl = nullptr;
384 UsingShadowDecl *FoundUsingShadow = nullptr;
385 switch (Result.getResultKind()) {
387 if (CorrectedII) {
388 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
389 AllowDeducedTemplate);
390 TypoCorrection Correction =
391 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
393 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
395 bool MemberOfUnknownSpecialization;
397 TemplateName.setIdentifier(NewII, NameLoc);
399 CXXScopeSpec NewSS, *NewSSPtr = SS;
400 if (SS && NNS) {
401 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
402 NewSSPtr = &NewSS;
403 }
404 if (Correction && (NNS || NewII != &II) &&
405 // Ignore a correction to a template type as the to-be-corrected
406 // identifier is not a template (typo correction for template names
407 // is handled elsewhere).
408 !(getLangOpts().CPlusPlus && NewSSPtr &&
409 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
410 Template, MemberOfUnknownSpecialization))) {
411 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
412 isClassName, HasTrailingDot, ObjectTypePtr,
413 IsCtorOrDtorName,
414 WantNontrivialTypeSourceInfo,
415 IsClassTemplateDeductionContext);
416 if (Ty) {
417 diagnoseTypo(Correction,
418 PDiag(diag::err_unknown_type_or_class_name_suggest)
419 << Result.getLookupName() << isClassName);
420 if (SS && NNS)
421 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
422 *CorrectedII = NewII;
423 return Ty;
424 }
425 }
426 }
427 Result.suppressDiagnostics();
428 return nullptr;
430 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
431 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
432 SS->getScopeRep(), &II);
433 TypeLocBuilder TLB;
437 TL.setNameLoc(NameLoc);
439 }
440 [[fallthrough]];
443 Result.suppressDiagnostics();
444 return nullptr;
445
447 // Recover from type-hiding ambiguities by hiding the type. We'll
448 // do the lookup again when looking for an object, and we can
449 // diagnose the error then. If we don't do this, then the error
450 // about hiding the type will be immediately followed by an error
451 // that only makes sense if the identifier was treated like a type.
452 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
453 Result.suppressDiagnostics();
454 return nullptr;
455 }
456
457 // Look to see if we have a type anywhere in the list of results.
458 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
459 Res != ResEnd; ++Res) {
460 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
462 RealRes) ||
463 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
464 if (!IIDecl ||
465 // Make the selection of the recovery decl deterministic.
466 RealRes->getLocation() < IIDecl->getLocation()) {
467 IIDecl = RealRes;
468 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
469 }
470 }
471 }
472
473 if (!IIDecl) {
474 // None of the entities we found is a type, so there is no way
475 // to even assume that the result is a type. In this case, don't
476 // complain about the ambiguity. The parser will either try to
477 // perform this lookup again (e.g., as an object name), which
478 // will produce the ambiguity, or will complain that it expected
479 // a type name.
480 Result.suppressDiagnostics();
481 return nullptr;
482 }
483
484 // We found a type within the ambiguous lookup; diagnose the
485 // ambiguity and then return that type. This might be the right
486 // answer, or it might not be, but it suppresses any attempt to
487 // perform the name lookup again.
488 break;
489
491 IIDecl = Result.getFoundDecl();
492 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
493 break;
494 }
495
496 assert(IIDecl && "Didn't find decl");
497
498 TypeLocBuilder TLB;
499 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
500 checkTypeDeclType(LookupCtx,
501 IsImplicitTypename ? DiagCtorKind::Implicit
503 TD, NameLoc);
504 QualType T;
505 if (FoundUsingShadow) {
507 SS ? SS->getScopeRep() : std::nullopt,
508 FoundUsingShadow);
509 if (!WantNontrivialTypeSourceInfo)
510 return ParsedType::make(T);
511 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
514 NameLoc);
515 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
517 SS ? SS->getScopeRep() : std::nullopt, Tag,
518 /*OwnsTag=*/false);
519 if (!WantNontrivialTypeSourceInfo)
520 return ParsedType::make(T);
521 auto TL = TLB.push<TagTypeLoc>(T);
523 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
525 TL.setNameLoc(NameLoc);
526 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
527 TN && !isa<ObjCTypeParamDecl>(TN)) {
528 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
529 SS ? SS->getScopeRep() : std::nullopt, TN);
530 if (!WantNontrivialTypeSourceInfo)
531 return ParsedType::make(T);
532 TLB.push<TypedefTypeLoc>(T).set(
533 /*ElaboratedKeywordLoc=*/SourceLocation(),
535 NameLoc);
536 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
537 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
538 SS ? SS->getScopeRep() : std::nullopt,
539 UD);
540 if (!WantNontrivialTypeSourceInfo)
541 return ParsedType::make(T);
542 TLB.push<UnresolvedUsingTypeLoc>(T).set(
543 /*ElaboratedKeywordLoc=*/SourceLocation(),
545 NameLoc);
546 } else {
547 T = Context.getTypeDeclType(TD);
548 if (!WantNontrivialTypeSourceInfo)
549 return ParsedType::make(T);
551 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
552 else
553 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
554 }
556 }
557
558 if (getLangOpts().HLSL) {
559 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
560 getAsTemplateNameDecl(IIDecl, /*AllowFunctionTemplates=*/false,
561 /*AllowDependent=*/false))) {
562 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(TD, NameLoc);
563 if (!ShorthandTy.isNull())
564 return ParsedType::make(ShorthandTy);
565 }
566 }
567
568 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
569 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
570 if (!HasTrailingDot) {
571 // FIXME: Support UsingType for this case.
572 QualType T = Context.getObjCInterfaceType(IDecl);
573 if (!WantNontrivialTypeSourceInfo)
574 return ParsedType::make(T);
575 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
576 TL.setNameLoc(NameLoc);
577 // FIXME: Pass in this source location.
578 TL.setNameEndLoc(NameLoc);
580 }
581 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
582 (void)DiagnoseUseOfDecl(UD, NameLoc);
583 // Recover with 'int'
584 return ParsedType::make(Context.IntTy);
585 } else if (AllowDeducedTemplate) {
586 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
587 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
588 // FIXME: Support UsingType here.
589 TemplateName Template = Context.getQualifiedTemplateName(
590 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
591 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
592 QualType T = Context.getDeducedTemplateSpecializationType(
594 Template);
597 TL.setNameLoc(NameLoc);
598 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
601 }
602 }
603
604 // As it's not plausibly a type, suppress diagnostics.
605 Result.suppressDiagnostics();
606 return nullptr;
607}
608
609// Builds a fake NNS for the given decl context.
612 for (;; DC = DC->getLookupParent()) {
613 DC = DC->getPrimaryContext();
614 auto *ND = dyn_cast<NamespaceDecl>(DC);
615 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
616 return NestedNameSpecifier(Context, ND, std::nullopt);
617 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
618 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
621 }
622 llvm_unreachable("something isn't in TU scope?");
623}
624
625/// Find the parent class with dependent bases of the innermost enclosing method
626/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
627/// up allowing unqualified dependent type names at class-level, which MSVC
628/// correctly rejects.
629static const CXXRecordDecl *
631 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
632 DC = DC->getPrimaryContext();
633 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
634 if (MD->getParent()->hasAnyDependentBases())
635 return MD->getParent();
636 }
637 return nullptr;
638}
639
641 SourceLocation NameLoc,
642 bool IsTemplateTypeArg) {
643 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
644
645 NestedNameSpecifier NNS = std::nullopt;
646 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
647 // If we weren't able to parse a default template argument, delay lookup
648 // until instantiation time by making a non-dependent DependentTypeName. We
649 // pretend we saw a NestedNameSpecifier referring to the current scope, and
650 // lookup is retried.
651 // FIXME: This hurts our diagnostic quality, since we get errors like "no
652 // type named 'Foo' in 'current_namespace'" when the user didn't write any
653 // name specifiers.
655 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
656 } else if (const CXXRecordDecl *RD =
658 // Build a DependentNameType that will perform lookup into RD at
659 // instantiation time.
660 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
661
662 // Diagnose that this identifier was undeclared, and retry the lookup during
663 // template instantiation.
664 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
665 << RD;
666 } else {
667 // This is not a situation that we should recover from.
668 return ParsedType();
669 }
670
671 QualType T =
672 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
673
674 // Build type location information. We synthesized the qualifier, so we have
675 // to build a fake NestedNameSpecifierLoc.
676 NestedNameSpecifierLocBuilder NNSLocBuilder;
677 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
678 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
679
680 TypeLocBuilder Builder;
681 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
682 DepTL.setNameLoc(NameLoc);
684 DepTL.setQualifierLoc(QualifierLoc);
685 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
686}
687
689 // Do a tag name lookup in this scope.
690 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
691 LookupName(R, S, false);
692 R.suppressDiagnostics();
693 if (R.getResultKind() == LookupResultKind::Found)
694 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
695 switch (TD->getTagKind()) {
701 return DeclSpec::TST_union;
703 return DeclSpec::TST_class;
705 return DeclSpec::TST_enum;
706 }
707 }
708
710}
711
713 if (!CurContext->isRecord())
714 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
715
716 switch (SS->getScopeRep().getKind()) {
718 return true;
720 QualType T(SS->getScopeRep().getAsType(), 0);
721 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
722 if (Context.hasSameUnqualifiedType(T, Base.getType()))
723 return true;
724 [[fallthrough]];
725 }
726 default:
727 return S->isFunctionPrototypeScope();
728 }
729}
730
732 SourceLocation IILoc,
733 Scope *S,
734 CXXScopeSpec *SS,
735 ParsedType &SuggestedType,
736 bool IsTemplateName) {
737 // Don't report typename errors for editor placeholders.
738 if (II->isEditorPlaceholder())
739 return;
740 // We don't have anything to suggest (yet).
741 SuggestedType = nullptr;
742
743 // There may have been a typo in the name of the type. Look up typo
744 // results, in case we have something that we can suggest.
745 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
746 /*AllowTemplates=*/IsTemplateName,
747 /*AllowNonTemplates=*/!IsTemplateName);
748 if (TypoCorrection Corrected =
751 // FIXME: Support error recovery for the template-name case.
752 bool CanRecover = !IsTemplateName;
753 if (Corrected.isKeyword()) {
754 // We corrected to a keyword.
755 diagnoseTypo(Corrected,
756 PDiag(IsTemplateName ? diag::err_no_template_suggest
757 : diag::err_unknown_typename_suggest)
758 << II);
759 II = Corrected.getCorrectionAsIdentifierInfo();
760 } else {
761 // We found a similarly-named type or interface; suggest that.
762 if (!SS || !SS->isSet()) {
763 diagnoseTypo(Corrected,
764 PDiag(IsTemplateName ? diag::err_no_template_suggest
765 : diag::err_unknown_typename_suggest)
766 << II, CanRecover);
767 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
768 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
769 bool DroppedSpecifier =
770 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
771 diagnoseTypo(Corrected,
772 PDiag(IsTemplateName
773 ? diag::err_no_member_template_suggest
774 : diag::err_unknown_nested_typename_suggest)
775 << II << DC << DroppedSpecifier << SS->getRange(),
776 CanRecover);
777 } else {
778 llvm_unreachable("could not have corrected a typo here");
779 }
780
781 if (!CanRecover)
782 return;
783
784 CXXScopeSpec tmpSS;
785 if (Corrected.getCorrectionSpecifier())
786 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
787 SourceRange(IILoc));
788 // FIXME: Support class template argument deduction here.
789 SuggestedType =
790 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
791 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
792 /*IsCtorOrDtorName=*/false,
793 /*WantNontrivialTypeSourceInfo=*/true);
794 }
795 return;
796 }
797
798 if (getLangOpts().CPlusPlus && !IsTemplateName) {
799 // See if II is a class template that the user forgot to pass arguments to.
800 UnqualifiedId Name;
801 Name.setIdentifier(II, IILoc);
802 CXXScopeSpec EmptySS;
803 TemplateTy TemplateResult;
804 bool MemberOfUnknownSpecialization;
805 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
806 Name, nullptr, true, TemplateResult,
807 MemberOfUnknownSpecialization) == TNK_Type_template) {
808 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
809 return;
810 }
811 }
812
813 // FIXME: Should we move the logic that tries to recover from a missing tag
814 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
815
816 if (!SS || (!SS->isSet() && !SS->isInvalid()))
817 Diag(IILoc, IsTemplateName ? diag::err_no_template
818 : diag::err_unknown_typename)
819 << II;
820 else if (DeclContext *DC = computeDeclContext(*SS, false))
821 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
822 : diag::err_typename_nested_not_found)
823 << II << DC << SS->getRange();
824 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
825 SuggestedType =
826 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
827 } else if (isDependentScopeSpecifier(*SS)) {
828 unsigned DiagID = diag::err_typename_missing;
829 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
830 DiagID = diag::ext_typename_missing;
831
832 SuggestedType =
833 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
834
835 Diag(SS->getRange().getBegin(), DiagID)
836 << GetTypeFromParser(SuggestedType)
837 << SourceRange(SS->getRange().getBegin(), IILoc)
838 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
839 } else {
840 assert(SS && SS->isInvalid() &&
841 "Invalid scope specifier has already been diagnosed");
842 }
843}
844
845/// Determine whether the given result set contains either a type name
846/// or
847static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
848 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
849 NextToken.is(tok::less);
850
851 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
853 return true;
854
855 if (CheckTemplate && isa<TemplateDecl>(*I))
856 return true;
857 }
858
859 return false;
860}
861
863 Scope *S, CXXScopeSpec &SS,
864 IdentifierInfo *&Name,
865 SourceLocation NameLoc) {
866 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
867 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
868 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
869 StringRef FixItTagName;
870 switch (Tag->getTagKind()) {
872 FixItTagName = "class ";
873 break;
874
876 FixItTagName = "enum ";
877 break;
878
880 FixItTagName = "struct ";
881 break;
882
884 FixItTagName = "__interface ";
885 break;
886
888 FixItTagName = "union ";
889 break;
890 }
891
892 StringRef TagName = FixItTagName.drop_back();
893 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
894 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
895 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
896
897 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
898 I != IEnd; ++I)
899 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
900 << Name << TagName;
901
902 // Replace lookup results with just the tag decl.
904 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
905 return true;
906 }
907
908 return false;
909}
910
912 IdentifierInfo *&Name,
913 SourceLocation NameLoc,
914 const Token &NextToken,
916 DeclarationNameInfo NameInfo(Name, NameLoc);
917 ObjCMethodDecl *CurMethod = getCurMethodDecl();
918
919 assert(NextToken.isNot(tok::coloncolon) &&
920 "parse nested name specifiers before calling ClassifyName");
921 if (getLangOpts().CPlusPlus && SS.isSet() &&
922 isCurrentClassName(*Name, S, &SS)) {
923 // Per [class.qual]p2, this names the constructors of SS, not the
924 // injected-class-name. We don't have a classification for that.
925 // There's not much point caching this result, since the parser
926 // will reject it later.
928 }
929
930 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
931 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
932 /*AllowBuiltinCreation=*/!CurMethod);
933
934 if (SS.isInvalid())
936
937 // For unqualified lookup in a class template in MSVC mode, look into
938 // dependent base classes where the primary class template is known.
939 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
940 if (ParsedType TypeInBase =
941 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
942 return TypeInBase;
943 }
944
945 // Perform lookup for Objective-C instance variables (including automatically
946 // synthesized instance variables), if we're in an Objective-C method.
947 // FIXME: This lookup really, really needs to be folded in to the normal
948 // unqualified lookup mechanism.
949 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
950 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
951 if (Ivar.isInvalid())
953 if (Ivar.isUsable())
955
956 // We defer builtin creation until after ivar lookup inside ObjC methods.
957 if (Result.empty())
959 }
960
961 bool SecondTry = false;
962 bool IsFilteredTemplateName = false;
963
964Corrected:
965 switch (Result.getResultKind()) {
967 // If an unqualified-id is followed by a '(', then we have a function
968 // call.
969 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
970 // In C++, this is an ADL-only call.
971 // FIXME: Reference?
974
975 // C90 6.3.2.2:
976 // If the expression that precedes the parenthesized argument list in a
977 // function call consists solely of an identifier, and if no
978 // declaration is visible for this identifier, the identifier is
979 // implicitly declared exactly as if, in the innermost block containing
980 // the function call, the declaration
981 //
982 // extern int identifier ();
983 //
984 // appeared.
985 //
986 // We also allow this in C99 as an extension. However, this is not
987 // allowed in all language modes as functions without prototypes may not
988 // be supported.
989 if (getLangOpts().implicitFunctionsAllowed()) {
990 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
992 }
993 }
994
995 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
996 // In C++20 onwards, this could be an ADL-only call to a function
997 // template, and we're required to assume that this is a template name.
998 //
999 // FIXME: Find a way to still do typo correction in this case.
1001 Context.getAssumedTemplateName(NameInfo.getName());
1003 }
1004
1005 // In C, we first see whether there is a tag type by the same name, in
1006 // which case it's likely that the user just forgot to write "enum",
1007 // "struct", or "union".
1008 if (!getLangOpts().CPlusPlus && !SecondTry &&
1009 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1010 break;
1011 }
1012
1013 // Perform typo correction to determine if there is another name that is
1014 // close to this name.
1015 if (!SecondTry && CCC) {
1016 SecondTry = true;
1017 if (TypoCorrection Corrected =
1018 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1019 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1020 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1021 unsigned QualifiedDiag = diag::err_no_member_suggest;
1022
1023 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1024 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1025 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1026 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1027 UnqualifiedDiag = diag::err_no_template_suggest;
1028 QualifiedDiag = diag::err_no_member_template_suggest;
1029 } else if (UnderlyingFirstDecl &&
1030 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1031 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1032 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1033 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1034 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1035 }
1036
1037 if (SS.isEmpty()) {
1038 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1039 } else {// FIXME: is this even reachable? Test it.
1040 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1041 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1042 Name->getName() == CorrectedStr;
1043 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1044 << Name << computeDeclContext(SS, false)
1045 << DroppedSpecifier << SS.getRange());
1046 }
1047
1048 // Update the name, so that the caller has the new name.
1049 Name = Corrected.getCorrectionAsIdentifierInfo();
1050
1051 // Typo correction corrected to a keyword.
1052 if (Corrected.isKeyword())
1053 return Name;
1054
1055 // Also update the LookupResult...
1056 // FIXME: This should probably go away at some point
1057 Result.clear();
1058 Result.setLookupName(Corrected.getCorrection());
1059 if (FirstDecl)
1060 Result.addDecl(FirstDecl);
1061
1062 // If we found an Objective-C instance variable, let
1063 // LookupInObjCMethod build the appropriate expression to
1064 // reference the ivar.
1065 // FIXME: This is a gross hack.
1066 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1067 DeclResult R =
1068 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1069 if (R.isInvalid())
1071 if (R.isUsable())
1072 return NameClassification::NonType(Ivar);
1073 }
1074
1075 goto Corrected;
1076 }
1077 }
1078
1079 // We failed to correct; just fall through and let the parser deal with it.
1080 Result.suppressDiagnostics();
1082
1084 // We performed name lookup into the current instantiation, and there were
1085 // dependent bases, so we treat this result the same way as any other
1086 // dependent nested-name-specifier.
1087
1088 // C++ [temp.res]p2:
1089 // A name used in a template declaration or definition and that is
1090 // dependent on a template-parameter is assumed not to name a type
1091 // unless the applicable name lookup finds a type name or the name is
1092 // qualified by the keyword typename.
1093 //
1094 // FIXME: If the next token is '<', we might want to ask the parser to
1095 // perform some heroics to see if we actually have a
1096 // template-argument-list, which would indicate a missing 'template'
1097 // keyword here.
1099 }
1100
1104 break;
1105
1107 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1108 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1109 /*AllowDependent=*/false)) {
1110 // C++ [temp.local]p3:
1111 // A lookup that finds an injected-class-name (10.2) can result in an
1112 // ambiguity in certain cases (for example, if it is found in more than
1113 // one base class). If all of the injected-class-names that are found
1114 // refer to specializations of the same class template, and if the name
1115 // is followed by a template-argument-list, the reference refers to the
1116 // class template itself and not a specialization thereof, and is not
1117 // ambiguous.
1118 //
1119 // This filtering can make an ambiguous result into an unambiguous one,
1120 // so try again after filtering out template names.
1122 if (!Result.isAmbiguous()) {
1123 IsFilteredTemplateName = true;
1124 break;
1125 }
1126 }
1127
1128 // Diagnose the ambiguity and return an error.
1130 }
1131
1132 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1133 (IsFilteredTemplateName ||
1135 Result, /*AllowFunctionTemplates=*/true,
1136 /*AllowDependent=*/false,
1137 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1139 // C++ [temp.names]p3:
1140 // After name lookup (3.4) finds that a name is a template-name or that
1141 // an operator-function-id or a literal- operator-id refers to a set of
1142 // overloaded functions any member of which is a function template if
1143 // this is followed by a <, the < is always taken as the delimiter of a
1144 // template-argument-list and never as the less-than operator.
1145 // C++2a [temp.names]p2:
1146 // A name is also considered to refer to a template if it is an
1147 // unqualified-id followed by a < and name lookup finds either one
1148 // or more functions or finds nothing.
1149 if (!IsFilteredTemplateName)
1151
1152 bool IsFunctionTemplate;
1153 bool IsVarTemplate;
1155 if (Result.end() - Result.begin() > 1) {
1156 IsFunctionTemplate = true;
1157 Template = Context.getOverloadedTemplateName(Result.begin(),
1158 Result.end());
1159 } else if (!Result.empty()) {
1161 *Result.begin(), /*AllowFunctionTemplates=*/true,
1162 /*AllowDependent=*/false));
1163 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1164 IsVarTemplate = isa<VarTemplateDecl>(TD);
1165
1166 UsingShadowDecl *FoundUsingShadow =
1167 dyn_cast<UsingShadowDecl>(*Result.begin());
1168 assert(!FoundUsingShadow ||
1169 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1170 Template = Context.getQualifiedTemplateName(
1171 SS.getScopeRep(),
1172 /*TemplateKeyword=*/false,
1173 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1174 } else {
1175 // All results were non-template functions. This is a function template
1176 // name.
1177 IsFunctionTemplate = true;
1178 Template = Context.getAssumedTemplateName(NameInfo.getName());
1179 }
1180
1181 if (IsFunctionTemplate) {
1182 // Function templates always go through overload resolution, at which
1183 // point we'll perform the various checks (e.g., accessibility) we need
1184 // to based on which function we selected.
1185 Result.suppressDiagnostics();
1186
1188 }
1189
1190 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1192 }
1193
1194 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1195 QualType T;
1196 TypeLocBuilder TLB;
1197 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1198 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1199 USD);
1200 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1201 SS.getWithLocInContext(Context), NameLoc);
1202 } else {
1203 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1204 Type);
1205 if (isa<TagType>(T)) {
1206 auto TTL = TLB.push<TagTypeLoc>(T);
1208 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1209 TTL.setNameLoc(NameLoc);
1210 } else if (isa<TypedefType>(T)) {
1211 TLB.push<TypedefTypeLoc>(T).set(
1212 /*ElaboratedKeywordLoc=*/SourceLocation(),
1213 SS.getWithLocInContext(Context), NameLoc);
1214 } else if (isa<UnresolvedUsingType>(T)) {
1215 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1216 /*ElaboratedKeywordLoc=*/SourceLocation(),
1217 SS.getWithLocInContext(Context), NameLoc);
1218 } else {
1219 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1220 }
1221 }
1223 };
1224
1225 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1226 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1227 DiagnoseUseOfDecl(Type, NameLoc);
1228 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1229 return BuildTypeFor(Type, *Result.begin());
1230 }
1231
1232 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1233 if (!Class) {
1234 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1235 if (ObjCCompatibleAliasDecl *Alias =
1236 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1237 Class = Alias->getClassInterface();
1238 }
1239
1240 if (Class) {
1241 DiagnoseUseOfDecl(Class, NameLoc);
1242
1243 if (NextToken.is(tok::period)) {
1244 // Interface. <something> is parsed as a property reference expression.
1245 // Just return "unknown" as a fall-through for now.
1246 Result.suppressDiagnostics();
1248 }
1249
1250 QualType T = Context.getObjCInterfaceType(Class);
1251 return ParsedType::make(T);
1252 }
1253
1255 // We want to preserve the UsingShadowDecl for concepts.
1256 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1260 }
1261
1262 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1263 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1265 }
1266
1267 // We can have a type template here if we're classifying a template argument.
1272
1273 // Check for a tag type hidden by a non-type decl in a few cases where it
1274 // seems likely a type is wanted instead of the non-type that was found.
1275 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1276 if ((NextToken.is(tok::identifier) ||
1277 (NextIsOp &&
1278 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1279 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1280 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1281 DiagnoseUseOfDecl(Type, NameLoc);
1282 return BuildTypeFor(Type, *Result.begin());
1283 }
1284
1285 // If we already know which single declaration is referenced, just annotate
1286 // that declaration directly. Defer resolving even non-overloaded class
1287 // member accesses, as we need to defer certain access checks until we know
1288 // the context.
1289 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1290 if (Result.isSingleResult() && !ADL &&
1291 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1292 return NameClassification::NonType(Result.getRepresentativeDecl());
1293
1294 // Otherwise, this is an overload set that we will need to resolve later.
1295 Result.suppressDiagnostics();
1297 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1298 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1299 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1300}
1301
1304 SourceLocation NameLoc) {
1305 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1306 CXXScopeSpec SS;
1307 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1308 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1309}
1310
1313 IdentifierInfo *Name,
1314 SourceLocation NameLoc,
1315 bool IsAddressOfOperand) {
1316 DeclarationNameInfo NameInfo(Name, NameLoc);
1317 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1318 NameInfo, IsAddressOfOperand,
1319 /*TemplateArgs=*/nullptr);
1320}
1321
1324 SourceLocation NameLoc,
1325 const Token &NextToken) {
1326 if (getCurMethodDecl() && SS.isEmpty())
1327 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1328 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1329
1330 // Reconstruct the lookup result.
1331 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1332 Result.addDecl(Found);
1333 Result.resolveKind();
1334
1335 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1336 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1337}
1338
1340 // For an implicit class member access, transform the result into a member
1341 // access expression if necessary.
1342 auto *ULE = cast<UnresolvedLookupExpr>(E);
1343 if ((*ULE->decls_begin())->isCXXClassMember()) {
1344 CXXScopeSpec SS;
1345 SS.Adopt(ULE->getQualifierLoc());
1346
1347 // Reconstruct the lookup result.
1348 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1350 Result.setNamingClass(ULE->getNamingClass());
1351 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1352 Result.addDecl(*I, I.getAccess());
1353 Result.resolveKind();
1355 nullptr, S);
1356 }
1357
1358 // Otherwise, this is already in the form we needed, and no further checks
1359 // are necessary.
1360 return ULE;
1361}
1362
1382
1384 assert(DC->getLexicalParent() == CurContext &&
1385 "The next DeclContext should be lexically contained in the current one.");
1386 CurContext = DC;
1387 if (S)
1388 S->setEntity(DC);
1389}
1390
1392 assert(CurContext && "DeclContext imbalance!");
1393
1394 CurContext = CurContext->getLexicalParent();
1395 assert(CurContext && "Popped translation unit!");
1396}
1397
1399 Decl *D) {
1400 // Unlike PushDeclContext, the context to which we return is not necessarily
1401 // the containing DC of TD, because the new context will be some pre-existing
1402 // TagDecl definition instead of a fresh one.
1403 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1404 CurContext = cast<TagDecl>(D)->getDefinition();
1405 assert(CurContext && "skipping definition of undefined tag");
1406 // Start lookups from the parent of the current context; we don't want to look
1407 // into the pre-existing complete definition.
1408 S->setEntity(CurContext->getLookupParent());
1409 return Result;
1410}
1411
1415
1417 // C++0x [basic.lookup.unqual]p13:
1418 // A name used in the definition of a static data member of class
1419 // X (after the qualified-id of the static member) is looked up as
1420 // if the name was used in a member function of X.
1421 // C++0x [basic.lookup.unqual]p14:
1422 // If a variable member of a namespace is defined outside of the
1423 // scope of its namespace then any name used in the definition of
1424 // the variable member (after the declarator-id) is looked up as
1425 // if the definition of the variable member occurred in its
1426 // namespace.
1427 // Both of these imply that we should push a scope whose context
1428 // is the semantic context of the declaration. We can't use
1429 // PushDeclContext here because that context is not necessarily
1430 // lexically contained in the current context. Fortunately,
1431 // the containing scope should have the appropriate information.
1432
1433 assert(!S->getEntity() && "scope already has entity");
1434
1435#ifndef NDEBUG
1436 Scope *Ancestor = S->getParent();
1437 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1438 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1439#endif
1440
1441 CurContext = DC;
1442 S->setEntity(DC);
1443
1444 if (S->getParent()->isTemplateParamScope()) {
1445 // Also set the corresponding entities for all immediately-enclosing
1446 // template parameter scopes.
1448 }
1449}
1450
1452 assert(S->getEntity() == CurContext && "Context imbalance!");
1453
1454 // Switch back to the lexical context. The safety of this is
1455 // enforced by an assert in EnterDeclaratorContext.
1456 Scope *Ancestor = S->getParent();
1457 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1458 CurContext = Ancestor->getEntity();
1459
1460 // We don't need to do anything with the scope, which is going to
1461 // disappear.
1462}
1463
1465 assert(S->isTemplateParamScope() &&
1466 "expected to be initializing a template parameter scope");
1467
1468 // C++20 [temp.local]p7:
1469 // In the definition of a member of a class template that appears outside
1470 // of the class template definition, the name of a member of the class
1471 // template hides the name of a template-parameter of any enclosing class
1472 // templates (but not a template-parameter of the member if the member is a
1473 // class or function template).
1474 // C++20 [temp.local]p9:
1475 // In the definition of a class template or in the definition of a member
1476 // of such a template that appears outside of the template definition, for
1477 // each non-dependent base class (13.8.2.1), if the name of the base class
1478 // or the name of a member of the base class is the same as the name of a
1479 // template-parameter, the base class name or member name hides the
1480 // template-parameter name (6.4.10).
1481 //
1482 // This means that a template parameter scope should be searched immediately
1483 // after searching the DeclContext for which it is a template parameter
1484 // scope. For example, for
1485 // template<typename T> template<typename U> template<typename V>
1486 // void N::A<T>::B<U>::f(...)
1487 // we search V then B<U> (and base classes) then U then A<T> (and base
1488 // classes) then T then N then ::.
1489 unsigned ScopeDepth = getTemplateDepth(S);
1490 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1491 DeclContext *SearchDCAfterScope = DC;
1492 for (; DC; DC = DC->getLookupParent()) {
1493 if (const TemplateParameterList *TPL =
1494 cast<Decl>(DC)->getDescribedTemplateParams()) {
1495 unsigned DCDepth = TPL->getDepth() + 1;
1496 if (DCDepth > ScopeDepth)
1497 continue;
1498 if (ScopeDepth == DCDepth)
1499 SearchDCAfterScope = DC = DC->getLookupParent();
1500 break;
1501 }
1502 }
1503 S->setLookupEntity(SearchDCAfterScope);
1504 }
1505}
1506
1508 ArrayRef<ParmVarDecl *> Params) {
1509 for (ParmVarDecl *Param : Params)
1510 if (Param->getIdentifier()) {
1511 S->AddDecl(Param);
1512 IdResolver.AddDecl(Param);
1513 }
1514}
1515
1517 ArrayRef<ParmVarDecl *> Params) {
1518 // Remove in reverse so each name is the most recent one when it is removed.
1519 for (ParmVarDecl *Param : llvm::reverse(Params))
1520 if (Param->getIdentifier()) {
1521 IdResolver.RemoveDecl(Param);
1522 S->RemoveDecl(Param);
1523 }
1524}
1525
1527 // We assume that the caller has already called
1528 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1529 FunctionDecl *FD = D->getAsFunction();
1530 if (!FD)
1531 return;
1532
1533 // Same implementation as PushDeclContext, but enters the context
1534 // from the lexical parent, rather than the top-level class.
1535 assert(CurContext == FD->getLexicalParent() &&
1536 "The next DeclContext should be lexically contained in the current one.");
1537 CurContext = FD;
1539
1541}
1542
1544 // Same implementation as PopDeclContext, but returns to the lexical parent,
1545 // rather than the top-level class.
1546 assert(CurContext && "DeclContext imbalance!");
1547 CurContext = CurContext->getLexicalParent();
1548 assert(CurContext && "Popped translation unit!");
1549}
1550
1551/// Determine whether overloading is allowed for a new function
1552/// declaration considering prior declarations of the same name.
1553///
1554/// This routine determines whether overloading is possible, not
1555/// whether a new declaration actually overloads a previous one.
1556/// It will return true in C++ (where overloads are always permitted)
1557/// or, as a C extension, when either the new declaration or a
1558/// previous one is declared with the 'overloadable' attribute.
1560 ASTContext &Context,
1561 const FunctionDecl *New) {
1562 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1563 return true;
1564
1565 // Multiversion function declarations are not overloads in the
1566 // usual sense of that term, but lookup will report that an
1567 // overload set was found if more than one multiversion function
1568 // declaration is present for the same name. It is therefore
1569 // inadequate to assume that some prior declaration(s) had
1570 // the overloadable attribute; checking is required. Since one
1571 // declaration is permitted to omit the attribute, it is necessary
1572 // to check at least two; hence the 'any_of' check below. Note that
1573 // the overloadable attribute is implicitly added to declarations
1574 // that were required to have it but did not.
1575 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1576 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1577 return ND->hasAttr<OverloadableAttr>();
1578 });
1579 } else if (Previous.getResultKind() == LookupResultKind::Found)
1580 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1581
1582 return false;
1583}
1584
1585void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1586 // Move up the scope chain until we find the nearest enclosing
1587 // non-transparent context. The declaration will be introduced into this
1588 // scope.
1589 while (S->getEntity() && S->getEntity()->isTransparentContext())
1590 S = S->getParent();
1591
1592 // Add scoped declarations into their context, so that they can be
1593 // found later. Declarations without a context won't be inserted
1594 // into any context.
1595 if (AddToContext)
1596 CurContext->addDecl(D);
1597
1598 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1599 // are function-local declarations.
1600 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1601 if (!S->getFnParent())
1602 return;
1603
1604 // Even inside a function, an out-of-line definition of a type that is
1605 // nested inside a local class must not be pushed into the enclosing
1606 // function scope. For example:
1607 //
1608 // class A { public: class B; };
1609 // class A::B {}; // out-of-line definition inside the function
1610 // B b; // must fail - only A::B is valid
1611 // Wrapper{B{}} // must also fail
1612 //
1613 // Per C++ scoping rules only the qualified form A::B is accessible.
1614 // Without this guard, PushOnScopeChains would add B to the function's
1615 // local scope, making it findable via unqualified lookup, which is
1616 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1617 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1618 // of a local class being defined out-of-line.
1620 return;
1621 }
1622
1623 // Template instantiations should also not be pushed into scope.
1624 if (isa<FunctionDecl>(D) &&
1625 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1626 return;
1627
1628 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1629 S->AddDecl(D);
1630 return;
1631 }
1632 // If this replaces anything in the current scope,
1634 IEnd = IdResolver.end();
1635 for (; I != IEnd; ++I) {
1636 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1637 S->RemoveDecl(*I);
1638 IdResolver.RemoveDecl(*I);
1639
1640 // Should only need to replace one decl.
1641 break;
1642 }
1643 }
1644
1645 S->AddDecl(D);
1646
1647 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1648 // Implicitly-generated labels may end up getting generated in an order that
1649 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1650 // the label at the appropriate place in the identifier chain.
1651 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1652 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1653 if (IDC == CurContext) {
1654 if (!S->isDeclScope(*I))
1655 continue;
1656 } else if (IDC->Encloses(CurContext))
1657 break;
1658 }
1659
1660 IdResolver.InsertDeclAfter(I, D);
1661 } else {
1662 IdResolver.AddDecl(D);
1663 }
1665}
1666
1668 bool AllowInlineNamespace) const {
1669 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1670}
1671
1673 bool AllowInlineNamespace) const {
1674 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1675 return true;
1676
1677 if (auto *Shadow = dyn_cast<UsingShadowDecl>(D))
1678 return isDeclInScope(Shadow->getTargetDecl(), Ctx, S, AllowInlineNamespace);
1679
1680 return false;
1681}
1682
1684 DeclContext *TargetDC = DC->getPrimaryContext();
1685 do {
1686 if (DeclContext *ScopeDC = S->getEntity())
1687 if (ScopeDC->getPrimaryContext() == TargetDC)
1688 return S;
1689 } while ((S = S->getParent()));
1690
1691 return nullptr;
1692}
1693
1695 DeclContext*,
1696 ASTContext&);
1697
1699 bool ConsiderLinkage,
1700 bool AllowInlineNamespace) {
1701 LookupResult::Filter F = R.makeFilter();
1702 while (F.hasNext()) {
1703 NamedDecl *D = F.next();
1704
1705 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1706 continue;
1707
1708 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1709 continue;
1710
1711 F.erase();
1712 }
1713
1714 F.done();
1715}
1716
1718 if (auto *VD = dyn_cast<VarDecl>(D))
1719 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1720 if (auto *FD = dyn_cast<FunctionDecl>(D))
1721 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1722 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1723 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1724
1725 return false;
1726}
1727
1729 // [module.interface]p7:
1730 // A declaration is attached to a module as follows:
1731 // - If the declaration is a non-dependent friend declaration that nominates a
1732 // function with a declarator-id that is a qualified-id or template-id or that
1733 // nominates a class other than with an elaborated-type-specifier with neither
1734 // a nested-name-specifier nor a simple-template-id, it is attached to the
1735 // module to which the friend is attached ([basic.link]).
1736 if (New->getFriendObjectKind() &&
1737 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1738 New->setLocalOwningModule(Old->getOwningModule());
1740 return false;
1741 }
1742
1743 // Although we have questions for the module ownership of implicit
1744 // instantiations, it should be sure that we shouldn't diagnose the
1745 // redeclaration of incorrect module ownership for different implicit
1746 // instantiations in different modules. We will diagnose the redeclaration of
1747 // incorrect module ownership for the template itself.
1749 return false;
1750
1751 Module *NewM = New->getOwningModule();
1752 Module *OldM = Old->getOwningModule();
1753
1754 if (NewM && NewM->isPrivateModule())
1755 NewM = NewM->Parent;
1756 if (OldM && OldM->isPrivateModule())
1757 OldM = OldM->Parent;
1758
1759 if (NewM == OldM)
1760 return false;
1761
1762 if (NewM && OldM) {
1763 // A module implementation unit has visibility of the decls in its
1764 // implicitly imported interface.
1765 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1766 return false;
1767
1768 // Partitions are part of the module, but a partition could import another
1769 // module, so verify that the PMIs agree.
1770 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1771 getASTContext().isInSameModule(NewM, OldM))
1772 return false;
1773 }
1774
1775 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1776 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1777 if (NewIsModuleInterface || OldIsModuleInterface) {
1778 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1779 // if a declaration of D [...] appears in the purview of a module, all
1780 // other such declarations shall appear in the purview of the same module
1781 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1782 << New
1783 << NewIsModuleInterface
1784 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1785 << OldIsModuleInterface
1786 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1787 Diag(Old->getLocation(), diag::note_previous_declaration);
1788 New->setInvalidDecl();
1789 return true;
1790 }
1791
1792 return false;
1793}
1794
1796 // [module.interface]p1:
1797 // An export-declaration shall inhabit a namespace scope.
1798 //
1799 // So it is meaningless to talk about redeclaration which is not at namespace
1800 // scope.
1801 if (!New->getLexicalDeclContext()
1802 ->getNonTransparentContext()
1803 ->isFileContext() ||
1804 !Old->getLexicalDeclContext()
1806 ->isFileContext())
1807 return false;
1808
1809 bool IsNewExported = New->isInExportDeclContext();
1810 bool IsOldExported = Old->isInExportDeclContext();
1811
1812 // It should be irrevelant if both of them are not exported.
1813 if (!IsNewExported && !IsOldExported)
1814 return false;
1815
1816 if (IsOldExported)
1817 return false;
1818
1819 // If the Old declaration are not attached to named modules
1820 // and the New declaration are attached to global module.
1821 // It should be fine to allow the export since it doesn't change
1822 // the linkage of declarations. See
1823 // https://github.com/llvm/llvm-project/issues/98583 for details.
1824 if (!Old->isInNamedModule() && New->getOwningModule() &&
1825 New->getOwningModule()->isImplicitGlobalModule())
1826 return false;
1827
1828 assert(IsNewExported);
1829
1830 auto Lk = Old->getFormalLinkage();
1831 int S = 0;
1832 if (Lk == Linkage::Internal)
1833 S = 1;
1834 else if (Lk == Linkage::Module)
1835 S = 2;
1836 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1837 Diag(Old->getLocation(), diag::note_previous_declaration);
1838 return true;
1839}
1840
1843 return true;
1844
1846 return true;
1847
1848 return false;
1849}
1850
1852 const NamedDecl *Old) const {
1853 assert(getASTContext().isSameEntity(New, Old) &&
1854 "New and Old are not the same definition, we should diagnostic it "
1855 "immediately instead of checking it.");
1856 assert(const_cast<Sema *>(this)->isReachable(New) &&
1857 const_cast<Sema *>(this)->isReachable(Old) &&
1858 "We shouldn't see unreachable definitions here.");
1859
1860 Module *NewM = New->getOwningModule();
1861 Module *OldM = Old->getOwningModule();
1862
1863 // We only checks for named modules here. The header like modules is skipped.
1864 // FIXME: This is not right if we import the header like modules in the module
1865 // purview.
1866 //
1867 // For example, assuming "header.h" provides definition for `D`.
1868 // ```C++
1869 // //--- M.cppm
1870 // export module M;
1871 // import "header.h"; // or #include "header.h" but import it by clang modules
1872 // actually.
1873 //
1874 // //--- Use.cpp
1875 // import M;
1876 // import "header.h"; // or uses clang modules.
1877 // ```
1878 //
1879 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1880 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1881 // reject it. But the current implementation couldn't detect the case since we
1882 // don't record the information about the importee modules.
1883 //
1884 // But this might not be painful in practice. Since the design of C++20 Named
1885 // Modules suggests us to use headers in global module fragment instead of
1886 // module purview.
1887 if (NewM && NewM->isHeaderLikeModule())
1888 NewM = nullptr;
1889 if (OldM && OldM->isHeaderLikeModule())
1890 OldM = nullptr;
1891
1892 if (!NewM && !OldM)
1893 return true;
1894
1895 // [basic.def.odr]p14.3
1896 // Each such definition shall not be attached to a named module
1897 // ([module.unit]).
1898 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1899 return true;
1900
1901 // Then New and Old lives in the same TU if their share one same module unit.
1902 if (NewM)
1903 NewM = NewM->getTopLevelModule();
1904 if (OldM)
1905 OldM = OldM->getTopLevelModule();
1906 return OldM == NewM;
1907}
1908
1910 if (D->getDeclContext()->isFileContext())
1911 return false;
1912
1913 return isa<UsingShadowDecl>(D) ||
1916}
1917
1918/// Removes using shadow declarations not at class scope from the lookup
1919/// results.
1921 LookupResult::Filter F = R.makeFilter();
1922 while (F.hasNext())
1924 F.erase();
1925
1926 F.done();
1927}
1928
1929/// Check for this common pattern:
1930/// @code
1931/// class S {
1932/// S(const S&); // DO NOT IMPLEMENT
1933/// void operator=(const S&); // DO NOT IMPLEMENT
1934/// };
1935/// @endcode
1937 // FIXME: Should check for private access too but access is set after we get
1938 // the decl here.
1940 return false;
1941
1942 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1943 return CD->isCopyConstructor();
1944 return D->isCopyAssignmentOperator();
1945}
1946
1947bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1948 const DeclContext *DC = D->getDeclContext();
1949 while (!DC->isTranslationUnit()) {
1950 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1951 if (!RD->hasNameForLinkage())
1952 return true;
1953 }
1954 DC = DC->getParent();
1955 }
1956
1957 return !D->isExternallyVisible();
1958}
1959
1961 assert(D);
1962
1963 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1964 return false;
1965
1966 // Ignore all entities declared within templates, and out-of-line definitions
1967 // of members of class templates.
1968 if (D->getDeclContext()->isDependentContext() ||
1970 return false;
1971
1972 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1973 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1974 return false;
1975 // A non-out-of-line declaration of a member specialization was implicitly
1976 // instantiated; it's the out-of-line declaration that we're interested in.
1977 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1978 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1979 return false;
1980
1981 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1982 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1983 return false;
1984 } else {
1985 // 'static inline' functions are defined in headers; don't warn.
1986 if (FD->isInlined() && !isMainFileLoc(FD->getLocation()))
1987 return false;
1988 }
1989
1990 if (FD->doesThisDeclarationHaveABody() &&
1991 Context.DeclMustBeEmitted(FD))
1992 return false;
1993 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1994 // Constants and utility variables are defined in headers with internal
1995 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1996 // like "inline".)
1997 if (!isMainFileLoc(VD->getLocation()))
1998 return false;
1999
2000 if (Context.DeclMustBeEmitted(VD))
2001 return false;
2002
2003 if (VD->isStaticDataMember() &&
2004 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2005 return false;
2006 if (VD->isStaticDataMember() &&
2007 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2008 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
2009 return false;
2010
2011 if (VD->isInline() && !isMainFileLoc(VD->getLocation()))
2012 return false;
2013 } else {
2014 return false;
2015 }
2016
2017 // Only warn for unused decls internal to the translation unit.
2018 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
2019 // for inline functions defined in the main source file, for instance.
2020 return mightHaveNonExternalLinkage(D);
2021}
2022
2024 if (!D)
2025 return;
2026
2027 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2028 const FunctionDecl *First = FD->getFirstDecl();
2030 return; // First should already be in the vector.
2031 }
2032
2033 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2034 const VarDecl *First = VD->getFirstDecl();
2036 return; // First should already be in the vector.
2037 }
2038
2040 UnusedFileScopedDecls.push_back(D);
2041}
2042
2043static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2044 const NamedDecl *D) {
2045 if (D->isInvalidDecl())
2046 return false;
2047
2048 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2049 // For a decomposition declaration, warn if none of the bindings are
2050 // referenced, instead of if the variable itself is referenced (which
2051 // it is, by the bindings' expressions).
2052 bool IsAllIgnored = true;
2053 for (const auto *BD : DD->bindings()) {
2054 if (BD->isReferenced())
2055 return false;
2056 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2057 BD->hasAttr<UnusedAttr>());
2058 }
2059 if (IsAllIgnored)
2060 return false;
2061 } else if (!D->getDeclName()) {
2062 return false;
2063 } else if (D->isReferenced() || D->isUsed()) {
2064 return false;
2065 }
2066
2067 if (D->isPlaceholderVar(LangOpts))
2068 return false;
2069
2070 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2071 D->hasAttr<CleanupAttr>())
2072 return false;
2073
2074 if (isa<LabelDecl>(D))
2075 return true;
2076
2077 // Except for labels, we only care about unused decls that are local to
2078 // functions.
2079 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2080 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2081 // For dependent types, the diagnostic is deferred.
2082 WithinFunction =
2083 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2084 if (!WithinFunction)
2085 return false;
2086
2087 if (isa<TypedefNameDecl>(D))
2088 return true;
2089
2090 // White-list anything that isn't a local variable.
2092 return false;
2093
2094 // Types of valid local variables should be complete, so this should succeed.
2095 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2096
2097 const Expr *Init = VD->getInit();
2098 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2099 Init = Cleanups->getSubExpr();
2100
2101 const auto *Ty = VD->getType().getTypePtr();
2102
2103 // Only look at the outermost level of typedef.
2104 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2105 // Allow anything marked with __attribute__((unused)).
2106 if (TT->getDecl()->hasAttr<UnusedAttr>())
2107 return false;
2108 }
2109
2110 // Warn for reference variables whose initializtion performs lifetime
2111 // extension.
2112 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2113 MTE && MTE->getExtendingDecl()) {
2114 Ty = VD->getType().getNonReferenceType().getTypePtr();
2115 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2116 }
2117
2118 // If we failed to complete the type for some reason, or if the type is
2119 // dependent, don't diagnose the variable.
2120 if (Ty->isIncompleteType() || Ty->isDependentType())
2121 return false;
2122
2123 // Look at the element type to ensure that the warning behaviour is
2124 // consistent for both scalars and arrays.
2125 Ty = Ty->getBaseElementTypeUnsafe();
2126
2127 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2128 if (Tag->hasAttr<UnusedAttr>())
2129 return false;
2130
2131 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2132 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2133 return false;
2134
2135 if (Init) {
2136 const auto *Construct =
2137 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2138 if (Construct && !Construct->isElidable()) {
2139 const CXXConstructorDecl *CD = Construct->getConstructor();
2140 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2141 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2142 return false;
2143 }
2144
2145 // Suppress the warning if we don't know how this is constructed, and
2146 // it could possibly be non-trivial constructor.
2147 if (Init->isTypeDependent()) {
2148 for (const CXXConstructorDecl *Ctor : RD->ctors())
2149 if (!Ctor->isTrivial())
2150 return false;
2151 }
2152
2153 // Suppress the warning if the constructor is unresolved because
2154 // its arguments are dependent.
2156 return false;
2157 }
2158 }
2159 }
2160
2161 // TODO: __attribute__((unused)) templates?
2162 }
2163
2164 return true;
2165}
2166
2168 FixItHint &Hint) {
2169 if (isa<LabelDecl>(D)) {
2171 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2172 /*SkipTrailingWhitespaceAndNewline=*/false);
2173 if (AfterColon.isInvalid())
2174 return;
2176 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2177 }
2178}
2179
2182 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2183}
2184
2186 DiagReceiverTy DiagReceiver) {
2187 if (D->isDependentType())
2188 return;
2189
2190 for (auto *TmpD : D->decls()) {
2191 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2192 DiagnoseUnusedDecl(T, DiagReceiver);
2193 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2194 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2195 }
2196}
2197
2200 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2201}
2202
2205 return;
2206
2207 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2208 // typedefs can be referenced later on, so the diagnostics are emitted
2209 // at end-of-translation-unit.
2211 return;
2212 }
2213
2214 FixItHint Hint;
2216
2217 unsigned DiagID;
2218 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2219 DiagID = diag::warn_unused_exception_param;
2220 else if (isa<LabelDecl>(D))
2221 DiagID = diag::warn_unused_label;
2222 else
2223 DiagID = diag::warn_unused_variable;
2224
2225 SourceLocation DiagLoc = D->getLocation();
2226 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2227}
2228
2230 DiagReceiverTy DiagReceiver) {
2231 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2232 // it's not really unused.
2233 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2234 return;
2235
2236 // In C++, `_` variables behave as if they were maybe_unused
2237 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2238 return;
2239
2240 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2241
2242 if (Ty->isReferenceType() || Ty->isDependentType())
2243 return;
2244
2245 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2246 if (Tag->hasAttr<UnusedAttr>())
2247 return;
2248 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2249 // mimic gcc's behavior.
2250 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2251 RD && !RD->hasAttr<WarnUnusedAttr>())
2252 return;
2253 }
2254
2255 // Don't warn on volatile file-scope variables. They are visible beyond their
2256 // declaring function and writes to them could be observable side effects.
2257 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2258 return;
2259
2260 // Don't warn about __block Objective-C pointer variables, as they might
2261 // be assigned in the block but not used elsewhere for the purpose of lifetime
2262 // extension.
2263 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2264 return;
2265
2266 // Don't warn about Objective-C pointer variables with precise lifetime
2267 // semantics; they can be used to ensure ARC releases the object at a known
2268 // time, which may mean assignment but no other references.
2269 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2270 return;
2271
2272 auto iter = RefsMinusAssignments.find(VD->getCanonicalDecl());
2273 if (iter == RefsMinusAssignments.end())
2274 return;
2275
2276 assert(iter->getSecond() >= 0 &&
2277 "Found a negative number of references to a VarDecl");
2278 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2279 // Assume the given VarDecl is "used" if its ref count stored in
2280 // `RefMinusAssignments` is positive, with one exception.
2281 //
2282 // For a C++ variable whose decl (with initializer) entirely consist the
2283 // condition expression of a if/while/for construct,
2284 // Clang creates a DeclRefExpr for the condition expression rather than a
2285 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2286 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2287 // used in the body of the if/while/for construct.
2288 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2289 if (!UnusedCXXCondDecl)
2290 return;
2291 }
2292
2293 unsigned DiagID;
2294 if (isa<ParmVarDecl>(VD))
2295 DiagID = diag::warn_unused_but_set_parameter;
2296 else if (VD->isFileVarDecl())
2297 DiagID = diag::warn_unused_but_set_global;
2298 else
2299 DiagID = diag::warn_unused_but_set_variable;
2300 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2301}
2302
2304 Sema::DiagReceiverTy DiagReceiver) {
2305 // Verify that we have no forward references left. If so, there was a goto
2306 // or address of a label taken, but no definition of it. Label fwd
2307 // definitions are indicated with a null substmt which is also not a resolved
2308 // MS inline assembly label name.
2309 bool Diagnose = false;
2310 if (L->isMSAsmLabel())
2311 Diagnose = !L->isResolvedMSAsmLabel();
2312 else
2313 Diagnose = L->getStmt() == nullptr;
2314 if (Diagnose)
2315 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2316 << L);
2317}
2318
2320 S->applyNRVO();
2321
2322 if (S->decl_empty()) return;
2324 "Scope shouldn't contain decls!");
2325
2326 /// We visit the decls in non-deterministic order, but we want diagnostics
2327 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2328 /// and sort the diagnostics before emitting them, after we visited all decls.
2329 struct LocAndDiag {
2330 SourceLocation Loc;
2331 std::optional<SourceLocation> PreviousDeclLoc;
2333 };
2335 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2336 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2337 };
2338 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2339 SourceLocation PreviousDeclLoc,
2340 PartialDiagnostic PD) {
2341 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2342 };
2343
2344 for (auto *TmpD : S->decls()) {
2345 assert(TmpD && "This decl didn't get pushed??");
2346
2347 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2348 NamedDecl *D = cast<NamedDecl>(TmpD);
2349
2350 // Diagnose unused variables in this scope.
2352 DiagnoseUnusedDecl(D, addDiag);
2353 if (const auto *RD = dyn_cast<RecordDecl>(D))
2354 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2355 // Wait until end of TU to diagnose internal linkage file vars.
2356 if (auto *VD = dyn_cast<VarDecl>(D);
2357 VD && !VD->isInternalLinkageFileVar()) {
2358 DiagnoseUnusedButSetDecl(VD, addDiag);
2359 RefsMinusAssignments.erase(VD->getCanonicalDecl());
2360 }
2361 }
2362
2363 if (!D->getDeclName()) continue;
2364
2365 // If this was a forward reference to a label, verify it was defined.
2366 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2367 CheckPoppedLabel(LD, *this, addDiag);
2368
2369 // Partial translation units that are created in incremental processing must
2370 // not clean up the IdResolver because PTUs should take into account the
2371 // declarations that came from previous PTUs.
2372 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2374 IdResolver.RemoveDecl(D);
2375
2376 // Warn on it if we are shadowing a declaration.
2377 auto ShadowI = ShadowingDecls.find(D);
2378 if (ShadowI != ShadowingDecls.end()) {
2379 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2380 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2381 PDiag(diag::warn_ctor_parm_shadows_field)
2382 << D << FD << FD->getParent());
2383 }
2384 ShadowingDecls.erase(ShadowI);
2385 }
2386 }
2387
2388 llvm::sort(DeclDiags,
2389 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2390 // The particular order for diagnostics is not important, as long
2391 // as the order is deterministic. Using the raw location is going
2392 // to generally be in source order unless there are macro
2393 // expansions involved.
2394 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2395 });
2396 for (const LocAndDiag &D : DeclDiags) {
2397 Diag(D.Loc, D.PD);
2398 if (D.PreviousDeclLoc)
2399 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2400 }
2401}
2402
2404 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2405 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2406 (S->isClassScope() && !getLangOpts().CPlusPlus))
2407 S = S->getParent();
2408 return S;
2409}
2410
2411static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2413 switch (Error) {
2415 return "";
2417 return BuiltinInfo.getHeaderName(ID);
2419 return "stdio.h";
2421 return "setjmp.h";
2423 return "ucontext.h";
2424 }
2425 llvm_unreachable("unhandled error kind");
2426}
2427
2429 unsigned ID, SourceLocation Loc) {
2430 DeclContext *Parent = Context.getTranslationUnitDecl();
2431
2432 if (getLangOpts().CPlusPlus) {
2434 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2435 CLinkageDecl->setImplicit();
2436 Parent->addDecl(CLinkageDecl);
2437 Parent = CLinkageDecl;
2438 }
2439
2441 if (Context.BuiltinInfo.isImmediate(ID)) {
2442 assert(getLangOpts().CPlusPlus20 &&
2443 "consteval builtins should only be available in C++20 mode");
2444 ConstexprKind = ConstexprSpecKind::Consteval;
2445 }
2446
2448 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2449 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2450 Type->isFunctionProtoType(), ConstexprKind);
2451 New->setImplicit();
2452 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2453
2454 // Create Decl objects for each parameter, adding them to the
2455 // FunctionDecl.
2456 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2458 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2460 Context, New, SourceLocation(), SourceLocation(), nullptr,
2461 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2462 parm->setScopeInfo(0, i);
2463 Params.push_back(parm);
2464 }
2465 New->setParams(Params);
2466 }
2467
2469 return New;
2470}
2471
2473 Scope *S, bool ForRedeclaration,
2474 SourceLocation Loc) {
2476
2478 QualType R = Context.GetBuiltinType(ID, Error);
2479 if (Error) {
2480 if (!ForRedeclaration)
2481 return nullptr;
2482
2483 // If we have a builtin without an associated type we should not emit a
2484 // warning when we were not able to find a type for it.
2486 Context.BuiltinInfo.allowTypeMismatch(ID))
2487 return nullptr;
2488
2489 // If we could not find a type for setjmp it is because the jmp_buf type was
2490 // not defined prior to the setjmp declaration.
2492 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2493 << Context.BuiltinInfo.getName(ID);
2494 return nullptr;
2495 }
2496
2497 // Generally, we emit a warning that the declaration requires the
2498 // appropriate header.
2499 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2500 << getHeaderName(Context.BuiltinInfo, ID, Error)
2501 << Context.BuiltinInfo.getName(ID);
2502 return nullptr;
2503 }
2504
2505 if (!ForRedeclaration &&
2506 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2507 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2508 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2509 : diag::ext_implicit_lib_function_decl)
2510 << Context.BuiltinInfo.getName(ID) << R;
2511 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2512 Diag(Loc, diag::note_include_header_or_declare)
2513 << Header << Context.BuiltinInfo.getName(ID);
2514 }
2515
2516 if (R.isNull())
2517 return nullptr;
2518
2519 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2521
2522 // TUScope is the translation-unit scope to insert this function into.
2523 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2524 // relate Scopes to DeclContexts, and probably eliminate CurContext
2525 // entirely, but we're not there yet.
2526 DeclContext *SavedContext = CurContext;
2527 CurContext = New->getDeclContext();
2529 CurContext = SavedContext;
2530 return New;
2531}
2532
2533/// Typedef declarations don't have linkage, but they still denote the same
2534/// entity if their types are the same.
2535/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2536/// isSameEntity.
2537static void
2540 // This is only interesting when modules are enabled.
2541 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2542 return;
2543
2544 // Empty sets are uninteresting.
2545 if (Previous.empty())
2546 return;
2547
2548 LookupResult::Filter Filter = Previous.makeFilter();
2549 while (Filter.hasNext()) {
2550 NamedDecl *Old = Filter.next();
2551
2552 // Non-hidden declarations are never ignored.
2553 if (S.isVisible(Old))
2554 continue;
2555
2556 // Declarations of the same entity are not ignored, even if they have
2557 // different linkages.
2558 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2559 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2560 Decl->getUnderlyingType()))
2561 continue;
2562
2563 // If both declarations give a tag declaration a typedef name for linkage
2564 // purposes, then they declare the same entity.
2565 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2566 Decl->getAnonDeclWithTypedefName())
2567 continue;
2568 }
2569
2570 Filter.erase();
2571 }
2572
2573 Filter.done();
2574}
2575
2577 QualType OldType;
2578 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2579 OldType = OldTypedef->getUnderlyingType();
2580 else
2581 OldType = Context.getTypeDeclType(Old);
2582 QualType NewType = New->getUnderlyingType();
2583
2584 if (NewType->isVariablyModifiedType()) {
2585 // Must not redefine a typedef with a variably-modified type.
2586 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2587 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2588 << Kind << NewType;
2589 if (Old->getLocation().isValid())
2590 notePreviousDefinition(Old, New->getLocation());
2591 New->setInvalidDecl();
2592 return true;
2593 }
2594
2595 if (OldType != NewType &&
2596 !OldType->isDependentType() &&
2597 !NewType->isDependentType() &&
2598 !Context.hasSameType(OldType, NewType)) {
2599 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2600 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2601 << Kind << NewType << OldType;
2602 if (Old->getLocation().isValid())
2603 notePreviousDefinition(Old, New->getLocation());
2604 New->setInvalidDecl();
2605 return true;
2606 }
2607 return false;
2608}
2609
2611 LookupResult &OldDecls) {
2612 // If the new decl is known invalid already, don't bother doing any
2613 // merging checks.
2614 if (New->isInvalidDecl()) return;
2615
2616 // Allow multiple definitions for ObjC built-in typedefs.
2617 // FIXME: Verify the underlying types are equivalent!
2618 if (getLangOpts().ObjC) {
2619 const IdentifierInfo *TypeID = New->getIdentifier();
2620 switch (TypeID->getLength()) {
2621 default: break;
2622 case 2:
2623 {
2624 if (!TypeID->isStr("id"))
2625 break;
2626 QualType T = New->getUnderlyingType();
2627 if (!T->isPointerType())
2628 break;
2629 if (!T->isVoidPointerType()) {
2630 QualType PT = T->castAs<PointerType>()->getPointeeType();
2631 if (!PT->isStructureType())
2632 break;
2633 }
2634 Context.setObjCIdRedefinitionType(T);
2635 // Install the built-in type for 'id', ignoring the current definition.
2636 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2637 Context.getObjCIdType());
2638 return;
2639 }
2640 case 5:
2641 if (!TypeID->isStr("Class"))
2642 break;
2643 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2644 // Install the built-in type for 'Class', ignoring the current definition.
2645 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2646 Context.getObjCClassType());
2647 return;
2648 case 3:
2649 if (!TypeID->isStr("SEL"))
2650 break;
2651 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2652 // Install the built-in type for 'SEL', ignoring the current definition.
2653 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2654 Context.getObjCSelType());
2655 return;
2656 }
2657 // Fall through - the typedef name was not a builtin type.
2658 }
2659
2660 // Verify the old decl was also a type.
2661 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2662 if (!Old) {
2663 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2664 << New->getDeclName();
2665
2666 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2667 if (OldD->getLocation().isValid())
2668 notePreviousDefinition(OldD, New->getLocation());
2669
2670 return New->setInvalidDecl();
2671 }
2672
2673 // If the old declaration is invalid, just give up here.
2674 if (Old->isInvalidDecl())
2675 return New->setInvalidDecl();
2676
2677 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2678 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2679 auto *NewTag = New->getAnonDeclWithTypedefName();
2680 NamedDecl *Hidden = nullptr;
2681 if (OldTag && NewTag &&
2682 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2683 !hasVisibleDefinition(OldTag, &Hidden)) {
2684 // There is a definition of this tag, but it is not visible. Use it
2685 // instead of our tag.
2686 if (OldTD->isModed())
2687 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2688 OldTD->getUnderlyingType());
2689 else
2690 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2691
2692 // An anonymous enum is recognized as a redeclaration only when its
2693 // typedef name gets merged, at which point the new enum and its
2694 // enumerators already have a distinct canonical type. Link the enum
2695 // declarations, but also retype the new enumerators because
2696 // setPreviousDecl() does not update QualTypes built before the merge;
2697 // otherwise the merged typedef and its enumerators disagree on the type
2698 // (GH213299).
2699 //
2700 // FIXME: The global module restriction only limits the impact of this
2701 // change; relax it if the issue shows up in other contexts.
2702 if (Module *M = OldTag->getOwningModule(); M && M->isGlobalModule()) {
2703 if (auto *NewEnum = dyn_cast<EnumDecl>(NewTag)) {
2704 if (auto *OldEnum = dyn_cast<EnumDecl>(OldTag)) {
2705 NewEnum->setPreviousDecl(OldEnum);
2706 QualType EnumType = Context.getCanonicalTagType(OldEnum);
2707 for (auto *ECD : NewEnum->enumerators())
2708 ECD->setType(EnumType);
2709 }
2710 }
2711 }
2712
2713 // Make the old tag definition visible.
2715
2717 }
2718 }
2719
2720 // If the typedef types are not identical, reject them in all languages and
2721 // with any extensions enabled.
2722 if (isIncompatibleTypedef(Old, New))
2723 return;
2724
2725 // The types match. Link up the redeclaration chain and merge attributes if
2726 // the old declaration was a typedef.
2727 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2728 New->setPreviousDecl(Typedef);
2730 }
2731
2732 if (getLangOpts().MicrosoftExt)
2733 return;
2734
2735 if (getLangOpts().CPlusPlus) {
2736 // C++ [dcl.typedef]p2:
2737 // In a given non-class scope, a typedef specifier can be used to
2738 // redefine the name of any type declared in that scope to refer
2739 // to the type to which it already refers.
2741 return;
2742
2743 // C++0x [dcl.typedef]p4:
2744 // In a given class scope, a typedef specifier can be used to redefine
2745 // any class-name declared in that scope that is not also a typedef-name
2746 // to refer to the type to which it already refers.
2747 //
2748 // This wording came in via DR424, which was a correction to the
2749 // wording in DR56, which accidentally banned code like:
2750 //
2751 // struct S {
2752 // typedef struct A { } A;
2753 // };
2754 //
2755 // in the C++03 standard. We implement the C++0x semantics, which
2756 // allow the above but disallow
2757 //
2758 // struct S {
2759 // typedef int I;
2760 // typedef int I;
2761 // };
2762 //
2763 // since that was the intent of DR56.
2764 if (!isa<TypedefNameDecl>(Old))
2765 return;
2766
2767 Diag(New->getLocation(), diag::err_redefinition)
2768 << New->getDeclName();
2769 notePreviousDefinition(Old, New->getLocation());
2770 return New->setInvalidDecl();
2771 }
2772
2773 // Modules always permit redefinition of typedefs, as does C11.
2774 if (getLangOpts().Modules || getLangOpts().C11)
2775 return;
2776
2777 // If we have a redefinition of a typedef in C, emit a warning. This warning
2778 // is normally mapped to an error, but can be controlled with
2779 // -Wtypedef-redefinition. If either the original or the redefinition is
2780 // in a system header, don't emit this for compatibility with GCC.
2781 if (getDiagnostics().getSuppressSystemWarnings() &&
2782 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2783 (Old->isImplicit() ||
2784 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2785 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2786 return;
2787
2788 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2789 << New->getDeclName();
2790 notePreviousDefinition(Old, New->getLocation());
2791}
2792
2794 // If this was an unscoped enumeration, yank all of its enumerators
2795 // out of the scope.
2796 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2797 Scope *EnumScope = getNonFieldDeclScope(S);
2798 for (auto *ECD : ED->enumerators()) {
2799 assert(EnumScope->isDeclScope(ECD));
2800 EnumScope->RemoveDecl(ECD);
2801 IdResolver.RemoveDecl(ECD);
2802 }
2803 }
2804}
2805
2806/// DeclhasAttr - returns true if decl Declaration already has the target
2807/// attribute.
2808static bool DeclHasAttr(const Decl *D, const Attr *A) {
2809 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2810 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2811 for (const auto *i : D->attrs())
2812 if (i->getKind() == A->getKind()) {
2813 if (Ann) {
2814 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2815 return true;
2816 continue;
2817 }
2818 // FIXME: Don't hardcode this check
2819 if (OA && isa<OwnershipAttr>(i))
2820 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2821 return true;
2822 }
2823
2824 return false;
2825}
2826
2828 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2829 return VD->isThisDeclarationADefinition();
2830 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2831 return TD->isCompleteDefinition() || TD->isBeingDefined();
2832 return true;
2833}
2834
2835/// Merge alignment attributes from \p Old to \p New, taking into account the
2836/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2837///
2838/// \return \c true if any attributes were added to \p New.
2839static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2840 // Look for alignas attributes on Old, and pick out whichever attribute
2841 // specifies the strictest alignment requirement.
2842 AlignedAttr *OldAlignasAttr = nullptr;
2843 AlignedAttr *OldStrictestAlignAttr = nullptr;
2844 unsigned OldAlign = 0;
2845 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2846 // FIXME: We have no way of representing inherited dependent alignments
2847 // in a case like:
2848 // template<int A, int B> struct alignas(A) X;
2849 // template<int A, int B> struct alignas(B) X {};
2850 // For now, we just ignore any alignas attributes which are not on the
2851 // definition in such a case.
2852 if (I->isAlignmentDependent())
2853 return false;
2854
2855 if (I->isAlignas())
2856 OldAlignasAttr = I;
2857
2858 unsigned Align = I->getAlignment(S.Context);
2859 if (Align > OldAlign) {
2860 OldAlign = Align;
2861 OldStrictestAlignAttr = I;
2862 }
2863 }
2864
2865 // Look for alignas attributes on New.
2866 AlignedAttr *NewAlignasAttr = nullptr;
2867 unsigned NewAlign = 0;
2868 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2869 if (I->isAlignmentDependent())
2870 return false;
2871
2872 if (I->isAlignas())
2873 NewAlignasAttr = I;
2874
2875 unsigned Align = I->getAlignment(S.Context);
2876 if (Align > NewAlign)
2877 NewAlign = Align;
2878 }
2879
2880 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2881 // Both declarations have 'alignas' attributes. We require them to match.
2882 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2883 // fall short. (If two declarations both have alignas, they must both match
2884 // every definition, and so must match each other if there is a definition.)
2885
2886 // If either declaration only contains 'alignas(0)' specifiers, then it
2887 // specifies the natural alignment for the type.
2888 if (OldAlign == 0 || NewAlign == 0) {
2889 QualType Ty;
2890 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2891 Ty = VD->getType();
2892 else
2894
2895 if (OldAlign == 0)
2896 OldAlign = S.Context.getTypeAlign(Ty);
2897 if (NewAlign == 0)
2898 NewAlign = S.Context.getTypeAlign(Ty);
2899 }
2900
2901 if (OldAlign != NewAlign) {
2902 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2905 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2906 }
2907 }
2908
2909 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2910 // C++11 [dcl.align]p6:
2911 // if any declaration of an entity has an alignment-specifier,
2912 // every defining declaration of that entity shall specify an
2913 // equivalent alignment.
2914 // C11 6.7.5/7:
2915 // If the definition of an object does not have an alignment
2916 // specifier, any other declaration of that object shall also
2917 // have no alignment specifier.
2918 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2919 << OldAlignasAttr;
2920 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2921 << OldAlignasAttr;
2922 }
2923
2924 bool AnyAdded = false;
2925
2926 // Ensure we have an attribute representing the strictest alignment.
2927 if (OldAlign > NewAlign) {
2928 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2929 Clone->setInherited(true);
2930 New->addAttr(Clone);
2931 AnyAdded = true;
2932 }
2933
2934 // Ensure we have an alignas attribute if the old declaration had one.
2935 if (OldAlignasAttr && !NewAlignasAttr &&
2936 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2937 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2938 Clone->setInherited(true);
2939 New->addAttr(Clone);
2940 AnyAdded = true;
2941 }
2942
2943 return AnyAdded;
2944}
2945
2946#define WANT_DECL_MERGE_LOGIC
2947#include "clang/Sema/AttrParsedAttrImpl.inc"
2948#undef WANT_DECL_MERGE_LOGIC
2949
2951 const InheritableAttr *Attr,
2953 // Diagnose any mutual exclusions between the attribute that we want to add
2954 // and attributes that already exist on the declaration.
2955 if (!DiagnoseMutualExclusions(S, D, Attr))
2956 return false;
2957
2958 // This function copies an attribute Attr from a previous declaration to the
2959 // new declaration D if the new declaration doesn't itself have that attribute
2960 // yet or if that attribute allows duplicates.
2961 // If you're adding a new attribute that requires logic different from
2962 // "use explicit attribute on decl if present, else use attribute from
2963 // previous decl", for example if the attribute needs to be consistent
2964 // between redeclarations, you need to call a custom merge function here.
2965 InheritableAttr *NewAttr = nullptr;
2966 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) {
2967 const IdentifierInfo *InferredPlatformII = nullptr;
2968 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2969 InferredPlatformII = Inf->getPlatform();
2971 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2972 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2973 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2974 AA->getPriority(), AA->getEnvironment(), InferredPlatformII);
2975 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2976 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2977 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2978 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2979 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2980 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2981 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2982 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2983 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2984 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2985 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2986 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2987 FA->getFirstArg());
2988 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2989 NewAttr = S.mergeFormatMatchesAttr(
2990 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2991 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2992 NewAttr = S.mergeModularFormatAttr(
2993 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2994 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2995 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2996 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2997 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2998 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2999 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
3000 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
3001 IA->getInheritanceModel());
3002 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
3003 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
3004 &S.Context.Idents.get(AA->getSpelling()));
3005 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
3008 // CUDA target attributes are part of function signature for
3009 // overloading purposes and must not be merged.
3010 return false;
3011 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
3012 NewAttr = S.mergeMinSizeAttr(D, *MA);
3013 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
3014 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
3015 else if (const auto *SAA = dyn_cast<SwiftAttrAttr>(Attr))
3016 NewAttr = S.Swift().mergeAttrAttr(D, *SAA);
3017 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
3018 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
3019 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
3020 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
3021 else if (isa<AlignedAttr>(Attr))
3022 // AlignedAttrs are handled separately, because we need to handle all
3023 // such attributes on a declaration at the same time.
3024 NewAttr = nullptr;
3029 NewAttr = nullptr;
3030 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
3031 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
3032 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
3033 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
3034 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
3035 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
3036 else if (const auto *ENA = dyn_cast<WebAssemblyExportNameAttr>(Attr))
3037 NewAttr = S.Wasm().mergeExportNameAttr(D, *ENA);
3038 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
3039 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
3040 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
3041 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
3042 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
3043 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
3044 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
3045 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
3046 NT->getZ());
3047 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
3048 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
3049 WS->getPreferred(),
3050 WS->getSpelledArgsCount());
3051 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
3052 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
3053 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
3054 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
3055 else if (isa<SuppressAttr>(Attr))
3056 // Do nothing. Each redeclaration should be suppressed separately.
3057 NewAttr = nullptr;
3058 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
3059 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
3060 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
3061 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
3062 else if (const auto *PA = dyn_cast<PersonalityAttr>(Attr))
3063 NewAttr = S.mergePersonalityAttr(D, PA->getRoutine(), *PA);
3064
3065 if (NewAttr) {
3066 NewAttr->setInherited(true);
3067 D->addAttr(NewAttr);
3068 if (isa<MSInheritanceAttr>(NewAttr))
3070 return true;
3071 }
3072
3073 return false;
3074}
3075
3076static const NamedDecl *getDefinition(const Decl *D) {
3077 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3078 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3079 return Def;
3080 return nullptr;
3081 }
3082 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3083 const VarDecl *Def = VD->getDefinition();
3084 if (Def)
3085 return Def;
3086 return VD->getActingDefinition();
3087 }
3088 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3089 const FunctionDecl *Def = nullptr;
3090 if (FD->isDefined(Def, true))
3091 return Def;
3092 }
3093 return nullptr;
3094}
3095
3096static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3097 for (const auto *Attribute : D->attrs())
3098 if (Attribute->getKind() == Kind)
3099 return true;
3100 return false;
3101}
3102
3103/// checkNewAttributesAfterDef - If we already have a definition, check that
3104/// there are no new attributes in this declaration.
3105static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3106 if (!New->hasAttrs())
3107 return;
3108
3109 const NamedDecl *Def = getDefinition(Old);
3110 if (!Def || Def == New)
3111 return;
3112
3113 AttrVec &NewAttributes = New->getAttrs();
3114 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3115 Attr *NewAttribute = NewAttributes[I];
3116
3117 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3118 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3119 SkipBodyInfo SkipBody;
3120 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3121
3122 // If we're skipping this definition, drop the "alias" attribute.
3123 if (SkipBody.ShouldSkip) {
3124 NewAttributes.erase(NewAttributes.begin() + I);
3125 --E;
3126 continue;
3127 }
3128 } else {
3129 VarDecl *VD = cast<VarDecl>(New);
3130 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3132 ? diag::err_alias_after_tentative
3133 : diag::err_redefinition;
3134 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3135 if (Diag == diag::err_redefinition)
3136 S.notePreviousDefinition(Def, VD->getLocation());
3137 else
3138 S.Diag(Def->getLocation(), diag::note_previous_definition);
3139 VD->setInvalidDecl();
3140 }
3141 ++I;
3142 continue;
3143 }
3144
3145 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3146 // Tentative definitions are only interesting for the alias check above.
3147 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3148 ++I;
3149 continue;
3150 }
3151 }
3152
3153 if (hasAttribute(Def, NewAttribute->getKind())) {
3154 ++I;
3155 continue; // regular attr merging will take care of validating this.
3156 }
3157
3158 if (NewAttribute->getLocation().isInvalid()) {
3159 // An attribute with no source location was not written by the user. API
3160 // notes, in particular, are matched against whichever declaration the
3161 // compiler reaches, which can be a redeclaration that follows the
3162 // definition, possibly in a different module. There is nothing for the
3163 // user to correct, and erasing the attribute would silently change what
3164 // the annotated API means.
3165 ++I;
3166 continue;
3167 }
3168
3169 if (isa<C11NoReturnAttr>(NewAttribute)) {
3170 // C's _Noreturn is allowed to be added to a function after it is defined.
3171 ++I;
3172 continue;
3173 } else if (isa<UuidAttr>(NewAttribute)) {
3174 // msvc will allow a subsequent definition to add an uuid to a class
3175 ++I;
3176 continue;
3178 NewAttribute) &&
3179 NewAttribute->isStandardAttributeSyntax()) {
3180 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3181 // deprecated attribute can later be re-declared with the attribute and
3182 // vice-versa.
3183 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3184 // maybe_unused attribute can later be redeclared with the attribute and
3185 // vice versa.
3186 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3187 // nodiscard attribute can later be redeclared with the attribute and
3188 // vice-versa.
3189 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3190 ++I;
3191 continue;
3192 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3193 if (AA->isAlignas()) {
3194 // C++11 [dcl.align]p6:
3195 // if any declaration of an entity has an alignment-specifier,
3196 // every defining declaration of that entity shall specify an
3197 // equivalent alignment.
3198 // C11 6.7.5/7:
3199 // If the definition of an object does not have an alignment
3200 // specifier, any other declaration of that object shall also
3201 // have no alignment specifier.
3202 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3203 << AA;
3204 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3205 << AA;
3206 NewAttributes.erase(NewAttributes.begin() + I);
3207 --E;
3208 continue;
3209 }
3210 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3211 // If there is a C definition followed by a redeclaration with this
3212 // attribute then there are two different definitions. In C++, prefer the
3213 // standard diagnostics.
3214 if (!S.getLangOpts().CPlusPlus) {
3215 S.Diag(NewAttribute->getLocation(),
3216 diag::err_loader_uninitialized_redeclaration);
3217 S.Diag(Def->getLocation(), diag::note_previous_definition);
3218 NewAttributes.erase(NewAttributes.begin() + I);
3219 --E;
3220 continue;
3221 }
3222 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3223 cast<VarDecl>(New)->isInline() &&
3224 !cast<VarDecl>(New)->isInlineSpecified()) {
3225 // Don't warn about applying selectany to implicitly inline variables.
3226 // Older compilers and language modes would require the use of selectany
3227 // to make such variables inline, and it would have no effect if we
3228 // honored it.
3229 ++I;
3230 continue;
3231 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3232 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3233 // declarations after definitions.
3234 ++I;
3235 continue;
3236 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3237 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3238 // error since the definition will have already been created without
3239 // the semantic effects of the attribute having been applied.
3240 S.Diag(NewAttribute->getLocation(),
3241 diag::err_sycl_entry_point_after_definition)
3242 << NewAttribute;
3243 S.Diag(Def->getLocation(), diag::note_previous_definition);
3244 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3245 ++I;
3246 continue;
3247 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3248 // SYCLExternalAttr may be added after a definition.
3249 ++I;
3250 continue;
3251 }
3252
3253 S.Diag(NewAttribute->getLocation(),
3254 diag::warn_attribute_precede_definition);
3255 S.Diag(Def->getLocation(), diag::note_previous_definition);
3256 NewAttributes.erase(NewAttributes.begin() + I);
3257 --E;
3258 }
3259}
3260
3261static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3262 const ConstInitAttr *CIAttr,
3263 bool AttrBeforeInit) {
3264 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3265
3266 // Figure out a good way to write this specifier on the old declaration.
3267 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3268 // enough of the attribute list spelling information to extract that without
3269 // heroics.
3270 std::string SuitableSpelling;
3271 if (S.getLangOpts().CPlusPlus20)
3272 SuitableSpelling = std::string(
3273 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3274 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3275 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3276 InsertLoc, {tok::l_square, tok::l_square,
3277 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3278 S.PP.getIdentifierInfo("require_constant_initialization"),
3279 tok::r_square, tok::r_square}));
3280 if (SuitableSpelling.empty())
3281 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3282 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3283 S.PP.getIdentifierInfo("require_constant_initialization"),
3284 tok::r_paren, tok::r_paren}));
3285 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3286 SuitableSpelling = "constinit";
3287 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3288 SuitableSpelling = "[[clang::require_constant_initialization]]";
3289 if (SuitableSpelling.empty())
3290 SuitableSpelling = "__attribute__((require_constant_initialization))";
3291 SuitableSpelling += " ";
3292
3293 if (AttrBeforeInit) {
3294 // extern constinit int a;
3295 // int a = 0; // error (missing 'constinit'), accepted as extension
3296 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3297 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3298 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3299 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3300 } else {
3301 // int a = 0;
3302 // constinit extern int a; // error (missing 'constinit')
3303 S.Diag(CIAttr->getLocation(),
3304 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3305 : diag::warn_require_const_init_added_too_late)
3306 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3307 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3308 << CIAttr->isConstinit()
3309 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3310 }
3311}
3312
3315 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3316 UsedAttr *NewAttr = OldAttr->clone(Context);
3317 NewAttr->setInherited(true);
3318 New->addAttr(NewAttr);
3319 }
3320 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3321 RetainAttr *NewAttr = OldAttr->clone(Context);
3322 NewAttr->setInherited(true);
3323 New->addAttr(NewAttr);
3324 }
3325
3326 if (!Old->hasAttrs() && !New->hasAttrs())
3327 return;
3328
3329 // [dcl.constinit]p1:
3330 // If the [constinit] specifier is applied to any declaration of a
3331 // variable, it shall be applied to the initializing declaration.
3332 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3333 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3334 if (bool(OldConstInit) != bool(NewConstInit)) {
3335 const auto *OldVD = cast<VarDecl>(Old);
3336 auto *NewVD = cast<VarDecl>(New);
3337
3338 // Find the initializing declaration. Note that we might not have linked
3339 // the new declaration into the redeclaration chain yet.
3340 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3341 if (!InitDecl &&
3342 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3343 InitDecl = NewVD;
3344
3345 if (InitDecl == NewVD) {
3346 // This is the initializing declaration. If it would inherit 'constinit',
3347 // that's ill-formed. (Note that we do not apply this to the attribute
3348 // form).
3349 if (OldConstInit && OldConstInit->isConstinit())
3350 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3351 /*AttrBeforeInit=*/true);
3352 } else if (NewConstInit) {
3353 // This is the first time we've been told that this declaration should
3354 // have a constant initializer. If we already saw the initializing
3355 // declaration, this is too late.
3356 if (InitDecl && InitDecl != NewVD) {
3357 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3358 /*AttrBeforeInit=*/false);
3359 NewVD->dropAttr<ConstInitAttr>();
3360 }
3361 }
3362 }
3363
3364 // Attributes declared post-definition are currently ignored.
3365 checkNewAttributesAfterDef(*this, New, Old);
3366
3367 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3368 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3369 if (!OldA->isEquivalent(NewA)) {
3370 // This redeclaration changes __asm__ label.
3371 Diag(New->getLocation(), diag::err_different_asm_label);
3372 Diag(OldA->getLocation(), diag::note_previous_declaration);
3373 }
3374 } else if (Old->isUsed()) {
3375 // This redeclaration adds an __asm__ label to a declaration that has
3376 // already been ODR-used.
3377 Diag(New->getLocation(), diag::err_late_asm_label_name)
3378 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3379 }
3380 }
3381
3382 // Re-declaration cannot add abi_tag's.
3383 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3384 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3385 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3386 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3387 Diag(NewAbiTagAttr->getLocation(),
3388 diag::err_new_abi_tag_on_redeclaration)
3389 << NewTag;
3390 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3391 }
3392 }
3393 } else {
3394 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3395 Diag(Old->getLocation(), diag::note_previous_declaration);
3396 }
3397 }
3398
3399 // This redeclaration adds a section attribute.
3400 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3401 if (auto *VD = dyn_cast<VarDecl>(New)) {
3402 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3403 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3404 Diag(Old->getLocation(), diag::note_previous_declaration);
3405 }
3406 }
3407 }
3408
3409 // Redeclaration adds code-seg attribute.
3410 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3411 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3412 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3413 Diag(New->getLocation(), diag::warn_mismatched_section)
3414 << 0 /*codeseg*/;
3415 Diag(Old->getLocation(), diag::note_previous_declaration);
3416 }
3417
3418 if (!Old->hasAttrs())
3419 return;
3420
3421 bool foundAny = New->hasAttrs();
3422
3423 // Ensure that any moving of objects within the allocated map is done before
3424 // we process them.
3425 if (!foundAny) New->setAttrs(AttrVec());
3426
3427 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3428 // Ignore deprecated/unavailable/availability attributes if requested.
3430 if (isa<DeprecatedAttr>(I) ||
3433 switch (AMK) {
3435 continue;
3436
3441 LocalAMK = AMK;
3442 break;
3443 }
3444 }
3445
3446 // Already handled.
3447 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3448 continue;
3449
3450 // Don't propagate inferred noreturn or conflicting inline attributes to
3451 // explicit specializations.
3453 isa<NoInlineAttr>(I)) {
3454 if (auto *FD = dyn_cast<FunctionDecl>(New);
3455 FD &&
3456 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3457 continue;
3458 }
3459
3460 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3461 foundAny = true;
3462 }
3463
3464 if (mergeAlignedAttrs(*this, New, Old))
3465 foundAny = true;
3466
3467 if (!foundAny) New->dropAttrs();
3468}
3469
3471 for (const Attr *A : D->attrs())
3472 checkAttrIsTypeDependent(D, A);
3473}
3474
3475// Returns the number of added attributes.
3476template <class T>
3477static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3478 Sema &S) {
3479 unsigned found = 0;
3480 for (const auto *I : From->specific_attrs<T>()) {
3481 if (!DeclHasAttr(To, I)) {
3482 T *newAttr = cast<T>(I->clone(S.Context));
3483 newAttr->setInherited(true);
3484 To->addAttr(newAttr);
3485 ++found;
3486 }
3487 }
3488 return found;
3489}
3490
3491template <class F>
3492static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3493 F &&propagator) {
3494 if (!From->hasAttrs()) {
3495 return;
3496 }
3497
3498 bool foundAny = To->hasAttrs();
3499
3500 // Ensure that any moving of objects within the allocated map is
3501 // done before we process them.
3502 if (!foundAny)
3503 To->setAttrs(AttrVec());
3504
3505 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3506
3507 if (!foundAny)
3508 To->dropAttrs();
3509}
3510
3511/// mergeParamDeclAttributes - Copy attributes from the old parameter
3512/// to the new one.
3514 const ParmVarDecl *oldDecl, Sema &S) {
3516 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3517 unsigned found = 0;
3518 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3519 // Propagate the lifetimebound attribute from parameters to the
3520 // most recent declaration. Note that this doesn't include the implicit
3521 // 'this' parameter, as the attribute is applied to the function type in
3522 // that case.
3523 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3524 return found;
3525 });
3526}
3527
3529 const ASTContext &Ctx) {
3530
3531 auto NoSizeInfo = [&Ctx](QualType Ty) {
3532 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3533 return true;
3534 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3535 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3536 return false;
3537 };
3538
3539 // `type[]` is equivalent to `type *` and `type[*]`.
3540 if (NoSizeInfo(Old) && NoSizeInfo(New))
3541 return true;
3542
3543 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3544 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3545 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3546 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3547 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3548 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3549 return false;
3550 return true;
3551 }
3552
3553 // Only compare size, ignore Size modifiers and CVR.
3554 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3555 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3557 }
3558
3559 // Don't try to compare dependent sized array
3560 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3561 return true;
3562 }
3563
3564 return Old == New;
3565}
3566
3567static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3568 const ParmVarDecl *OldParam,
3569 Sema &S) {
3570 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3571 if (auto Newnullability = NewParam->getType()->getNullability()) {
3572 if (*Oldnullability != *Newnullability) {
3573 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3575 *Newnullability,
3577 != 0))
3579 *Oldnullability,
3581 != 0));
3582 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3583 }
3584 } else {
3585 QualType NewT = NewParam->getType();
3586 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3587 NewParam->setType(NewT);
3588 }
3589 }
3590 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3591 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3592 if (OldParamDT && NewParamDT &&
3593 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3594 QualType OldParamOT = OldParamDT->getOriginalType();
3595 QualType NewParamOT = NewParamDT->getOriginalType();
3596 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3597 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3598 << NewParam << NewParamOT;
3599 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3600 << OldParamOT;
3601 }
3602 }
3603}
3604
3605namespace {
3606
3607/// Used in MergeFunctionDecl to keep track of function parameters in
3608/// C.
3609struct GNUCompatibleParamWarning {
3610 ParmVarDecl *OldParm;
3611 ParmVarDecl *NewParm;
3612 QualType PromotedType;
3613};
3614
3615} // end anonymous namespace
3616
3617// Determine whether the previous declaration was a definition, implicit
3618// declaration, or a declaration.
3619template <typename T>
3620static std::pair<diag::kind, SourceLocation>
3622 diag::kind PrevDiag;
3623 SourceLocation OldLocation = Old->getLocation();
3624 if (Old->isThisDeclarationADefinition())
3625 PrevDiag = diag::note_previous_definition;
3626 else if (Old->isImplicit()) {
3627 PrevDiag = diag::note_previous_implicit_declaration;
3628 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3629 if (FD->getBuiltinID())
3630 PrevDiag = diag::note_previous_builtin_declaration;
3631 }
3632 if (OldLocation.isInvalid())
3633 OldLocation = New->getLocation();
3634 } else
3635 PrevDiag = diag::note_previous_declaration;
3636 return std::make_pair(PrevDiag, OldLocation);
3637}
3638
3639/// canRedefineFunction - checks if a function can be redefined. Currently,
3640/// only extern inline functions can be redefined, and even then only in
3641/// GNU89 mode.
3642static bool canRedefineFunction(const FunctionDecl *FD,
3643 const LangOptions& LangOpts) {
3644 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3645 !LangOpts.CPlusPlus &&
3646 FD->isInlineSpecified() &&
3647 FD->getStorageClass() == SC_Extern);
3648}
3649
3650const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3651 const AttributedType *AT = T->getAs<AttributedType>();
3652 while (AT && !AT->isCallingConv())
3653 AT = AT->getModifiedType()->getAs<AttributedType>();
3654 return AT;
3655}
3656
3657template <typename T>
3658static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3659 const DeclContext *DC = Old->getDeclContext();
3660 if (DC->isRecord())
3661 return false;
3662
3663 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3664 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3665 return true;
3666 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3667 return true;
3668 return false;
3669}
3670
3671template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3672static bool isExternC(VarTemplateDecl *) { return false; }
3673static bool isExternC(FunctionTemplateDecl *) { return false; }
3674
3675/// Check whether a redeclaration of an entity introduced by a
3676/// using-declaration is valid, given that we know it's not an overload
3677/// (nor a hidden tag declaration).
3678template<typename ExpectedDecl>
3680 ExpectedDecl *New) {
3681 // C++11 [basic.scope.declarative]p4:
3682 // Given a set of declarations in a single declarative region, each of
3683 // which specifies the same unqualified name,
3684 // -- they shall all refer to the same entity, or all refer to functions
3685 // and function templates; or
3686 // -- exactly one declaration shall declare a class name or enumeration
3687 // name that is not a typedef name and the other declarations shall all
3688 // refer to the same variable or enumerator, or all refer to functions
3689 // and function templates; in this case the class name or enumeration
3690 // name is hidden (3.3.10).
3691
3692 // C++11 [namespace.udecl]p14:
3693 // If a function declaration in namespace scope or block scope has the
3694 // same name and the same parameter-type-list as a function introduced
3695 // by a using-declaration, and the declarations do not declare the same
3696 // function, the program is ill-formed.
3697
3698 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3699 if (Old &&
3700 !Old->getDeclContext()->getRedeclContext()->Equals(
3701 New->getDeclContext()->getRedeclContext()) &&
3702 !(isExternC(Old) && isExternC(New)))
3703 Old = nullptr;
3704
3705 if (!Old) {
3706 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3707 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3708 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3709 return true;
3710 }
3711 return false;
3712}
3713
3715 const FunctionDecl *B) {
3716 assert(A->getNumParams() == B->getNumParams());
3717
3718 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3719 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3720 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3721 if (AttrA == AttrB)
3722 return true;
3723 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3724 AttrA->isDynamic() == AttrB->isDynamic();
3725 };
3726
3727 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3728}
3729
3730/// If necessary, adjust the semantic declaration context for a qualified
3731/// declaration to name the correct inline namespace within the qualifier.
3733 DeclaratorDecl *OldD) {
3734 // The only case where we need to update the DeclContext is when
3735 // redeclaration lookup for a qualified name finds a declaration
3736 // in an inline namespace within the context named by the qualifier:
3737 //
3738 // inline namespace N { int f(); }
3739 // int ::f(); // Sema DC needs adjusting from :: to N::.
3740 //
3741 // For unqualified declarations, the semantic context *can* change
3742 // along the redeclaration chain (for local extern declarations,
3743 // extern "C" declarations, and friend declarations in particular).
3744 if (!NewD->getQualifier())
3745 return;
3746
3747 // NewD is probably already in the right context.
3748 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3749 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3750 if (NamedDC->Equals(SemaDC))
3751 return;
3752
3753 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3754 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3755 "unexpected context for redeclaration");
3756
3757 auto *LexDC = NewD->getLexicalDeclContext();
3758 auto FixSemaDC = [=](NamedDecl *D) {
3759 if (!D)
3760 return;
3761 D->setDeclContext(SemaDC);
3762 D->setLexicalDeclContext(LexDC);
3763 };
3764
3765 FixSemaDC(NewD);
3766 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3767 FixSemaDC(FD->getDescribedFunctionTemplate());
3768 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3769 FixSemaDC(VD->getDescribedVarTemplate());
3770}
3771
3773 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3774 // Verify the old decl was also a function.
3775 FunctionDecl *Old = OldD->getAsFunction();
3776 if (!Old) {
3777 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3778 // We don't need to check the using friend pattern from other module unit
3779 // since we should have diagnosed such cases in its unit already.
3780 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3781 Diag(New->getLocation(), diag::err_using_decl_friend);
3782 Diag(Shadow->getTargetDecl()->getLocation(),
3783 diag::note_using_decl_target);
3784 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3785 << 0;
3786 return true;
3787 }
3788
3789 // Check whether the two declarations might declare the same function or
3790 // function template.
3791 if (FunctionTemplateDecl *NewTemplate =
3792 New->getDescribedFunctionTemplate()) {
3794 NewTemplate))
3795 return true;
3796 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3797 ->getAsFunction();
3798 } else {
3799 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3800 return true;
3801 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3802 }
3803 } else {
3804 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3805 << New->getDeclName();
3806 notePreviousDefinition(OldD, New->getLocation());
3807 return true;
3808 }
3809 }
3810
3811 // If the old declaration was found in an inline namespace and the new
3812 // declaration was qualified, update the DeclContext to match.
3814
3815 // If the old declaration is invalid, just give up here.
3816 if (Old->isInvalidDecl())
3817 return true;
3818
3819 // Disallow redeclaration of some builtins.
3820 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3821 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3822 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3823 << Old << Old->getType();
3824 return true;
3825 }
3826
3827 diag::kind PrevDiag;
3828 SourceLocation OldLocation;
3829 std::tie(PrevDiag, OldLocation) =
3831
3832 // Don't complain about this if we're in GNU89 mode and the old function
3833 // is an extern inline function.
3834 // Don't complain about specializations. They are not supposed to have
3835 // storage classes.
3836 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3837 New->getStorageClass() == SC_Static &&
3838 Old->hasExternalFormalLinkage() &&
3839 !New->getTemplateSpecializationInfo() &&
3841 if (getLangOpts().MicrosoftExt) {
3842 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3843 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3844 } else {
3845 Diag(New->getLocation(), diag::err_static_non_static)
3846 << New << /*MixedLinkageUB=*/false;
3847 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3848 return true;
3849 }
3850 }
3851
3852 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3853 if (!Old->hasAttr<InternalLinkageAttr>()) {
3854 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3855 << ILA;
3856 Diag(Old->getLocation(), diag::note_previous_declaration);
3857 New->dropAttr<InternalLinkageAttr>();
3858 }
3859
3860 if (auto *EA = New->getAttr<ErrorAttr>()) {
3861 if (!Old->hasAttr<ErrorAttr>()) {
3862 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3863 Diag(Old->getLocation(), diag::note_previous_declaration);
3864 New->dropAttr<ErrorAttr>();
3865 }
3866 }
3867
3869 return true;
3870
3871 if (!getLangOpts().CPlusPlus) {
3872 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3873 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3874 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3875 << New << OldOvl;
3876
3877 // Try our best to find a decl that actually has the overloadable
3878 // attribute for the note. In most cases (e.g. programs with only one
3879 // broken declaration/definition), this won't matter.
3880 //
3881 // FIXME: We could do this if we juggled some extra state in
3882 // OverloadableAttr, rather than just removing it.
3883 const Decl *DiagOld = Old;
3884 if (OldOvl) {
3885 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3886 const auto *A = D->getAttr<OverloadableAttr>();
3887 return A && !A->isImplicit();
3888 });
3889 // If we've implicitly added *all* of the overloadable attrs to this
3890 // chain, emitting a "previous redecl" note is pointless.
3891 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3892 }
3893
3894 if (DiagOld)
3895 Diag(DiagOld->getLocation(),
3896 diag::note_attribute_overloadable_prev_overload)
3897 << OldOvl;
3898
3899 if (OldOvl)
3900 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3901 else
3902 New->dropAttr<OverloadableAttr>();
3903 }
3904 }
3905
3906 // It is not permitted to redeclare an SME function with different SME
3907 // attributes.
3908 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3909 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3910 << New->getType() << Old->getType();
3911 Diag(OldLocation, diag::note_previous_declaration);
3912 return true;
3913 }
3914
3915 // If a function is first declared with a calling convention, but is later
3916 // declared or defined without one, all following decls assume the calling
3917 // convention of the first.
3918 //
3919 // It's OK if a function is first declared without a calling convention,
3920 // but is later declared or defined with the default calling convention.
3921 //
3922 // To test if either decl has an explicit calling convention, we look for
3923 // AttributedType sugar nodes on the type as written. If they are missing or
3924 // were canonicalized away, we assume the calling convention was implicit.
3925 //
3926 // Note also that we DO NOT return at this point, because we still have
3927 // other tests to run.
3928 QualType OldQType = Context.getCanonicalType(Old->getType());
3929 QualType NewQType = Context.getCanonicalType(New->getType());
3930 const FunctionType *OldType = cast<FunctionType>(OldQType);
3931 const FunctionType *NewType = cast<FunctionType>(NewQType);
3932 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3933 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3934 bool RequiresAdjustment = false;
3935
3936 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3938 const FunctionType *FT =
3939 First->getType().getCanonicalType()->castAs<FunctionType>();
3941 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3942 if (!NewCCExplicit) {
3943 // Inherit the CC from the previous declaration if it was specified
3944 // there but not here.
3945 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3946 RequiresAdjustment = true;
3947 } else if (Old->getBuiltinID()) {
3948 // Builtin attribute isn't propagated to the new one yet at this point,
3949 // so we check if the old one is a builtin.
3950
3951 // Calling Conventions on a Builtin aren't really useful and setting a
3952 // default calling convention and cdecl'ing some builtin redeclarations is
3953 // common, so warn and ignore the calling convention on the redeclaration.
3954 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3955 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3957 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3958 RequiresAdjustment = true;
3959 } else {
3960 // Calling conventions aren't compatible, so complain.
3961 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3962 Diag(New->getLocation(), diag::err_cconv_change)
3963 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3964 << !FirstCCExplicit
3965 << (!FirstCCExplicit ? "" :
3967
3968 // Put the note on the first decl, since it is the one that matters.
3969 Diag(First->getLocation(), diag::note_previous_declaration);
3970 return true;
3971 }
3972 }
3973
3974 // FIXME: diagnose the other way around?
3975 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3976 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3977 RequiresAdjustment = true;
3978 }
3979
3980 // If the declaration is marked with cfi_unchecked_callee but the definition
3981 // isn't, the definition is also cfi_unchecked_callee.
3982 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3983 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3984 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3985 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3986
3987 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3988 EPI2.CFIUncheckedCallee = true;
3989 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3990 FPT2->getParamTypes(), EPI2);
3991 NewType = cast<FunctionType>(NewQType);
3992 New->setType(NewQType);
3993 }
3994 }
3995 }
3996
3997 // Merge regparm attribute.
3998 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3999 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
4000 if (NewTypeInfo.getHasRegParm()) {
4001 Diag(New->getLocation(), diag::err_regparm_mismatch)
4002 << NewType->getRegParmType()
4003 << OldType->getRegParmType();
4004 Diag(OldLocation, diag::note_previous_declaration);
4005 return true;
4006 }
4007
4008 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
4009 RequiresAdjustment = true;
4010 }
4011
4012 // Merge ns_returns_retained attribute.
4013 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
4014 if (NewTypeInfo.getProducesResult()) {
4015 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
4016 << "'ns_returns_retained'";
4017 Diag(OldLocation, diag::note_previous_declaration);
4018 return true;
4019 }
4020
4021 NewTypeInfo = NewTypeInfo.withProducesResult(true);
4022 RequiresAdjustment = true;
4023 }
4024
4025 if (OldTypeInfo.getNoCallerSavedRegs() !=
4026 NewTypeInfo.getNoCallerSavedRegs()) {
4027 if (NewTypeInfo.getNoCallerSavedRegs()) {
4028 AnyX86NoCallerSavedRegistersAttr *Attr =
4029 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
4030 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
4031 Diag(OldLocation, diag::note_previous_declaration);
4032 return true;
4033 }
4034
4035 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
4036 RequiresAdjustment = true;
4037 }
4038
4039 if (RequiresAdjustment) {
4040 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
4041 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
4042 New->setType(QualType(AdjustedType, 0));
4043 NewQType = Context.getCanonicalType(New->getType());
4044 }
4045
4046 // If this redeclaration makes the function inline, we may need to add it to
4047 // UndefinedButUsed.
4048 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4049 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
4050 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4051 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4052 SourceLocation()));
4053
4054 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4055 // about it.
4056 if (New->hasAttr<GNUInlineAttr>() &&
4057 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4058 UndefinedButUsed.erase(Old->getCanonicalDecl());
4059 }
4060
4061 // If pass_object_size params don't match up perfectly, this isn't a valid
4062 // redeclaration.
4063 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4065 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
4066 << New->getDeclName();
4067 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4068 return true;
4069 }
4070
4071 QualType OldQTypeForComparison = OldQType;
4072 if (Context.hasAnyFunctionEffects()) {
4073 const auto OldFX = Old->getFunctionEffects();
4074 const auto NewFX = New->getFunctionEffects();
4075 if (OldFX != NewFX) {
4076 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4077 for (const auto &Diff : Diffs) {
4078 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
4079 Diag(New->getLocation(),
4080 diag::warn_mismatched_func_effect_redeclaration)
4081 << Diff.effectName();
4082 Diag(Old->getLocation(), diag::note_previous_declaration);
4083 }
4084 }
4085 // Following a warning, we could skip merging effects from the previous
4086 // declaration, but that would trigger an additional "conflicting types"
4087 // error.
4088 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4090 FunctionEffectSet MergedFX =
4091 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4092 if (!MergeErrs.empty())
4093 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4094 Old->getLocation());
4095
4096 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4097 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4098 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4099 NewFPT->getParamTypes(), EPI);
4100
4101 New->setType(ModQT);
4102 NewQType = New->getType();
4103
4104 // Revise OldQTForComparison to include the merged effects,
4105 // so as not to fail due to differences later.
4106 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4107 EPI = OldFPT->getExtProtoInfo();
4108 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4109 OldQTypeForComparison = Context.getFunctionType(
4110 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4111 }
4112 if (OldFX.empty()) {
4113 // A redeclaration may add the attribute to a previously seen function
4114 // body which needs to be verified.
4115 maybeAddDeclWithEffects(Old, MergedFX);
4116 }
4117 }
4118 }
4119 }
4120
4121 if (getLangOpts().CPlusPlus) {
4122 OldQType = Context.getCanonicalType(Old->getType());
4123 NewQType = Context.getCanonicalType(New->getType());
4124
4125 // Go back to the type source info to compare the declared return types,
4126 // per C++1y [dcl.type.auto]p13:
4127 // Redeclarations or specializations of a function or function template
4128 // with a declared return type that uses a placeholder type shall also
4129 // use that placeholder, not a deduced type.
4130 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4131 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4132 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4133 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4134 OldDeclaredReturnType)) {
4135 QualType ResQT;
4136 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4137 OldDeclaredReturnType->isObjCObjectPointerType())
4138 // FIXME: This does the wrong thing for a deduced return type.
4139 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4140 if (ResQT.isNull()) {
4141 if (New->isCXXClassMember() && New->isOutOfLine())
4142 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4143 << New << New->getReturnTypeSourceRange();
4144 else if (Old->isExternC() && New->isExternC() &&
4145 !Old->hasAttr<OverloadableAttr>() &&
4146 !New->hasAttr<OverloadableAttr>())
4147 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4148 else
4149 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4150 << New->getReturnTypeSourceRange();
4151 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4152 << Old->getReturnTypeSourceRange();
4153 return true;
4154 }
4155 else
4156 NewQType = ResQT;
4157 }
4158
4159 QualType OldReturnType = OldType->getReturnType();
4160 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4161 if (OldReturnType != NewReturnType) {
4162 // If this function has a deduced return type and has already been
4163 // defined, copy the deduced value from the old declaration.
4164 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4165 if (OldAT && OldAT->isDeduced()) {
4166 QualType DT = OldAT->getDeducedType();
4167 if (DT.isNull()) {
4168 New->setType(SubstAutoTypeDependent(New->getType()));
4169 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4170 } else {
4171 New->setType(SubstAutoType(New->getType(), DT));
4172 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4173 }
4174 }
4175 }
4176
4177 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4178 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4179 if (OldMethod && NewMethod) {
4180 // Preserve triviality.
4181 NewMethod->setTrivial(OldMethod->isTrivial());
4182
4183 // MSVC allows explicit template specialization at class scope:
4184 // 2 CXXMethodDecls referring to the same function will be injected.
4185 // We don't want a redeclaration error.
4186 bool IsClassScopeExplicitSpecialization =
4187 OldMethod->isFunctionTemplateSpecialization() &&
4189 bool isFriend = NewMethod->getFriendObjectKind();
4190
4191 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4192 !IsClassScopeExplicitSpecialization) {
4193 // -- Member function declarations with the same name and the
4194 // same parameter types cannot be overloaded if any of them
4195 // is a static member function declaration.
4196 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4197 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4198 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4199 return true;
4200 }
4201
4202 // C++ [class.mem]p1:
4203 // [...] A member shall not be declared twice in the
4204 // member-specification, except that a nested class or member
4205 // class template can be declared and then later defined.
4206 if (!inTemplateInstantiation()) {
4207 unsigned NewDiag;
4208 if (isa<CXXConstructorDecl>(OldMethod))
4209 NewDiag = diag::err_constructor_redeclared;
4210 else if (isa<CXXDestructorDecl>(NewMethod))
4211 NewDiag = diag::err_destructor_redeclared;
4212 else if (isa<CXXConversionDecl>(NewMethod))
4213 NewDiag = diag::err_conv_function_redeclared;
4214 else
4215 NewDiag = diag::err_member_redeclared;
4216
4217 Diag(New->getLocation(), NewDiag);
4218 } else {
4219 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4220 << New << New->getType();
4221 }
4222 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4223 return true;
4224
4225 // Complain if this is an explicit declaration of a special
4226 // member that was initially declared implicitly.
4227 //
4228 // As an exception, it's okay to befriend such methods in order
4229 // to permit the implicit constructor/destructor/operator calls.
4230 } else if (OldMethod->isImplicit()) {
4231 if (isFriend) {
4232 NewMethod->setImplicit();
4233 } else {
4234 Diag(NewMethod->getLocation(),
4235 diag::err_definition_of_implicitly_declared_member)
4236 << New << OldMethod->getSpecialMemberKind();
4237 return true;
4238 }
4239 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4240 Diag(NewMethod->getLocation(),
4241 diag::err_definition_of_explicitly_defaulted_member)
4242 << OldMethod->getSpecialMemberKind();
4243 return true;
4244 }
4245 }
4246
4247 // C++1z [over.load]p2
4248 // Certain function declarations cannot be overloaded:
4249 // -- Function declarations that differ only in the return type,
4250 // the exception specification, or both cannot be overloaded.
4251
4252 // Check the exception specifications match. This may recompute the type of
4253 // both Old and New if it resolved exception specifications, so grab the
4254 // types again after this. Because this updates the type, we do this before
4255 // any of the other checks below, which may update the "de facto" NewQType
4256 // but do not necessarily update the type of New.
4258 return true;
4259
4260 // C++11 [dcl.attr.noreturn]p1:
4261 // The first declaration of a function shall specify the noreturn
4262 // attribute if any declaration of that function specifies the noreturn
4263 // attribute.
4264 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4265 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4266 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4267 << NRA;
4268 Diag(Old->getLocation(), diag::note_previous_declaration);
4269 }
4270
4271 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4272 // When a function is declared with SYCL_EXTERNAL, that macro must be
4273 // used on the first declaration of that function in the translation unit.
4274 // Redeclarations of the function in the same translation unit may
4275 // optionally use SYCL_EXTERNAL, but this is not required.
4276 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4277 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4278 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4279 << SEA;
4280 Diag(Old->getLocation(), diag::note_previous_declaration);
4281 }
4282
4283 // (C++98 8.3.5p3):
4284 // All declarations for a function shall agree exactly in both the
4285 // return type and the parameter-type-list.
4286 // We also want to respect all the extended bits except noreturn.
4287
4288 // noreturn should now match unless the old type info didn't have it.
4289 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4290 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4291 const FunctionType *OldTypeForComparison
4292 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4293 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4294 assert(OldQTypeForComparison.isCanonical());
4295 }
4296
4298 // As a special case, retain the language linkage from previous
4299 // declarations of a friend function as an extension.
4300 //
4301 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4302 // and is useful because there's otherwise no way to specify language
4303 // linkage within class scope.
4304 //
4305 // Check cautiously as the friend object kind isn't yet complete.
4306 if (New->getFriendObjectKind() != Decl::FOK_None) {
4307 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4308 Diag(OldLocation, PrevDiag);
4309 } else {
4310 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4311 Diag(OldLocation, PrevDiag);
4312 return true;
4313 }
4314 }
4315
4316 // HLSL check parameters for matching ABI specifications.
4317 if (getLangOpts().HLSL) {
4318 if (HLSL().CheckCompatibleParameterABI(New, Old))
4319 return true;
4320
4321 // If no errors are generated when checking parameter ABIs we can check if
4322 // the two declarations have the same type ignoring the ABIs and if so,
4323 // the declarations can be merged. This case for merging is only valid in
4324 // HLSL because there are no valid cases of merging mismatched parameter
4325 // ABIs except the HLSL implicit in and explicit in.
4326 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4327 NewQType))
4328 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4329 // Fall through for conflicting redeclarations and redefinitions.
4330 }
4331
4332 // If the function types are compatible, merge the declarations. Ignore the
4333 // exception specifier because it was already checked above in
4334 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4335 // about incompatible types under -fms-compatibility.
4336 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4337 NewQType))
4338 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4339
4340 // If the types are imprecise (due to dependent constructs in friends or
4341 // local extern declarations), it's OK if they differ. We'll check again
4342 // during instantiation.
4343 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4344 return false;
4345
4346 // Fall through for conflicting redeclarations and redefinitions.
4347 }
4348
4349 // C: Function types need to be compatible, not identical. This handles
4350 // duplicate function decls like "void f(int); void f(enum X);" properly.
4351 if (!getLangOpts().CPlusPlus) {
4352 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4353 // type is specified by a function definition that contains a (possibly
4354 // empty) identifier list, both shall agree in the number of parameters
4355 // and the type of each parameter shall be compatible with the type that
4356 // results from the application of default argument promotions to the
4357 // type of the corresponding identifier. ...
4358 // This cannot be handled by ASTContext::typesAreCompatible() because that
4359 // doesn't know whether the function type is for a definition or not when
4360 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4361 // we need to cover here is that the number of arguments agree as the
4362 // default argument promotion rules were already checked by
4363 // ASTContext::typesAreCompatible().
4364 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4365 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4366 if (Old->hasInheritedPrototype())
4367 Old = Old->getCanonicalDecl();
4368 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4369 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4370 return true;
4371 }
4372
4373 // If we are merging two functions where only one of them has a prototype,
4374 // we may have enough information to decide to issue a diagnostic that the
4375 // function without a prototype will change behavior in C23. This handles
4376 // cases like:
4377 // void i(); void i(int j);
4378 // void i(int j); void i();
4379 // void i(); void i(int j) {}
4380 // See ActOnFinishFunctionBody() for other cases of the behavior change
4381 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4382 // type without a prototype.
4383 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4384 !New->isImplicit() && !Old->isImplicit()) {
4385 const FunctionDecl *WithProto, *WithoutProto;
4386 if (New->hasWrittenPrototype()) {
4387 WithProto = New;
4388 WithoutProto = Old;
4389 } else {
4390 WithProto = Old;
4391 WithoutProto = New;
4392 }
4393
4394 if (WithProto->getNumParams() != 0) {
4395 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4396 // The one without the prototype will be changing behavior in C23, so
4397 // warn about that one so long as it's a user-visible declaration.
4398 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4399 if (WithoutProto == New)
4400 IsWithoutProtoADef = NewDeclIsDefn;
4401 else
4402 IsWithProtoADef = NewDeclIsDefn;
4403 Diag(WithoutProto->getLocation(),
4404 diag::warn_non_prototype_changes_behavior)
4405 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4406 << (WithoutProto == Old) << IsWithProtoADef;
4407
4408 // The reason the one without the prototype will be changing behavior
4409 // is because of the one with the prototype, so note that so long as
4410 // it's a user-visible declaration. There is one exception to this:
4411 // when the new declaration is a definition without a prototype, the
4412 // old declaration with a prototype is not the cause of the issue,
4413 // and that does not need to be noted because the one with a
4414 // prototype will not change behavior in C23.
4415 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4416 !IsWithoutProtoADef)
4417 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4418 }
4419 }
4420 }
4421
4422 if (Context.typesAreCompatible(OldQType, NewQType)) {
4423 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4424 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4425 const FunctionProtoType *OldProto = nullptr;
4426 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4427 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4428 // The old declaration provided a function prototype, but the
4429 // new declaration does not. Merge in the prototype.
4430 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4431 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4432 OldProto->getParamTypes(),
4433 OldProto->getExtProtoInfo());
4434 New->setType(NewQType);
4435 New->setHasInheritedPrototype();
4436
4437 // Synthesize parameters with the same types.
4439 for (const auto &ParamType : OldProto->param_types()) {
4441 Context, New, SourceLocation(), SourceLocation(), nullptr,
4442 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4443 Param->setScopeInfo(0, Params.size());
4444 Param->setImplicit();
4445 Params.push_back(Param);
4446 }
4447
4448 New->setParams(Params);
4449 }
4450
4451 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4452 }
4453 }
4454
4455 // Check if the function types are compatible when pointer size address
4456 // spaces are ignored.
4457 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4458 return false;
4459
4460 // GNU C permits a K&R definition to follow a prototype declaration
4461 // if the declared types of the parameters in the K&R definition
4462 // match the types in the prototype declaration, even when the
4463 // promoted types of the parameters from the K&R definition differ
4464 // from the types in the prototype. GCC then keeps the types from
4465 // the prototype.
4466 //
4467 // If a variadic prototype is followed by a non-variadic K&R definition,
4468 // the K&R definition becomes variadic. This is sort of an edge case, but
4469 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4470 // C99 6.9.1p8.
4471 if (!getLangOpts().CPlusPlus &&
4472 Old->hasPrototype() && !New->hasPrototype() &&
4473 New->getType()->getAs<FunctionProtoType>() &&
4474 Old->getNumParams() == New->getNumParams()) {
4477 const FunctionProtoType *OldProto
4478 = Old->getType()->getAs<FunctionProtoType>();
4479 const FunctionProtoType *NewProto
4480 = New->getType()->getAs<FunctionProtoType>();
4481
4482 // Determine whether this is the GNU C extension.
4483 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4484 NewProto->getReturnType());
4485 bool LooseCompatible = !MergedReturn.isNull();
4486 for (unsigned Idx = 0, End = Old->getNumParams();
4487 LooseCompatible && Idx != End; ++Idx) {
4488 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4489 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4490 if (Context.typesAreCompatible(OldParm->getType(),
4491 NewProto->getParamType(Idx))) {
4492 ArgTypes.push_back(NewParm->getType());
4493 } else if (Context.typesAreCompatible(OldParm->getType(),
4494 NewParm->getType(),
4495 /*CompareUnqualified=*/true)) {
4496 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4497 NewProto->getParamType(Idx) };
4498 Warnings.push_back(Warn);
4499 ArgTypes.push_back(NewParm->getType());
4500 } else
4501 LooseCompatible = false;
4502 }
4503
4504 if (LooseCompatible) {
4505 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4506 Diag(Warnings[Warn].NewParm->getLocation(),
4507 diag::ext_param_promoted_not_compatible_with_prototype)
4508 << Warnings[Warn].PromotedType
4509 << Warnings[Warn].OldParm->getType();
4510 if (Warnings[Warn].OldParm->getLocation().isValid())
4511 Diag(Warnings[Warn].OldParm->getLocation(),
4512 diag::note_previous_declaration);
4513 }
4514
4515 if (MergeTypeWithOld)
4516 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4517 OldProto->getExtProtoInfo()));
4518 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4519 }
4520
4521 // Fall through to diagnose conflicting types.
4522 }
4523
4524 // A function that has already been declared has been redeclared or
4525 // defined with a different type; show an appropriate diagnostic.
4526
4527 // If the previous declaration was an implicitly-generated builtin
4528 // declaration, then at the very least we should use a specialized note.
4529 unsigned BuiltinID;
4530 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4531 // If it's actually a library-defined builtin function like 'malloc'
4532 // or 'printf', just warn about the incompatible redeclaration.
4533 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4534 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4535 Diag(OldLocation, diag::note_previous_builtin_declaration)
4536 << Old << Old->getType();
4537 return false;
4538 }
4539
4540 PrevDiag = diag::note_previous_builtin_declaration;
4541 }
4542
4543 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4544 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4545 return true;
4546}
4547
4549 Scope *S, bool MergeTypeWithOld) {
4550 // Merge the attributes
4552
4553 // Merge "pure" flag.
4554 if (Old->isPureVirtual())
4555 New->setIsPureVirtual();
4556
4557 // Merge "used" flag.
4558 if (Old->getMostRecentDecl()->isUsed(false))
4559 New->setIsUsed();
4560
4561 // Merge attributes from the parameters. These can mismatch with K&R
4562 // declarations.
4563 if (New->getNumParams() == Old->getNumParams())
4564 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4565 ParmVarDecl *NewParam = New->getParamDecl(i);
4566 ParmVarDecl *OldParam = Old->getParamDecl(i);
4567 mergeParamDeclAttributes(NewParam, OldParam, *this);
4568 mergeParamDeclTypes(NewParam, OldParam, *this);
4569 }
4570
4571 if (getLangOpts().CPlusPlus)
4572 return MergeCXXFunctionDecl(New, Old, S);
4573
4574 // Merge the function types so the we get the composite types for the return
4575 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4576 // was visible.
4577 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4578 if (!Merged.isNull() && MergeTypeWithOld)
4579 New->setType(Merged);
4580
4581 return false;
4582}
4583
4585 ObjCMethodDecl *oldMethod) {
4586 // Merge the attributes, including deprecated/unavailable
4587 AvailabilityMergeKind MergeKind =
4589 ? (oldMethod->isOptional()
4592 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4595
4596 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4597
4598 // Merge attributes from the parameters.
4600 oe = oldMethod->param_end();
4602 ni = newMethod->param_begin(), ne = newMethod->param_end();
4603 ni != ne && oi != oe; ++ni, ++oi)
4604 mergeParamDeclAttributes(*ni, *oi, *this);
4605
4606 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4607}
4608
4610 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4611
4612 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4613 ? diag::err_redefinition_different_type
4614 : diag::err_redeclaration_different_type)
4615 << New->getDeclName() << New->getType() << Old->getType();
4616
4617 diag::kind PrevDiag;
4618 SourceLocation OldLocation;
4619 std::tie(PrevDiag, OldLocation)
4621 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4622 New->setInvalidDecl();
4623}
4624
4626 bool MergeTypeWithOld) {
4627 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4628 return;
4629
4630 QualType MergedT;
4631 if (getLangOpts().CPlusPlus) {
4632 if (New->getType()->isUndeducedType()) {
4633 // We don't know what the new type is until the initializer is attached.
4634 return;
4635 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4636 // These could still be something that needs exception specs checked.
4637 return MergeVarDeclExceptionSpecs(New, Old);
4638 }
4639 // C++ [basic.link]p10:
4640 // [...] the types specified by all declarations referring to a given
4641 // object or function shall be identical, except that declarations for an
4642 // array object can specify array types that differ by the presence or
4643 // absence of a major array bound (8.3.4).
4644 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4645 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4646 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4647
4648 // We are merging a variable declaration New into Old. If it has an array
4649 // bound, and that bound differs from Old's bound, we should diagnose the
4650 // mismatch.
4651 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4652 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4653 PrevVD = PrevVD->getPreviousDecl()) {
4654 QualType PrevVDTy = PrevVD->getType();
4655 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4656 continue;
4657
4658 if (!Context.hasSameType(New->getType(), PrevVDTy))
4659 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4660 }
4661 }
4662
4663 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4664 if (Context.hasSameType(OldArray->getElementType(),
4665 NewArray->getElementType()))
4666 MergedT = New->getType();
4667 }
4668 // FIXME: Check visibility. New is hidden but has a complete type. If New
4669 // has no array bound, it should not inherit one from Old, if Old is not
4670 // visible.
4671 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4672 if (Context.hasSameType(OldArray->getElementType(),
4673 NewArray->getElementType()))
4674 MergedT = Old->getType();
4675 }
4676 }
4677 else if (New->getType()->isObjCObjectPointerType() &&
4678 Old->getType()->isObjCObjectPointerType()) {
4679 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4680 Old->getType());
4681 }
4682 } else {
4683 // C 6.2.7p2:
4684 // All declarations that refer to the same object or function shall have
4685 // compatible type.
4686 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4687 }
4688 if (MergedT.isNull()) {
4689 // It's OK if we couldn't merge types if either type is dependent, for a
4690 // block-scope variable. In other cases (static data members of class
4691 // templates, variable templates, ...), we require the types to be
4692 // equivalent.
4693 // FIXME: The C++ standard doesn't say anything about this.
4694 if ((New->getType()->isDependentType() ||
4695 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4696 // If the old type was dependent, we can't merge with it, so the new type
4697 // becomes dependent for now. We'll reproduce the original type when we
4698 // instantiate the TypeSourceInfo for the variable.
4699 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4700 New->setType(Context.DependentTy);
4701 return;
4702 }
4703 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4704 }
4705
4706 // Don't actually update the type on the new declaration if the old
4707 // declaration was an extern declaration in a different scope.
4708 if (MergeTypeWithOld)
4709 New->setType(MergedT);
4710}
4711
4712static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4714 // C11 6.2.7p4:
4715 // For an identifier with internal or external linkage declared
4716 // in a scope in which a prior declaration of that identifier is
4717 // visible, if the prior declaration specifies internal or
4718 // external linkage, the type of the identifier at the later
4719 // declaration becomes the composite type.
4720 //
4721 // If the variable isn't visible, we do not merge with its type.
4722 if (Previous.isShadowed())
4723 return false;
4724
4725 if (S.getLangOpts().CPlusPlus) {
4726 // C++11 [dcl.array]p3:
4727 // If there is a preceding declaration of the entity in the same
4728 // scope in which the bound was specified, an omitted array bound
4729 // is taken to be the same as in that earlier declaration.
4730 return NewVD->isPreviousDeclInSameBlockScope() ||
4731 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4733 } else {
4734 // If the old declaration was function-local, don't merge with its
4735 // type unless we're in the same function.
4736 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4737 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4738 }
4739}
4740
4742 // If the new decl is already invalid, don't do any other checking.
4743 if (New->isInvalidDecl())
4744 return;
4745
4746 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4747 return;
4748
4749 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4750
4751 // Verify the old decl was also a variable or variable template.
4752 VarDecl *Old = nullptr;
4753 VarTemplateDecl *OldTemplate = nullptr;
4754 if (Previous.isSingleResult()) {
4755 if (NewTemplate) {
4756 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4757 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4758
4759 if (auto *Shadow =
4760 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4761 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4762 return New->setInvalidDecl();
4763 } else {
4764 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4765
4766 if (auto *Shadow =
4767 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4768 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4769 return New->setInvalidDecl();
4770 }
4771 }
4772 if (!Old) {
4773 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4774 << New->getDeclName();
4775 notePreviousDefinition(Previous.getRepresentativeDecl(),
4776 New->getLocation());
4777 return New->setInvalidDecl();
4778 }
4779
4780 // If the old declaration was found in an inline namespace and the new
4781 // declaration was qualified, update the DeclContext to match.
4783
4784 // Ensure the template parameters are compatible.
4785 if (NewTemplate &&
4787 OldTemplate->getTemplateParameters(),
4788 /*Complain=*/true, TPL_TemplateMatch))
4789 return New->setInvalidDecl();
4790
4791 // C++ [class.mem]p1:
4792 // A member shall not be declared twice in the member-specification [...]
4793 //
4794 // Here, we need only consider static data members.
4795 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4796 Diag(New->getLocation(), diag::err_duplicate_member)
4797 << New->getIdentifier();
4798 Diag(Old->getLocation(), diag::note_previous_declaration);
4799 New->setInvalidDecl();
4800 }
4801
4802 if (NewTemplate && OldTemplate)
4803 mergeDeclAttributes(NewTemplate, OldTemplate);
4804
4806
4807 // Warn if an already-defined variable is made a weak_import in a subsequent
4808 // declaration
4809 if (New->hasAttr<WeakImportAttr>())
4810 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4811 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4812 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4813 Diag(D->getLocation(), diag::note_previous_definition);
4814 // Remove weak_import attribute on new declaration.
4815 New->dropAttr<WeakImportAttr>();
4816 break;
4817 }
4818 }
4819
4820 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4821 if (!Old->hasAttr<InternalLinkageAttr>()) {
4822 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4823 << ILA;
4824 Diag(Old->getLocation(), diag::note_previous_declaration);
4825 New->dropAttr<InternalLinkageAttr>();
4826 }
4827
4828 // Merge the types.
4829 VarDecl *MostRecent = Old->getMostRecentDecl();
4830 if (MostRecent != Old) {
4831 MergeVarDeclTypes(New, MostRecent,
4832 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4833 if (New->isInvalidDecl())
4834 return;
4835 }
4836
4838 if (New->isInvalidDecl())
4839 return;
4840
4841 diag::kind PrevDiag;
4842 SourceLocation OldLocation;
4843 std::tie(PrevDiag, OldLocation) =
4845
4846 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4847 if (New->getStorageClass() == SC_Static &&
4848 !New->isStaticDataMember() &&
4849 Old->hasExternalFormalLinkage()) {
4850 if (getLangOpts().MicrosoftExt) {
4851 Diag(New->getLocation(), diag::ext_static_non_static)
4852 << New->getDeclName();
4853 Diag(OldLocation, PrevDiag);
4854 } else {
4855 // This is the same internal/external linkage conflict as C2y 6.7.1p7;
4856 // before C2y it was undefined behavior (C11 6.2.2p7), so note that in
4857 // the older C language modes.
4858 Diag(New->getLocation(), diag::err_static_non_static)
4859 << New->getDeclName()
4860 << (!getLangOpts().CPlusPlus && !getLangOpts().C2y);
4861 Diag(OldLocation, PrevDiag);
4862 return New->setInvalidDecl();
4863 }
4864 }
4865
4866 // C2y 6.7.1p7: an identifier shall not appear with both internal and
4867 // external linkage within a translation unit. Before C2y this was UB
4868 // (C11 6.2.2p7).
4869 //
4870 // In C, a local shadow prevents a block-scope extern from inheriting the
4871 // file-scope static's internal linkage (C2y 6.2.2p6), so it defaults to
4872 // external linkage, creating the conflict.
4873 //
4874 // In C++, block-scope extern declarations target the enclosing namespace
4875 // scope ([dcl.meaning.general]/3.5), bypassing local shadows entirely, so
4876 // the extern always inherits internal linkage. No conflict arises.
4877 if (!getLangOpts().CPlusPlus && New->isLocalVarDecl() &&
4878 New->hasExternalStorage() && Previous.isShadowed() &&
4880 Diag(New->getLocation(), diag::err_internal_extern_mismatch)
4881 << New->getDeclName() << getLangOpts().C2y;
4882 Diag(OldLocation, diag::note_previous_declaration);
4883 return New->setInvalidDecl();
4884 }
4885
4886 // C99 6.2.2p4:
4887 // For an identifier declared with the storage-class specifier
4888 // extern in a scope in which a prior declaration of that
4889 // identifier is visible,23) if the prior declaration specifies
4890 // internal or external linkage, the linkage of the identifier at
4891 // the later declaration is the same as the linkage specified at
4892 // the prior declaration. If no prior declaration is visible, or
4893 // if the prior declaration specifies no linkage, then the
4894 // identifier has external linkage.
4895 if (New->hasExternalStorage() && Old->hasLinkage())
4896 /* Okay */;
4897 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4898 !New->isStaticDataMember() &&
4900 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4901 Diag(OldLocation, PrevDiag);
4902 return New->setInvalidDecl();
4903 }
4904
4905 // Check if extern is followed by non-extern and vice-versa.
4906 if (New->hasExternalStorage() &&
4907 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4908 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4909 Diag(OldLocation, PrevDiag);
4910 return New->setInvalidDecl();
4911 }
4912 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4913 !New->hasExternalStorage()) {
4914 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4915 Diag(OldLocation, PrevDiag);
4916 return New->setInvalidDecl();
4917 }
4918
4920 return;
4921
4922 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4923
4924 // FIXME: The test for external storage here seems wrong? We still
4925 // need to check for mismatches.
4926 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4927 // Don't complain about out-of-line definitions of static members.
4928 !(Old->getLexicalDeclContext()->isRecord() &&
4929 !New->getLexicalDeclContext()->isRecord())) {
4930 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4931 Diag(OldLocation, PrevDiag);
4932 return New->setInvalidDecl();
4933 }
4934
4935 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4936 if (VarDecl *Def = Old->getDefinition()) {
4937 // C++1z [dcl.fcn.spec]p4:
4938 // If the definition of a variable appears in a translation unit before
4939 // its first declaration as inline, the program is ill-formed.
4940 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4941 Diag(Def->getLocation(), diag::note_previous_definition);
4942 }
4943 }
4944
4945 // If this redeclaration makes the variable inline, we may need to add it to
4946 // UndefinedButUsed.
4947 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4948 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4949 !Old->isInAnotherModuleUnit())
4950 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4951 SourceLocation()));
4952
4953 if (New->getTLSKind() != Old->getTLSKind()) {
4954 if (!Old->getTLSKind()) {
4955 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4956 Diag(OldLocation, PrevDiag);
4957 } else if (!New->getTLSKind()) {
4958 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4959 Diag(OldLocation, PrevDiag);
4960 } else {
4961 // Do not allow redeclaration to change the variable between requiring
4962 // static and dynamic initialization.
4963 // FIXME: GCC allows this, but uses the TLS keyword on the first
4964 // declaration to determine the kind. Do we need to be compatible here?
4965 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4966 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4967 Diag(OldLocation, PrevDiag);
4968 }
4969 }
4970
4971 // C++ doesn't have tentative definitions, so go right ahead and check here.
4972 if (getLangOpts().CPlusPlus) {
4973 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4974 Old->getCanonicalDecl()->isConstexpr()) {
4975 // This definition won't be a definition any more once it's been merged.
4976 Diag(New->getLocation(),
4977 diag::warn_deprecated_redundant_constexpr_static_def);
4978 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4979 VarDecl *Def = Old->getDefinition();
4980 if (Def && checkVarDeclRedefinition(Def, New))
4981 return;
4982 if (Old->isInvalidDecl())
4983 New->setInvalidDecl();
4984 }
4985 } else {
4986 // C++ may not have a tentative definition rule, but it has a different
4987 // rule about what constitutes a definition in the first place. See
4988 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4989 // contains the extern specifier and doesn't have an initializer, it's fine
4990 // in C++.
4991 if (New->getTLSKind() != VarDecl::TLS_None &&
4992 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4993 VarDecl *Def = Old->getDefinition();
4994 if (Def && checkVarDeclRedefinition(Def, New)) {
4995 return;
4996 }
4997 } else if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4998 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4999 << New;
5000 Diag(Old->getLocation(), diag::note_previous_declaration);
5001 }
5002 }
5003
5005 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
5006 Diag(OldLocation, PrevDiag);
5007 New->setInvalidDecl();
5008 return;
5009 }
5010
5011 // Merge "used" flag.
5012 if (Old->getMostRecentDecl()->isUsed(false))
5013 New->setIsUsed();
5014
5015 // Keep a chain of previous declarations.
5016 New->setPreviousDecl(Old);
5017 if (NewTemplate)
5018 NewTemplate->setPreviousDecl(OldTemplate);
5019
5020 // Inherit access appropriately.
5021 New->setAccess(Old->getAccess());
5022 if (NewTemplate)
5023 NewTemplate->setAccess(New->getAccess());
5024
5025 if (Old->isInline())
5026 New->setImplicitlyInline();
5027}
5028
5031 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
5032 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
5033 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
5034 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
5035 auto &HSI = PP.getHeaderSearchInfo();
5036 StringRef HdrFilename =
5037 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
5038
5039 auto noteFromModuleOrInclude = [&](Module *Mod,
5040 SourceLocation IncLoc) -> bool {
5041 // Redefinition errors with modules are common with non modular mapped
5042 // headers, example: a non-modular header H in module A that also gets
5043 // included directly in a TU. Pointing twice to the same header/definition
5044 // is confusing, try to get better diagnostics when modules is on.
5045 if (IncLoc.isValid()) {
5046 if (Mod) {
5047 Diag(IncLoc, diag::note_redefinition_modules_same_file)
5048 << HdrFilename.str() << Mod->getFullModuleName();
5049 if (!Mod->DefinitionLoc.isInvalid())
5050 Diag(Mod->DefinitionLoc, diag::note_defined_here)
5051 << Mod->getFullModuleName();
5052 } else {
5053 Diag(IncLoc, diag::note_redefinition_include_same_file)
5054 << HdrFilename.str();
5055 }
5056 return true;
5057 }
5058
5059 return false;
5060 };
5061
5062 // Is it the same file and same offset? Provide more information on why
5063 // this leads to a redefinition error.
5064 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
5065 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
5066 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
5067 bool EmittedDiag =
5068 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5069 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5070
5071 // If the header has no guards, emit a note suggesting one.
5072 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
5073 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
5074
5075 if (EmittedDiag)
5076 return;
5077 }
5078
5079 // Redefinition coming from different files or couldn't do better above.
5080 if (Old->getLocation().isValid())
5081 Diag(Old->getLocation(), diag::note_previous_definition);
5082}
5083
5085 if ((!hasVisibleDefinition(Old) ||
5086 isFromSameSingleIncludeHeader(Old, New->getLocation())) &&
5087 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5089 New->getDescribedVarTemplate() ||
5090 !New->getTemplateParameterLists().empty() ||
5091 New->getDeclContext()->isDependentContext() ||
5092 New->hasAttr<SelectAnyAttr>())) {
5093 // The previous definition is hidden, and multiple definitions are
5094 // permitted (in separate TUs). Demote this to a declaration.
5095 New->demoteThisDefinitionToDeclaration();
5096
5097 // Make the canonical definition visible.
5098 if (auto *OldTD = Old->getDescribedVarTemplate())
5101 return false;
5102 } else {
5103 Diag(New->getLocation(), diag::err_redefinition) << New;
5104 notePreviousDefinition(Old, New->getLocation());
5105 New->setInvalidDecl();
5106 return true;
5107 }
5108}
5109
5111 DeclSpec &DS,
5112 const ParsedAttributesView &DeclAttrs,
5113 RecordDecl *&AnonRecord) {
5115 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5116}
5117
5118// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5119// disambiguate entities defined in different scopes.
5120// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5121// compatibility.
5122// We will pick our mangling number depending on which version of MSVC is being
5123// targeted.
5124static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5128}
5129
5130void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5131 if (!Context.getLangOpts().CPlusPlus)
5132 return;
5133
5134 if (isa<CXXRecordDecl>(Tag->getParent())) {
5135 // If this tag is the direct child of a class, number it if
5136 // it is anonymous.
5137 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5138 return;
5140 Context.getManglingNumberContext(Tag->getParent());
5141 Context.setManglingNumber(
5142 Tag, MCtx.getManglingNumber(
5143 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5144 return;
5145 }
5146
5147 // If this tag isn't a direct child of a class, number it if it is local.
5149 Decl *ManglingContextDecl;
5150 std::tie(MCtx, ManglingContextDecl) =
5151 getCurrentMangleNumberContext(Tag->getDeclContext());
5152 if (MCtx) {
5153 Context.setManglingNumber(
5154 Tag, MCtx->getManglingNumber(
5155 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5156 }
5157}
5158
5159namespace {
5160struct NonCLikeKind {
5161 enum {
5162 None,
5163 BaseClass,
5164 DefaultMemberInit,
5165 Lambda,
5166 Friend,
5167 OtherMember,
5168 Invalid,
5169 } Kind = None;
5170 SourceRange Range;
5171
5172 explicit operator bool() { return Kind != None; }
5173};
5174}
5175
5176/// Determine whether a class is C-like, according to the rules of C++
5177/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5178static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5179 if (RD->isInvalidDecl())
5180 return {NonCLikeKind::Invalid, {}};
5181
5182 // C++ [dcl.typedef]p9: [P1766R1]
5183 // An unnamed class with a typedef name for linkage purposes shall not
5184 //
5185 // -- have any base classes
5186 if (RD->getNumBases())
5187 return {NonCLikeKind::BaseClass,
5189 RD->bases_end()[-1].getEndLoc())};
5190 bool Invalid = false;
5191 for (Decl *D : RD->decls()) {
5192 // Don't complain about things we already diagnosed.
5193 if (D->isInvalidDecl()) {
5194 Invalid = true;
5195 continue;
5196 }
5197
5198 // -- have any [...] default member initializers
5199 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5200 if (FD->hasInClassInitializer()) {
5201 auto *Init = FD->getInClassInitializer();
5202 return {NonCLikeKind::DefaultMemberInit,
5203 Init ? Init->getSourceRange() : D->getSourceRange()};
5204 }
5205 continue;
5206 }
5207
5208 // FIXME: We don't allow friend declarations. This violates the wording of
5209 // P1766, but not the intent.
5210 if (isa<FriendDecl>(D))
5211 return {NonCLikeKind::Friend, D->getSourceRange()};
5212
5213 // -- declare any members other than non-static data members, member
5214 // enumerations, or member classes,
5216 isa<EnumDecl>(D))
5217 continue;
5218 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5219 if (!MemberRD) {
5220 if (D->isImplicit())
5221 continue;
5222 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5223 }
5224
5225 // -- contain a lambda-expression,
5226 if (MemberRD->isLambda())
5227 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5228
5229 // and all member classes shall also satisfy these requirements
5230 // (recursively).
5231 if (MemberRD->isThisDeclarationADefinition()) {
5232 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5233 return Kind;
5234 }
5235 }
5236
5237 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5238}
5239
5241 TypedefNameDecl *NewTD) {
5242 if (TagFromDeclSpec->isInvalidDecl())
5243 return;
5244
5245 // Do nothing if the tag already has a name for linkage purposes.
5246 if (TagFromDeclSpec->hasNameForLinkage())
5247 return;
5248
5249 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5250 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5251
5252 // The type must match the tag exactly; no qualifiers allowed.
5253 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5254 Context.getCanonicalTagType(TagFromDeclSpec))) {
5255 if (getLangOpts().CPlusPlus)
5256 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5257 return;
5258 }
5259
5260 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5261 // An unnamed class with a typedef name for linkage purposes shall [be
5262 // C-like].
5263 //
5264 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5265 // shouldn't happen, but there are constructs that the language rule doesn't
5266 // disallow for which we can't reasonably avoid computing linkage early.
5267 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5268 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5269 : NonCLikeKind();
5270 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5271 if (NonCLike || ChangesLinkage) {
5272 if (NonCLike.Kind == NonCLikeKind::Invalid)
5273 return;
5274
5275 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5276 if (ChangesLinkage) {
5277 // If the linkage changes, we can't accept this as an extension.
5278 if (NonCLike.Kind == NonCLikeKind::None)
5279 DiagID = diag::err_typedef_changes_linkage;
5280 else
5281 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5282 }
5283
5284 SourceLocation FixitLoc =
5285 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5286 llvm::SmallString<40> TextToInsert;
5287 TextToInsert += ' ';
5288 TextToInsert += NewTD->getIdentifier()->getName();
5289
5290 Diag(FixitLoc, DiagID)
5291 << isa<TypeAliasDecl>(NewTD)
5292 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5293 if (NonCLike.Kind != NonCLikeKind::None) {
5294 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5295 << NonCLike.Kind - 1 << NonCLike.Range;
5296 }
5297 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5298 << NewTD << isa<TypeAliasDecl>(NewTD);
5299
5300 if (ChangesLinkage)
5301 return;
5302 }
5303
5304 // Otherwise, set this as the anon-decl typedef for the tag.
5305 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5306
5307 // Now that we have a name for the tag, process API notes again.
5308 ProcessAPINotes(TagFromDeclSpec);
5309}
5310
5311static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5313 switch (T) {
5315 return 0;
5317 return 1;
5319 return 2;
5321 return 3;
5322 case DeclSpec::TST_enum:
5323 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5324 if (ED->isScopedUsingClassTag())
5325 return 5;
5326 if (ED->isScoped())
5327 return 6;
5328 }
5329 return 4;
5330 default:
5331 llvm_unreachable("unexpected type specifier");
5332 }
5333}
5334
5336 DeclSpec &DS,
5337 const ParsedAttributesView &DeclAttrs,
5338 MultiTemplateParamsArg TemplateParams,
5339 bool IsExplicitInstantiation,
5340 RecordDecl *&AnonRecord,
5341 SourceLocation EllipsisLoc) {
5342 Decl *TagD = nullptr;
5343 TagDecl *Tag = nullptr;
5349 TagD = DS.getRepAsDecl();
5350
5351 if (!TagD) // We probably had an error
5352 return nullptr;
5353
5354 // Note that the above type specs guarantee that the
5355 // type rep is a Decl, whereas in many of the others
5356 // it's a Type.
5357 if (isa<TagDecl>(TagD))
5358 Tag = cast<TagDecl>(TagD);
5359 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5360 Tag = CTD->getTemplatedDecl();
5361 }
5362
5363 if (Tag) {
5364 handleTagNumbering(Tag, S);
5365 Tag->setFreeStanding();
5366 if (Tag->isInvalidDecl())
5367 return Tag;
5368 }
5369
5370 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5371 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5372 // or incomplete types shall not be restrict-qualified."
5373 if (TypeQuals & DeclSpec::TQ_restrict)
5375 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5376 << DS.getSourceRange();
5377 }
5378
5379 if (DS.isInlineSpecified())
5380 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5381 << getLangOpts().CPlusPlus17;
5382
5383 if (DS.hasConstexprSpecifier()) {
5384 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5385 // and definitions of functions and variables.
5386 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5387 // the declaration of a function or function template
5388 if (Tag)
5389 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5391 << static_cast<int>(DS.getConstexprSpecifier());
5392 else if (getLangOpts().C23)
5393 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5394 else
5395 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5396 << static_cast<int>(DS.getConstexprSpecifier());
5397 // Don't emit warnings after this error.
5398 return TagD;
5399 }
5400
5402
5403 if (DS.isFriendSpecified()) {
5404 // If we're dealing with a decl but not a TagDecl, assume that
5405 // whatever routines created it handled the friendship aspect.
5406 if (TagD && !Tag)
5407 return nullptr;
5408 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5409 }
5410
5411 assert(EllipsisLoc.isInvalid() &&
5412 "Friend ellipsis but not friend-specified?");
5413
5414 // Track whether this decl-specifier declares anything.
5415 bool DeclaresAnything = true;
5416
5417 // Handle anonymous struct definitions.
5418 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5419 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5421 if (getLangOpts().CPlusPlus ||
5422 Record->getDeclContext()->isRecord()) {
5423 // If CurContext is a DeclContext that can contain statements,
5424 // RecursiveASTVisitor won't visit the decls that
5425 // BuildAnonymousStructOrUnion() will put into CurContext.
5426 // Also store them here so that they can be part of the
5427 // DeclStmt that gets created in this case.
5428 // FIXME: Also return the IndirectFieldDecls created by
5429 // BuildAnonymousStructOr union, for the same reason?
5430 if (CurContext->isFunctionOrMethod())
5431 AnonRecord = Record;
5432 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5433 Context.getPrintingPolicy());
5434 }
5435
5436 DeclaresAnything = false;
5437 }
5438 }
5439
5440 // C11 6.7.2.1p2:
5441 // A struct-declaration that does not declare an anonymous structure or
5442 // anonymous union shall contain a struct-declarator-list.
5443 //
5444 // This rule also existed in C89 and C99; the grammar for struct-declaration
5445 // did not permit a struct-declaration without a struct-declarator-list.
5446 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5448 // Check for Microsoft C extension: anonymous struct/union member.
5449 // Handle 2 kinds of anonymous struct/union:
5450 // struct STRUCT;
5451 // union UNION;
5452 // and
5453 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5454 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5455 if ((Tag && Tag->getDeclName()) ||
5457 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5458 : DS.getRepAsType().get()->getAsRecordDecl();
5459 if (Record && getLangOpts().MSAnonymousStructs) {
5460 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5461 << Record->isUnion() << DS.getSourceRange();
5463 }
5464
5465 DeclaresAnything = false;
5466 }
5467 }
5468
5469 // Skip all the checks below if we have a type error.
5471 (TagD && TagD->isInvalidDecl()))
5472 return TagD;
5473
5474 if (getLangOpts().CPlusPlus &&
5476 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5477 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5478 !Enum->isInvalidDecl())
5479 DeclaresAnything = false;
5480
5481 if (!DS.isMissingDeclaratorOk()) {
5482 // Customize diagnostic for a typedef missing a name.
5484 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5485 << DS.getSourceRange();
5486 else
5487 DeclaresAnything = false;
5488 }
5489
5490 if (DS.isModulePrivateSpecified() &&
5491 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5492 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5493 << Tag->getTagKind()
5495
5497
5498 // C 6.7/2:
5499 // A declaration [...] shall declare at least a declarator [...], a tag,
5500 // or the members of an enumeration.
5501 // C++ [dcl.dcl]p3:
5502 // [If there are no declarators], and except for the declaration of an
5503 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5504 // names into the program, or shall redeclare a name introduced by a
5505 // previous declaration.
5506 if (!DeclaresAnything) {
5507 // In C, we allow this as a (popular) extension / bug. Don't bother
5508 // producing further diagnostics for redundant qualifiers after this.
5509 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5510 ? diag::err_no_declarators
5511 : diag::ext_no_declarators)
5512 << DS.getSourceRange();
5513 return TagD;
5514 }
5515
5516 // C++ [dcl.stc]p1:
5517 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5518 // init-declarator-list of the declaration shall not be empty.
5519 // C++ [dcl.fct.spec]p1:
5520 // If a cv-qualifier appears in a decl-specifier-seq, the
5521 // init-declarator-list of the declaration shall not be empty.
5522 //
5523 // Spurious qualifiers here appear to be valid in C.
5524 unsigned DiagID = diag::warn_standalone_specifier;
5525 if (getLangOpts().CPlusPlus)
5526 DiagID = diag::ext_standalone_specifier;
5527
5528 // Note that a linkage-specification sets a storage class, but
5529 // 'extern "C" struct foo;' is actually valid and not theoretically
5530 // useless.
5531 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5532 if (SCS == DeclSpec::SCS_mutable)
5533 // Since mutable is not a viable storage class specifier in C, there is
5534 // no reason to treat it as an extension. Instead, diagnose as an error.
5535 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5536 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5537 Diag(DS.getStorageClassSpecLoc(), DiagID)
5539 }
5540
5544 if (DS.getTypeQualifiers()) {
5546 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5548 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5549 // Restrict is covered above.
5551 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5553 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5554 }
5555
5556 // Warn about ignored type attributes, for example:
5557 // __attribute__((aligned)) struct A;
5558 // Attributes should be placed after tag to apply to type declaration.
5559 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5560 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5561 if (TypeSpecType == DeclSpec::TST_class ||
5562 TypeSpecType == DeclSpec::TST_struct ||
5563 TypeSpecType == DeclSpec::TST_interface ||
5564 TypeSpecType == DeclSpec::TST_union ||
5565 TypeSpecType == DeclSpec::TST_enum) {
5566
5567 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5568 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5569 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5570 DiagnosticId = diag::warn_attribute_ignored;
5571 else if (AL.isRegularKeywordAttribute())
5572 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5573 else
5574 DiagnosticId = diag::warn_declspec_attribute_ignored;
5575 Diag(AL.getLoc(), DiagnosticId)
5576 << AL << GetDiagnosticTypeSpecifierID(DS);
5577 };
5578
5579 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5580 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5581 }
5582 }
5583
5584 return TagD;
5585}
5586
5587/// We are trying to inject an anonymous member into the given scope;
5588/// check if there's an existing declaration that can't be overloaded.
5589///
5590/// \return true if this is a forbidden redeclaration
5591static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5592 DeclContext *Owner,
5593 DeclarationName Name,
5594 SourceLocation NameLoc, bool IsUnion,
5595 StorageClass SC) {
5596 LookupResult R(SemaRef, Name, NameLoc,
5600 if (!SemaRef.LookupName(R, S)) return false;
5601
5602 // Pick a representative declaration.
5603 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5604 assert(PrevDecl && "Expected a non-null Decl");
5605
5606 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5607 return false;
5608
5609 if (SC == StorageClass::SC_None &&
5610 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5611 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5612 if (!Owner->isRecord())
5613 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5614 return false;
5615 }
5616
5617 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5618 << IsUnion << Name;
5619 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5620
5621 return true;
5622}
5623
5625 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5627}
5628
5630 if (!getLangOpts().CPlusPlus)
5631 return;
5632
5633 // This function can be parsed before we have validated the
5634 // structure as an anonymous struct
5635 if (Record->isAnonymousStructOrUnion())
5636 return;
5637
5638 const NamedDecl *First = 0;
5639 for (const Decl *D : Record->decls()) {
5640 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5641 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5642 continue;
5643 if (!First)
5644 First = ND;
5645 else
5647 }
5648}
5649
5650/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5651/// anonymous struct or union AnonRecord into the owning context Owner
5652/// and scope S. This routine will be invoked just after we realize
5653/// that an unnamed union or struct is actually an anonymous union or
5654/// struct, e.g.,
5655///
5656/// @code
5657/// union {
5658/// int i;
5659/// float f;
5660/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5661/// // f into the surrounding scope.x
5662/// @endcode
5663///
5664/// This routine is recursive, injecting the names of nested anonymous
5665/// structs/unions into the owning context and scope as well.
5666static bool
5668 RecordDecl *AnonRecord, AccessSpecifier AS,
5669 StorageClass SC,
5670 SmallVectorImpl<NamedDecl *> &Chaining) {
5671 bool Invalid = false;
5672
5673 // Look every FieldDecl and IndirectFieldDecl with a name.
5674 for (auto *D : AnonRecord->decls()) {
5675 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5676 cast<NamedDecl>(D)->getDeclName()) {
5677 ValueDecl *VD = cast<ValueDecl>(D);
5678 // C++ [class.union]p2:
5679 // The names of the members of an anonymous union shall be
5680 // distinct from the names of any other entity in the
5681 // scope in which the anonymous union is declared.
5682
5683 bool FieldInvalid = CheckAnonMemberRedeclaration(
5684 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5685 AnonRecord->isUnion(), SC);
5686 if (FieldInvalid)
5687 Invalid = true;
5688
5689 // Inject the IndirectFieldDecl even if invalid, because later
5690 // diagnostics may depend on it being present, see findDefaultInitializer.
5691
5692 // C++ [class.union]p2:
5693 // For the purpose of name lookup, after the anonymous union
5694 // definition, the members of the anonymous union are
5695 // considered to have been defined in the scope in which the
5696 // anonymous union is declared.
5697 unsigned OldChainingSize = Chaining.size();
5698 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5699 Chaining.append(IF->chain_begin(), IF->chain_end());
5700 else
5701 Chaining.push_back(VD);
5702
5703 assert(Chaining.size() >= 2);
5704 NamedDecl **NamedChain =
5705 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5706 for (unsigned i = 0; i < Chaining.size(); i++)
5707 NamedChain[i] = Chaining[i];
5708
5710 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5711 VD->getType(), {NamedChain, Chaining.size()});
5712
5713 for (const auto *Attr : VD->attrs())
5714 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5715
5716 IndirectField->setAccess(AS);
5717 IndirectField->setImplicit();
5718 IndirectField->setInvalidDecl(FieldInvalid);
5719 SemaRef.PushOnScopeChains(IndirectField, S);
5720
5721 // That includes picking up the appropriate access specifier.
5722 if (AS != AS_none)
5723 IndirectField->setAccess(AS);
5724
5725 Chaining.resize(OldChainingSize);
5726 }
5727 }
5728
5729 return Invalid;
5730}
5731
5732/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5733/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5734/// illegal input values are mapped to SC_None.
5735static StorageClass
5737 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5738 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5739 "Parser allowed 'typedef' as storage class VarDecl.");
5740 switch (StorageClassSpec) {
5743 if (DS.isExternInLinkageSpec())
5744 return SC_None;
5745 return SC_Extern;
5746 case DeclSpec::SCS_static: return SC_Static;
5747 case DeclSpec::SCS_auto: return SC_Auto;
5750 // Illegal SCSs map to None: error reporting is up to the caller.
5751 case DeclSpec::SCS_mutable: // Fall through.
5752 case DeclSpec::SCS_typedef: return SC_None;
5753 }
5754 llvm_unreachable("unknown storage class specifier");
5755}
5756
5758 assert(Record->hasInClassInitializer());
5759
5760 for (const auto *I : Record->decls()) {
5761 const auto *FD = dyn_cast<FieldDecl>(I);
5762 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5763 FD = IFD->getAnonField();
5764 if (FD && FD->hasInClassInitializer())
5765 return FD->getLocation();
5766 }
5767
5768 llvm_unreachable("couldn't find in-class initializer");
5769}
5770
5772 SourceLocation DefaultInitLoc) {
5773 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5774 return;
5775
5776 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5777 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5778}
5779
5781 CXXRecordDecl *AnonUnion) {
5782 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5783 return;
5784
5786}
5787
5789 AccessSpecifier AS,
5791 const PrintingPolicy &Policy) {
5792 DeclContext *Owner = Record->getDeclContext();
5793
5794 // Diagnose whether this anonymous struct/union is an extension.
5795 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5796 Diag(Record->getLocation(), diag::ext_anonymous_union);
5797 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5798 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5799 else if (!Record->isUnion() && !getLangOpts().C11)
5800 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5801
5802 // C and C++ require different kinds of checks for anonymous
5803 // structs/unions.
5804 bool Invalid = false;
5805 if (getLangOpts().CPlusPlus) {
5806 const char *PrevSpec = nullptr;
5807 if (Record->isUnion()) {
5808 // C++ [class.union]p6:
5809 // C++17 [class.union.anon]p2:
5810 // Anonymous unions declared in a named namespace or in the
5811 // global namespace shall be declared static.
5812 unsigned DiagID;
5813 DeclContext *OwnerScope = Owner->getRedeclContext();
5815 (OwnerScope->isTranslationUnit() ||
5816 (OwnerScope->isNamespace() &&
5817 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5818 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5819 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5820
5821 // Recover by adding 'static'.
5823 PrevSpec, DiagID, Policy);
5824 }
5825 // C++ [class.union]p6:
5826 // A storage class is not allowed in a declaration of an
5827 // anonymous union in a class scope.
5829 isa<RecordDecl>(Owner)) {
5831 diag::err_anonymous_union_with_storage_spec)
5833
5834 // Recover by removing the storage specifier.
5837 PrevSpec, DiagID, Context.getPrintingPolicy());
5838 }
5839 }
5840
5841 // Ignore const/volatile/restrict qualifiers.
5842 if (DS.getTypeQualifiers()) {
5844 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5845 << Record->isUnion() << "const"
5849 diag::ext_anonymous_struct_union_qualified)
5850 << Record->isUnion() << "volatile"
5854 diag::ext_anonymous_struct_union_qualified)
5855 << Record->isUnion() << "restrict"
5859 diag::ext_anonymous_struct_union_qualified)
5860 << Record->isUnion() << "_Atomic"
5864 diag::ext_anonymous_struct_union_qualified)
5865 << Record->isUnion() << "__unaligned"
5867
5869 }
5870
5871 // C++ [class.union]p2:
5872 // The member-specification of an anonymous union shall only
5873 // define non-static data members. [Note: nested types and
5874 // functions cannot be declared within an anonymous union. ]
5875 for (auto *Mem : Record->decls()) {
5876 // Ignore invalid declarations; we already diagnosed them.
5877 if (Mem->isInvalidDecl())
5878 continue;
5879
5880 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5881 // C++ [class.union]p3:
5882 // An anonymous union shall not have private or protected
5883 // members (clause 11).
5884 assert(FD->getAccess() != AS_none);
5885 if (FD->getAccess() != AS_public) {
5886 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5887 << Record->isUnion() << (FD->getAccess() == AS_protected);
5888 Invalid = true;
5889 }
5890
5891 // C++ [class.union]p1
5892 // An object of a class with a non-trivial constructor, a non-trivial
5893 // copy constructor, a non-trivial destructor, or a non-trivial copy
5894 // assignment operator cannot be a member of a union, nor can an
5895 // array of such objects.
5896 if (CheckNontrivialField(FD))
5897 Invalid = true;
5898 } else if (Mem->isImplicit()) {
5899 // Any implicit members are fine.
5900 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5901 // This is a type that showed up in an
5902 // elaborated-type-specifier inside the anonymous struct or
5903 // union, but which actually declares a type outside of the
5904 // anonymous struct or union. It's okay.
5905 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5906 if (!MemRecord->isAnonymousStructOrUnion() &&
5907 MemRecord->getDeclName()) {
5908 // Visual C++ allows type definition in anonymous struct or union.
5909 if (getLangOpts().MicrosoftExt)
5910 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5911 << Record->isUnion();
5912 else {
5913 // This is a nested type declaration.
5914 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5915 << Record->isUnion();
5916 Invalid = true;
5917 }
5918 } else {
5919 // This is an anonymous type definition within another anonymous type.
5920 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5921 // not part of standard C++.
5922 Diag(MemRecord->getLocation(),
5923 diag::ext_anonymous_record_with_anonymous_type)
5924 << Record->isUnion();
5925 }
5926 } else if (isa<AccessSpecDecl>(Mem)) {
5927 // Any access specifier is fine.
5928 } else if (isa<StaticAssertDecl>(Mem)) {
5929 // In C++1z, static_assert declarations are also fine.
5930 } else {
5931 // We have something that isn't a non-static data
5932 // member. Complain about it.
5933 unsigned DK = diag::err_anonymous_record_bad_member;
5934 if (isa<TypeDecl>(Mem))
5935 DK = diag::err_anonymous_record_with_type;
5936 else if (isa<FunctionDecl>(Mem))
5937 DK = diag::err_anonymous_record_with_function;
5938 else if (isa<VarDecl>(Mem))
5939 DK = diag::err_anonymous_record_with_static;
5940
5941 // Visual C++ allows type definition in anonymous struct or union.
5942 if (getLangOpts().MicrosoftExt &&
5943 DK == diag::err_anonymous_record_with_type)
5944 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5945 << Record->isUnion();
5946 else {
5947 Diag(Mem->getLocation(), DK) << Record->isUnion();
5948 Invalid = true;
5949 }
5950 }
5951 }
5952
5953 // C++11 [class.union]p8 (DR1460):
5954 // At most one variant member of a union may have a
5955 // brace-or-equal-initializer.
5956 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5957 Owner->isRecord())
5960 }
5961
5962 if (!Record->isUnion() && !Owner->isRecord()) {
5963 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5964 << getLangOpts().CPlusPlus;
5965 Invalid = true;
5966 }
5967
5968 // C++ [dcl.dcl]p3:
5969 // [If there are no declarators], and except for the declaration of an
5970 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5971 // names into the program
5972 // C++ [class.mem]p2:
5973 // each such member-declaration shall either declare at least one member
5974 // name of the class or declare at least one unnamed bit-field
5975 //
5976 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5977 if (getLangOpts().CPlusPlus && Record->field_empty())
5978 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5979
5980 // Mock up a declarator.
5984 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5985
5986 // Create a declaration for this anonymous struct/union.
5987 NamedDecl *Anon = nullptr;
5988 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5989 Anon = FieldDecl::Create(
5990 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5991 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5992 /*BitWidth=*/nullptr, /*Mutable=*/false,
5993 /*InitStyle=*/ICIS_NoInit);
5994 Anon->setAccess(AS);
5995 ProcessDeclAttributes(S, Anon, Dc);
5996
5997 if (getLangOpts().CPlusPlus)
5998 FieldCollector->Add(cast<FieldDecl>(Anon));
5999 } else {
6000 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
6001 if (SCSpec == DeclSpec::SCS_mutable) {
6002 // mutable can only appear on non-static class members, so it's always
6003 // an error here
6004 Diag(Record->getLocation(), diag::err_mutable_nonmember);
6005 Invalid = true;
6006 SC = SC_None;
6007 }
6008
6009 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
6010 Record->getLocation(), /*IdentifierInfo=*/nullptr,
6011 Context.getCanonicalTagType(Record), TInfo, SC);
6012 if (Invalid)
6013 Anon->setInvalidDecl();
6014
6015 ProcessDeclAttributes(S, Anon, Dc);
6016
6017 // Default-initialize the implicit variable. This initialization will be
6018 // trivial in almost all cases, except if a union member has an in-class
6019 // initializer:
6020 // union { int n = 0; };
6022 }
6023 Anon->setImplicit();
6024
6025 // Mark this as an anonymous struct/union type.
6026 Record->setAnonymousStructOrUnion(true);
6027
6028 // Add the anonymous struct/union object to the current
6029 // context. We'll be referencing this object when we refer to one of
6030 // its members.
6031 Owner->addDecl(Anon);
6032
6033 // Inject the members of the anonymous struct/union into the owning
6034 // context and into the identifier resolver chain for name lookup
6035 // purposes.
6037 Chain.push_back(Anon);
6038
6039 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
6040 Chain))
6041 Invalid = true;
6042
6043 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
6044 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6046 Decl *ManglingContextDecl;
6047 std::tie(MCtx, ManglingContextDecl) =
6048 getCurrentMangleNumberContext(NewVD->getDeclContext());
6049 if (MCtx) {
6050 Context.setManglingNumber(
6051 NewVD, MCtx->getManglingNumber(
6052 NewVD, getMSManglingNumber(getLangOpts(), S)));
6053 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6054 }
6055 }
6056 }
6057
6058 if (Invalid)
6059 Anon->setInvalidDecl();
6060
6061 return Anon;
6062}
6063
6065 RecordDecl *Record) {
6066 assert(Record && "expected a record!");
6067
6068 // Mock up a declarator.
6071 assert(TInfo && "couldn't build declarator info for anonymous struct");
6072
6073 auto *ParentDecl = cast<RecordDecl>(CurContext);
6074 CanQualType RecTy = Context.getCanonicalTagType(Record);
6075
6076 // Create a declaration for this anonymous struct.
6077 NamedDecl *Anon =
6078 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
6079 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
6080 /*BitWidth=*/nullptr, /*Mutable=*/false,
6081 /*InitStyle=*/ICIS_NoInit);
6082 Anon->setImplicit();
6083
6084 // Add the anonymous struct object to the current context.
6085 CurContext->addDecl(Anon);
6086
6087 // Inject the members of the anonymous struct into the current
6088 // context and into the identifier resolver chain for name lookup
6089 // purposes.
6091 Chain.push_back(Anon);
6092
6093 RecordDecl *RecordDef = Record->getDefinition();
6094 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
6095 diag::err_field_incomplete_or_sizeless) ||
6097 *this, S, CurContext, RecordDef, AS_none,
6099 Anon->setInvalidDecl();
6100 ParentDecl->setInvalidDecl();
6101 }
6102
6103 return Anon;
6104}
6105
6109
6112 DeclarationNameInfo NameInfo;
6113 NameInfo.setLoc(Name.StartLocation);
6114
6115 switch (Name.getKind()) {
6116
6119 NameInfo.setName(Name.Identifier);
6120 return NameInfo;
6121
6123 // C++ [temp.deduct.guide]p3:
6124 // The simple-template-id shall name a class template specialization.
6125 // The template-name shall be the same identifier as the template-name
6126 // of the simple-template-id.
6127 // These together intend to imply that the template-name shall name a
6128 // class template.
6129 // FIXME: template<typename T> struct X {};
6130 // template<typename T> using Y = X<T>;
6131 // Y(int) -> Y<int>;
6132 // satisfies these rules but does not name a class template.
6133 TemplateName TN = Name.TemplateName.get().get();
6134 auto *Template = TN.getAsTemplateDecl();
6136 Diag(Name.StartLocation,
6137 diag::err_deduction_guide_name_not_class_template)
6138 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6139 if (Template)
6141 return DeclarationNameInfo();
6142 }
6143
6144 NameInfo.setName(
6145 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6146 return NameInfo;
6147 }
6148
6150 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6154 return NameInfo;
6155
6157 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6158 Name.Identifier));
6160 return NameInfo;
6161
6163 TypeSourceInfo *TInfo;
6165 if (Ty.isNull())
6166 return DeclarationNameInfo();
6167 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6168 Context.getCanonicalType(Ty)));
6169 NameInfo.setNamedTypeInfo(TInfo);
6170 return NameInfo;
6171 }
6172
6174 TypeSourceInfo *TInfo;
6175 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6176 if (Ty.isNull())
6177 return DeclarationNameInfo();
6178 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6179 Context.getCanonicalType(Ty)));
6180 NameInfo.setNamedTypeInfo(TInfo);
6181 return NameInfo;
6182 }
6183
6185 // In well-formed code, we can only have a constructor
6186 // template-id that refers to the current context, so go there
6187 // to find the actual type being constructed.
6188 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6189 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6190 return DeclarationNameInfo();
6191
6192 // Determine the type of the class being constructed.
6193 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6194
6195 // FIXME: Check two things: that the template-id names the same type as
6196 // CurClassType, and that the template-id does not occur when the name
6197 // was qualified.
6198
6199 NameInfo.setName(
6200 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6201 // FIXME: should we retrieve TypeSourceInfo?
6202 NameInfo.setNamedTypeInfo(nullptr);
6203 return NameInfo;
6204 }
6205
6207 TypeSourceInfo *TInfo;
6208 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6209 if (Ty.isNull())
6210 return DeclarationNameInfo();
6211 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6212 Context.getCanonicalType(Ty)));
6213 NameInfo.setNamedTypeInfo(TInfo);
6214 return NameInfo;
6215 }
6216
6218 TemplateName TName = Name.TemplateId->Template.get();
6219 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6220 return Context.getNameForTemplate(TName, TNameLoc);
6221 }
6222
6223 } // switch (Name.getKind())
6224
6225 llvm_unreachable("Unknown name kind");
6226}
6227
6229 do {
6230 if (Ty->isPointerOrReferenceType())
6231 Ty = Ty->getPointeeType();
6232 else if (Ty->isArrayType())
6234 else
6235 return Ty.withoutLocalFastQualifiers();
6236 } while (true);
6237}
6238
6239/// hasSimilarParameters - Determine whether the C++ functions Declaration
6240/// and Definition have "nearly" matching parameters. This heuristic is
6241/// used to improve diagnostics in the case where an out-of-line function
6242/// definition doesn't match any declaration within the class or namespace.
6243/// Also sets Params to the list of indices to the parameters that differ
6244/// between the declaration and the definition. If hasSimilarParameters
6245/// returns true and Params is empty, then all of the parameters match.
6249 SmallVectorImpl<unsigned> &Params) {
6250 Params.clear();
6251 if (Declaration->param_size() != Definition->param_size())
6252 return false;
6253 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6254 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6255 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6256
6257 // The parameter types are identical
6258 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6259 continue;
6260
6261 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6262 QualType DefParamBaseTy = getCoreType(DefParamTy);
6263 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6264 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6265
6266 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6267 (DeclTyName && DeclTyName == DefTyName))
6268 Params.push_back(Idx);
6269 else // The two parameters aren't even close
6270 return false;
6271 }
6272
6273 return true;
6274}
6275
6276/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6277/// declarator needs to be rebuilt in the current instantiation.
6278/// Any bits of declarator which appear before the name are valid for
6279/// consideration here. That's specifically the type in the decl spec
6280/// and the base type in any member-pointer chunks.
6282 DeclarationName Name) {
6283 // The types we specifically need to rebuild are:
6284 // - typenames, typeofs, and decltypes
6285 // - types which will become injected class names
6286 // Of course, we also need to rebuild any type referencing such a
6287 // type. It's safest to just say "dependent", but we call out a
6288 // few cases here.
6289
6290 DeclSpec &DS = D.getMutableDeclSpec();
6291 switch (DS.getTypeSpecType()) {
6295#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6296#include "clang/Basic/BuiltinTraits.inc"
6297 case DeclSpec::TST_atomic: {
6298 // Grab the type from the parser.
6299 TypeSourceInfo *TSI = nullptr;
6300 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6301 if (T.isNull() || !T->isInstantiationDependentType()) break;
6302
6303 // Make sure there's a type source info. This isn't really much
6304 // of a waste; most dependent types should have type source info
6305 // attached already.
6306 if (!TSI)
6308
6309 // Rebuild the type in the current instantiation.
6311 if (!TSI) return true;
6312
6313 // Store the new type back in the decl spec.
6314 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6315 DS.UpdateTypeRep(LocType);
6316 break;
6317 }
6318
6322 Expr *E = DS.getRepAsExpr();
6324 if (Result.isInvalid()) return true;
6325 DS.UpdateExprRep(Result.get());
6326 break;
6327 }
6328
6329 default:
6330 // Nothing to do for these decl specs.
6331 break;
6332 }
6333
6334 // It doesn't matter what order we do this in.
6335 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6336 DeclaratorChunk &Chunk = D.getTypeObject(I);
6337
6338 // The only type information in the declarator which can come
6339 // before the declaration name is the base type of a member
6340 // pointer.
6342 continue;
6343
6344 // Rebuild the scope specifier in-place.
6345 CXXScopeSpec &SS = Chunk.Mem.Scope();
6347 return true;
6348 }
6349
6350 return false;
6351}
6352
6353/// Returns true if the declaration is declared in a system header or from a
6354/// system macro.
6355static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6356 return SM.isInSystemHeader(D->getLocation()) ||
6358}
6359
6361 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6362 // of system decl.
6363 if (D->getPreviousDecl() || D->isImplicit())
6364 return;
6367 !isFromSystemHeader(Context.getSourceManager(), D)) {
6368 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6369 << D << static_cast<int>(Status);
6370 }
6371}
6372
6375
6376 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6377 // declaration only if the `bind_to_declaration` extension is set.
6379 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6380 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6381 llvm::omp::TraitProperty::
6382 implementation_extension_bind_to_declaration))
6384 S, D, MultiTemplateParamsArg(), Bases);
6385
6387
6388 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6389 Dcl && Dcl->getDeclContext()->isFileContext())
6391
6392 if (!Bases.empty())
6394 Bases);
6395
6396 return Dcl;
6397}
6398
6400 DeclarationNameInfo NameInfo) {
6401 DeclarationName Name = NameInfo.getName();
6402
6403 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6404 while (Record && Record->isAnonymousStructOrUnion())
6405 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6406 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6407 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6408 return true;
6409 }
6410
6411 return false;
6412}
6413
6415 DeclarationName Name,
6416 SourceLocation Loc,
6417 TemplateIdAnnotation *TemplateId,
6418 bool IsMemberSpecialization) {
6419 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6420 "without nested-name-specifier");
6421 DeclContext *Cur = CurContext;
6422 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6423 Cur = Cur->getParent();
6424
6425 // If the user provided a superfluous scope specifier that refers back to the
6426 // class in which the entity is already declared, diagnose and ignore it.
6427 //
6428 // class X {
6429 // void X::f();
6430 // };
6431 //
6432 // Note, it was once ill-formed to give redundant qualification in all
6433 // contexts, but that rule was removed by DR482.
6434 if (Cur->Equals(DC)) {
6435 if (Cur->isRecord()) {
6436 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6437 : diag::err_member_extra_qualification)
6438 << Name << FixItHint::CreateRemoval(SS.getRange());
6439 SS.clear();
6440 } else {
6441 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6442 }
6443 return false;
6444 }
6445
6446 // Check whether the qualifying scope encloses the scope of the original
6447 // declaration. For a template-id, we perform the checks in
6448 // CheckTemplateSpecializationScope.
6449 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6451 if (Cur->isRecord())
6452 Diag(Loc, diag::err_member_qualification)
6453 << Name << SS.getRange();
6454 else if (isa<TranslationUnitDecl>(DC))
6455 Diag(Loc, diag::err_invalid_declarator_global_scope)
6456 << Name << SS.getRange();
6457 else if (isa<FunctionDecl>(Cur))
6458 Diag(Loc, diag::err_invalid_declarator_in_function)
6459 << Name << SS.getRange();
6460 else if (isa<BlockDecl>(Cur))
6461 Diag(Loc, diag::err_invalid_declarator_in_block)
6462 << Name << SS.getRange();
6463 else if (isa<ExportDecl>(Cur)) {
6464 if (!isa<NamespaceDecl>(DC))
6465 Diag(Loc, diag::err_export_non_namespace_scope_name)
6466 << Name << SS.getRange();
6467 else
6468 // The cases that DC is not NamespaceDecl should be handled in
6469 // CheckRedeclarationExported.
6470 return false;
6471 } else
6472 Diag(Loc, diag::err_invalid_declarator_scope)
6473 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6474
6475 return true;
6476 }
6477
6478 if (Cur->isRecord()) {
6479 // C++26 [temp.expl.spec]p3 (Adopted as a DR in CWG727):
6480 // An explicit specialization may be declared in any scope in which the
6481 // corresponding primary template may be defined.
6482 if (IsMemberSpecialization)
6483 return false;
6484
6485 // Cannot qualify members within a class.
6486 Diag(Loc, diag::err_member_qualification)
6487 << Name << SS.getRange();
6488 SS.clear();
6489
6490 // C++ constructors and destructors with incorrect scopes can break
6491 // our AST invariants by having the wrong underlying types. If
6492 // that's the case, then drop this declaration entirely.
6495 !Context.hasSameType(
6496 Name.getCXXNameType(),
6497 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6498 return true;
6499
6500 return false;
6501 }
6502
6503 // C++23 [temp.names]p5:
6504 // The keyword template shall not appear immediately after a declarative
6505 // nested-name-specifier.
6506 //
6507 // First check the template-id (if any), and then check each component of the
6508 // nested-name-specifier in reverse order.
6509 //
6510 // FIXME: nested-name-specifiers in friend declarations are declarative,
6511 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6512 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6513 Diag(Loc, diag::ext_template_after_declarative_nns)
6515
6517 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6518 TL = std::exchange(NextTL, TypeLoc())) {
6519 SourceLocation TemplateKeywordLoc;
6520 switch (TL.getTypeLocClass()) {
6521 case TypeLoc::TemplateSpecialization: {
6522 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6523 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6524 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6525 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6526 << TST.getLocalSourceRange();
6527 break;
6528 }
6529 case TypeLoc::Decltype:
6530 case TypeLoc::PackIndexing: {
6531 const Type *T = TL.getTypePtr();
6532 // C++23 [expr.prim.id.qual]p2:
6533 // [...] A declarative nested-name-specifier shall not have a
6534 // computed-type-specifier.
6535 //
6536 // CWG2858 changed this from 'decltype-specifier' to
6537 // 'computed-type-specifier'.
6538 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6539 << T->isDecltypeType() << TL.getSourceRange();
6540 break;
6541 }
6542 case TypeLoc::DependentName:
6543 NextTL =
6544 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6545 break;
6546 default:
6547 break;
6548 }
6549 if (TemplateKeywordLoc.isValid())
6550 Diag(Loc, diag::ext_template_after_declarative_nns)
6551 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6552 }
6553
6554 return false;
6555}
6556
6558 MultiTemplateParamsArg TemplateParamLists) {
6559 // TODO: consider using NameInfo for diagnostic.
6561 DeclarationName Name = NameInfo.getName();
6562
6563 // All of these full declarators require an identifier. If it doesn't have
6564 // one, the ParsedFreeStandingDeclSpec action should be used.
6565 if (D.isDecompositionDeclarator()) {
6566 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6567 } else if (!Name) {
6568 if (!D.isInvalidType()) // Reject this if we think it is valid.
6569 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6571 return nullptr;
6573 return nullptr;
6574
6575 DeclContext *DC = CurContext;
6576 if (D.getCXXScopeSpec().isInvalid())
6577 D.setInvalidType();
6578 else if (D.getCXXScopeSpec().isSet()) {
6581 return nullptr;
6582
6583 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6584 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6585 if (!DC || isa<EnumDecl>(DC)) {
6586 // If we could not compute the declaration context, it's because the
6587 // declaration context is dependent but does not refer to a class,
6588 // class template, or class template partial specialization. Complain
6589 // and return early, to avoid the coming semantic disaster.
6591 diag::err_template_qualified_declarator_no_match)
6593 << D.getCXXScopeSpec().getRange();
6594 return nullptr;
6595 }
6596 bool IsDependentContext = DC->isDependentContext();
6597
6598 if (!IsDependentContext &&
6600 return nullptr;
6601
6602 // If a class is incomplete, do not parse entities inside it.
6605 diag::err_member_def_undefined_record)
6606 << Name << DC << D.getCXXScopeSpec().getRange();
6607 return nullptr;
6608 }
6609 if (!D.getDeclSpec().isFriendSpecified()) {
6610 TemplateIdAnnotation *TemplateId =
6612 ? D.getName().TemplateId
6613 : nullptr;
6615 D.getIdentifierLoc(), TemplateId,
6616 /*IsMemberSpecialization=*/false)) {
6617 if (DC->isRecord())
6618 return nullptr;
6619
6620 D.setInvalidType();
6621 } else if (CurContext->isRecord() && !CurContext->Equals(DC)) {
6622 D.setInvalidType();
6623 }
6624 }
6625
6626 // Check whether we need to rebuild the type of the given
6627 // declaration in the current instantiation.
6628 if (EnteringContext && IsDependentContext &&
6629 TemplateParamLists.size() != 0) {
6630 ContextRAII SavedContext(*this, DC);
6631 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6632 D.setInvalidType();
6633 }
6634 }
6635
6637 QualType R = TInfo->getType();
6638
6641 D.setInvalidType();
6642
6643 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6645
6646 // See if this is a redefinition of a variable in the same scope.
6647 if (!D.getCXXScopeSpec().isSet()) {
6648 bool IsLinkageLookup = false;
6649 bool CreateBuiltins = false;
6650
6651 // If the declaration we're planning to build will be a function
6652 // or object with linkage, then look for another declaration with
6653 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6654 //
6655 // If the declaration we're planning to build will be declared with
6656 // external linkage in the translation unit, create any builtin with
6657 // the same name.
6659 /* Do nothing*/;
6660 else if (CurContext->isFunctionOrMethod() &&
6662 R->isFunctionType())) {
6663 IsLinkageLookup = true;
6664 CreateBuiltins =
6665 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6666 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6668 CreateBuiltins = true;
6669
6670 if (IsLinkageLookup) {
6672 Previous.setRedeclarationKind(
6674 }
6675
6676 LookupName(Previous, S, CreateBuiltins);
6677 } else { // Something like "int foo::x;"
6679
6680 // C++ [dcl.meaning]p1:
6681 // When the declarator-id is qualified, the declaration shall refer to a
6682 // previously declared member of the class or namespace to which the
6683 // qualifier refers (or, in the case of a namespace, of an element of the
6684 // inline namespace set of that namespace (7.3.1)) or to a specialization
6685 // thereof; [...]
6686 //
6687 // Note that we already checked the context above, and that we do not have
6688 // enough information to make sure that Previous contains the declaration
6689 // we want to match. For example, given:
6690 //
6691 // class X {
6692 // void f();
6693 // void f(float);
6694 // };
6695 //
6696 // void X::f(int) { } // ill-formed
6697 //
6698 // In this case, Previous will point to the overload set
6699 // containing the two f's declared in X, but neither of them
6700 // matches.
6701
6703 }
6704
6705 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6706 TPD && TPD->isTemplateParameter()) {
6707 // Older versions of clang allowed the names of function/variable templates
6708 // to shadow the names of their template parameters. For the compatibility
6709 // purposes we detect such cases and issue a default-to-error warning that
6710 // can be disabled with -Wno-strict-primary-template-shadow.
6711 if (!D.isInvalidType()) {
6712 bool AllowForCompatibility = false;
6713 if (Scope *DeclParent = S->getDeclParent();
6714 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6715 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6716 TemplateParamParent->isDeclScope(TPD);
6717 }
6719 AllowForCompatibility);
6720 }
6721
6722 // Just pretend that we didn't see the previous declaration.
6723 Previous.clear();
6724 }
6725
6726 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6727 // Forget that the previous declaration is the injected-class-name.
6728 Previous.clear();
6729
6730 // In C++, the previous declaration we find might be a tag type
6731 // (class or enum). In this case, the new declaration will hide the
6732 // tag type. Note that this applies to functions, function templates, and
6733 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6734 if (Previous.isSingleTagDecl() &&
6736 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6737 Previous.clear();
6738
6739 // Check that there are no default arguments other than in the parameters
6740 // of a function declaration (C++ only).
6741 if (getLangOpts().CPlusPlus)
6743
6744 /// Get the innermost enclosing declaration scope.
6745 S = S->getDeclParent();
6746
6747 NamedDecl *New;
6748
6749 bool AddToScope = true;
6751 if (TemplateParamLists.size()) {
6752 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6753 return nullptr;
6754 }
6755
6756 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6757 } else if (R->isFunctionType()) {
6758 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6759 TemplateParamLists,
6760 AddToScope);
6761 } else {
6762 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6763 AddToScope);
6764 }
6765
6766 if (!New)
6767 return nullptr;
6768
6770
6771 // If this has an identifier and is not a function template specialization,
6772 // add it to the scope stack.
6773 if (New->getDeclName() && AddToScope)
6775
6776 if (OpenMP().isInOpenMPDeclareTargetContext())
6778
6779 return New;
6780}
6781
6782/// Helper method to turn variable array types into constant array
6783/// types in certain situations which would otherwise be errors (for
6784/// GCC compatibility).
6786 ASTContext &Context,
6787 bool &SizeIsNegative,
6788 llvm::APSInt &Oversized) {
6789 // This method tries to turn a variable array into a constant
6790 // array even when the size isn't an ICE. This is necessary
6791 // for compatibility with code that depends on gcc's buggy
6792 // constant expression folding, like struct {char x[(int)(char*)2];}
6793 SizeIsNegative = false;
6794 Oversized = 0;
6795
6796 if (T->isDependentType())
6797 return QualType();
6798
6800 const Type *Ty = Qs.strip(T);
6801
6802 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6803 QualType Pointee = PTy->getPointeeType();
6804 QualType FixedType =
6805 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6806 Oversized);
6807 if (FixedType.isNull()) return FixedType;
6808 FixedType = Context.getPointerType(FixedType);
6809 return Qs.apply(Context, FixedType);
6810 }
6811 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6812 QualType Inner = PTy->getInnerType();
6813 QualType FixedType =
6814 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6815 Oversized);
6816 if (FixedType.isNull()) return FixedType;
6817 FixedType = Context.getParenType(FixedType);
6818 return Qs.apply(Context, FixedType);
6819 }
6820
6821 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6822 if (!VLATy)
6823 return QualType();
6824
6825 QualType ElemTy = VLATy->getElementType();
6826 if (ElemTy->isVariablyModifiedType()) {
6827 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6828 SizeIsNegative, Oversized);
6829 if (ElemTy.isNull())
6830 return QualType();
6831 }
6832
6834 if (!VLATy->getSizeExpr() ||
6835 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6836 return QualType();
6837
6838 llvm::APSInt Res = Result.Val.getInt();
6839
6840 // Check whether the array size is negative.
6841 if (Res.isSigned() && Res.isNegative()) {
6842 SizeIsNegative = true;
6843 return QualType();
6844 }
6845
6846 // Check whether the array is too large to be addressed.
6847 unsigned ActiveSizeBits =
6848 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6849 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6850 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6851 : Res.getActiveBits();
6852 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6853 Oversized = std::move(Res);
6854 return QualType();
6855 }
6856
6857 QualType FoldedArrayType = Context.getConstantArrayType(
6858 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6859 return Qs.apply(Context, FoldedArrayType);
6860}
6861
6862static void
6864 SrcTL = SrcTL.getUnqualifiedLoc();
6865 DstTL = DstTL.getUnqualifiedLoc();
6866 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6867 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6868 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6869 DstPTL.getPointeeLoc());
6870 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6871 return;
6872 }
6873 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6874 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6875 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6876 DstPTL.getInnerLoc());
6877 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6878 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6879 return;
6880 }
6881 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6882 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6883 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6884 TypeLoc DstElemTL = DstATL.getElementLoc();
6885 if (VariableArrayTypeLoc SrcElemATL =
6886 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6887 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6888 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6889 } else {
6890 DstElemTL.initializeFullCopy(SrcElemTL);
6891 }
6892 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6893 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6894 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6895}
6896
6897/// Helper method to turn variable array types into constant array
6898/// types in certain situations which would otherwise be errors (for
6899/// GCC compatibility).
6900static TypeSourceInfo*
6902 ASTContext &Context,
6903 bool &SizeIsNegative,
6904 llvm::APSInt &Oversized) {
6905 QualType FixedTy
6906 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6907 SizeIsNegative, Oversized);
6908 if (FixedTy.isNull())
6909 return nullptr;
6910 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6912 FixedTInfo->getTypeLoc());
6913 return FixedTInfo;
6914}
6915
6918 unsigned FailedFoldDiagID) {
6919 bool SizeIsNegative;
6920 llvm::APSInt Oversized;
6922 TInfo, Context, SizeIsNegative, Oversized);
6923 if (FixedTInfo) {
6924 Diag(Loc, diag::ext_vla_folded_to_constant);
6925 TInfo = FixedTInfo;
6926 T = FixedTInfo->getType();
6927 return true;
6928 }
6929
6930 if (SizeIsNegative)
6931 Diag(Loc, diag::err_typecheck_negative_array_size);
6932 else if (Oversized.getBoolValue())
6933 Diag(Loc, diag::err_array_too_large) << toString(
6934 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6935 /*UpperCase=*/false, /*InsertSeparators=*/true);
6936 else if (FailedFoldDiagID)
6937 Diag(Loc, FailedFoldDiagID);
6938 return false;
6939}
6940
6941void
6943 if (!getLangOpts().CPlusPlus &&
6945 // Don't need to track declarations in the TU in C.
6946 return;
6947
6948 // Note that we have a locally-scoped external with this name.
6949 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6950}
6951
6953 // FIXME: We can have multiple results via __attribute__((overloadable)).
6954 auto Result = Context.getExternCContextDecl()->lookup(Name);
6955 return Result.empty() ? nullptr : *Result.begin();
6956}
6957
6959 // FIXME: We should probably indicate the identifier in question to avoid
6960 // confusion for constructs like "virtual int a(), b;"
6961 if (DS.isVirtualSpecified())
6963 diag::err_virtual_non_function);
6964
6965 if (DS.hasExplicitSpecifier())
6967 diag::err_explicit_non_function);
6968
6969 if (DS.isNoreturnSpecified())
6971 diag::err_noreturn_non_function);
6972}
6973
6974NamedDecl*
6977 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6978 if (D.getCXXScopeSpec().isSet()) {
6979 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6980 << D.getCXXScopeSpec().getRange();
6981 D.setInvalidType();
6982 // Pretend we didn't see the scope specifier.
6983 DC = CurContext;
6984 Previous.clear();
6985 }
6986
6988
6991 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6992 ? diag::warn_ms_inline_non_function
6993 : diag::err_inline_non_function)
6994 << getLangOpts().CPlusPlus17;
6996 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6997 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6998
7002 diag::err_deduction_guide_invalid_specifier)
7003 << "typedef";
7004 else
7005 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
7006 << D.getName().getSourceRange();
7007 return nullptr;
7008 }
7009
7010 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
7011 if (!NewTD) return nullptr;
7012
7013 // Handle attributes prior to checking for duplicates in MergeVarDecl
7014 ProcessDeclAttributes(S, NewTD, D);
7015
7017
7018 bool Redeclaration = D.isRedeclaration();
7021 return ND;
7022}
7023
7024void
7026 // C99 6.7.7p2: If a typedef name specifies a variably modified type
7027 // then it shall have block scope.
7028 // Note that variably modified types must be fixed before merging the decl so
7029 // that redeclarations will match.
7030 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
7031 QualType T = TInfo->getType();
7032 if (T->isVariablyModifiedType()) {
7034
7035 if (S->getFnParent() == nullptr) {
7036 bool SizeIsNegative;
7037 llvm::APSInt Oversized;
7038 TypeSourceInfo *FixedTInfo =
7040 SizeIsNegative,
7041 Oversized);
7042 if (FixedTInfo) {
7043 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
7044 NewTD->setTypeSourceInfo(FixedTInfo);
7045 } else {
7046 if (SizeIsNegative)
7047 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
7048 else if (T->isVariableArrayType())
7049 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
7050 else if (Oversized.getBoolValue())
7051 Diag(NewTD->getLocation(), diag::err_array_too_large)
7052 << toString(Oversized, 10);
7053 else
7054 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
7055 NewTD->setInvalidDecl();
7056 }
7057 }
7058 }
7059}
7060
7061NamedDecl*
7064
7065 // Find the shadowed declaration before filtering for scope.
7066 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
7067
7068 // Merge the decl with the existing one if appropriate. If the decl is
7069 // in an outer scope, it isn't the same thing.
7070 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
7071 /*AllowInlineNamespace*/false);
7073 if (!Previous.empty()) {
7074 Redeclaration = true;
7075 MergeTypedefNameDecl(S, NewTD, Previous);
7076 } else {
7078 }
7079
7080 if (ShadowedDecl && !Redeclaration)
7081 CheckShadow(NewTD, ShadowedDecl, Previous);
7082
7083 // If this is the C FILE type, notify the AST context.
7084 if (IdentifierInfo *II = NewTD->getIdentifier())
7085 if (!NewTD->isInvalidDecl() &&
7087 switch (II->getNotableIdentifierID()) {
7088 case tok::NotableIdentifierKind::FILE:
7089 Context.setFILEDecl(NewTD);
7090 break;
7091 case tok::NotableIdentifierKind::jmp_buf:
7092 Context.setjmp_bufDecl(NewTD);
7093 break;
7094 case tok::NotableIdentifierKind::sigjmp_buf:
7095 Context.setsigjmp_bufDecl(NewTD);
7096 break;
7097 case tok::NotableIdentifierKind::ucontext_t:
7098 Context.setucontext_tDecl(NewTD);
7099 break;
7100 case tok::NotableIdentifierKind::float_t:
7101 case tok::NotableIdentifierKind::double_t:
7102 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
7103 break;
7104 default:
7105 break;
7106 }
7107 }
7108
7109 return NewTD;
7110}
7111
7112/// Determines whether the given declaration is an out-of-scope
7113/// previous declaration.
7114///
7115/// This routine should be invoked when name lookup has found a
7116/// previous declaration (PrevDecl) that is not in the scope where a
7117/// new declaration by the same name is being introduced. If the new
7118/// declaration occurs in a local scope, previous declarations with
7119/// linkage may still be considered previous declarations (C99
7120/// 6.2.2p4-5, C++ [basic.link]p6).
7121///
7122/// \param PrevDecl the previous declaration found by name
7123/// lookup
7124///
7125/// \param DC the context in which the new declaration is being
7126/// declared.
7127///
7128/// \returns true if PrevDecl is an out-of-scope previous declaration
7129/// for a new delcaration with the same name.
7130static bool
7132 ASTContext &Context) {
7133 if (!PrevDecl)
7134 return false;
7135
7136 if (!PrevDecl->hasLinkage())
7137 return false;
7138
7139 if (Context.getLangOpts().CPlusPlus) {
7140 // C++ [basic.link]p6:
7141 // If there is a visible declaration of an entity with linkage
7142 // having the same name and type, ignoring entities declared
7143 // outside the innermost enclosing namespace scope, the block
7144 // scope declaration declares that same entity and receives the
7145 // linkage of the previous declaration.
7146 DeclContext *OuterContext = DC->getRedeclContext();
7147 if (!OuterContext->isFunctionOrMethod())
7148 // This rule only applies to block-scope declarations.
7149 return false;
7150
7151 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7152 if (PrevOuterContext->isRecord())
7153 // We found a member function: ignore it.
7154 return false;
7155
7156 // Find the innermost enclosing namespace for the new and
7157 // previous declarations.
7158 OuterContext = OuterContext->getEnclosingNamespaceContext();
7159 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7160
7161 // The previous declaration is in a different namespace, so it
7162 // isn't the same function.
7163 if (!OuterContext->Equals(PrevOuterContext))
7164 return false;
7165 }
7166
7167 return true;
7168}
7169
7171 CXXScopeSpec &SS = D.getCXXScopeSpec();
7172 if (!SS.isSet()) return;
7174}
7175
7178 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7179 // __opencl_c_program_scope_global_variables feature, the address space
7180 // for a variable at program scope or a static or extern variable inside
7181 // a function are inferred to be __global.
7182 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7183 Var->hasGlobalStorage())
7184 ImplAS = LangAS::opencl_global;
7185 Var->assignAddressSpace(Context, ImplAS);
7186}
7187
7189 const WeakAttr &Attr) {
7190 const NamedDecl *D = &ND;
7191 // IFuncAttr is not inherited, so a redeclaration may need to check the
7192 // attributes on the definition instead.
7193 if (const auto *FD = dyn_cast<FunctionDecl>(&ND))
7194 if (const FunctionDecl *Def = FD->getDefinition())
7195 D = Def;
7196 return DiagnoseMutualExclusions(S, D, &Attr);
7197}
7198
7199static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7200 // 'weak' only applies to declarations with external linkage.
7201 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7202 if (!ND.isExternallyVisible()) {
7203 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7204 ND.dropAttr<WeakAttr>();
7205 } else if (!checkWeakAttrCompatibility(S, ND, *Attr)) {
7206 // A forward #pragma weak adds the attribute without checking mutual
7207 // exclusions during attribute processing.
7208 ND.dropAttr<WeakAttr>();
7209 }
7210 }
7211}
7212
7213static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7214 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7215 if (ND.isExternallyVisible()) {
7216 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7217 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7218 }
7219 }
7220}
7221
7222static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7223 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7224 if (VD->hasInit()) {
7225 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7226 assert(VD->isThisDeclarationADefinition() &&
7227 "Broken AliasAttr handled late!");
7228 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7229 VD->dropAttr<AliasAttr>();
7230 }
7231 }
7232 }
7233}
7234
7235static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7236 // 'selectany' only applies to externally visible variable declarations.
7237 // It does not apply to functions.
7238 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7239 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7240 S.Diag(Attr->getLocation(),
7241 diag::err_attribute_selectany_non_extern_data);
7242 ND.dropAttr<SelectAnyAttr>();
7243 }
7244 }
7245}
7246
7248 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7249 if (!ND.isExternallyVisible())
7250 S.Diag(Attr->getLocation(),
7251 diag::warn_attribute_hybrid_patchable_non_extern);
7252 }
7253}
7254
7256 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7257 auto *VD = dyn_cast<VarDecl>(&ND);
7258 bool IsAnonymousNS = false;
7259 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7260 if (VD) {
7261 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7262 while (NS && !IsAnonymousNS) {
7263 IsAnonymousNS = NS->isAnonymousNamespace();
7264 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7265 }
7266 }
7267 // dll attributes require external linkage. Static locals may have external
7268 // linkage but still cannot be explicitly imported or exported.
7269 // In Microsoft mode, a variable defined in anonymous namespace must have
7270 // external linkage in order to be exported.
7271 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7272 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7273 (!AnonNSInMicrosoftMode &&
7274 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7275 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7276 << &ND << Attr;
7277 ND.setInvalidDecl();
7278 }
7279 }
7280}
7281
7283 // Check the attributes on the function type and function params, if any.
7284 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7285 FD = FD->getMostRecentDecl();
7286 // Don't declare this variable in the second operand of the for-statement;
7287 // GCC miscompiles that by ending its lifetime before evaluating the
7288 // third operand. See gcc.gnu.org/PR86769.
7290 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7291 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7292 TL = ATL.getModifiedLoc()) {
7293 // The [[lifetimebound]] attribute can be applied to the implicit object
7294 // parameter of a non-static member function (other than a ctor or dtor)
7295 // by applying it to the function type.
7296 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7297 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7298 int NoImplicitObjectError = -1;
7299 if (!MD)
7300 NoImplicitObjectError = 0;
7301 else if (MD->isStatic())
7302 NoImplicitObjectError = 1;
7303 else if (MD->isExplicitObjectMemberFunction())
7304 NoImplicitObjectError = 2;
7305 if (NoImplicitObjectError != -1) {
7306 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7307 << NoImplicitObjectError << A->getRange();
7308 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7309 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7310 << isa<CXXDestructorDecl>(MD) << A->getRange();
7311 } else if (MD->getReturnType()->isVoidType()) {
7312 S.Diag(
7313 MD->getLocation(),
7314 diag::
7315 err_lifetimebound_implicit_object_parameter_void_return_type);
7316 }
7317 }
7318 }
7319
7320 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7321 const ParmVarDecl *P = FD->getParamDecl(I);
7322
7323 // The [[lifetimebound]] attribute can be applied to a function parameter
7324 // only if the function returns a value.
7325 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7326 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7327 S.Diag(A->getLocation(),
7328 diag::err_lifetimebound_parameter_void_return_type);
7329 }
7330 }
7331 }
7332 }
7333}
7334
7336 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7337 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7338}
7339
7341 // Ensure that an auto decl is deduced otherwise the checks below might cache
7342 // the wrong linkage.
7343 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7344
7345 checkWeakAttr(S, ND);
7346 checkWeakRefAttr(S, ND);
7347 checkAliasAttr(S, ND);
7348 checkSelectAnyAttr(S, ND);
7350 checkInheritableAttr(S, ND);
7352}
7353
7355 NamedDecl *NewDecl,
7356 bool IsSpecialization,
7357 bool IsDefinition) {
7358 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7359 return;
7360
7361 bool IsTemplate = false;
7362 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7363 OldDecl = OldTD->getTemplatedDecl();
7364 IsTemplate = true;
7365 if (!IsSpecialization)
7366 IsDefinition = false;
7367 }
7368 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7369 NewDecl = NewTD->getTemplatedDecl();
7370 IsTemplate = true;
7371 }
7372
7373 if (!OldDecl || !NewDecl)
7374 return;
7375
7376 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7377 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7378 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7379 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7380
7381 // dllimport and dllexport are inheritable attributes so we have to exclude
7382 // inherited attribute instances.
7383 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7384 (NewExportAttr && !NewExportAttr->isInherited());
7385
7386 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7387 // the only exception being explicit specializations.
7388 // Implicitly generated declarations are also excluded for now because there
7389 // is no other way to switch these to use dllimport or dllexport.
7390 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7391
7392 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7393 // Allow with a warning for free functions and global variables.
7394 bool JustWarn = false;
7395 if (!OldDecl->isCXXClassMember()) {
7396 auto *VD = dyn_cast<VarDecl>(OldDecl);
7397 if (VD && !VD->getDescribedVarTemplate())
7398 JustWarn = true;
7399 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7400 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7401 JustWarn = true;
7402 }
7403
7404 // We cannot change a declaration that's been used because IR has already
7405 // been emitted. Dllimported functions will still work though (modulo
7406 // address equality) as they can use the thunk.
7407 if (OldDecl->isUsed())
7408 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7409 JustWarn = false;
7410
7411 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7412 : diag::err_attribute_dll_redeclaration;
7413 S.Diag(NewDecl->getLocation(), DiagID)
7414 << NewDecl
7415 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7416 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7417 if (!JustWarn) {
7418 NewDecl->setInvalidDecl();
7419 return;
7420 }
7421 }
7422
7423 // A redeclaration is not allowed to drop a dllimport attribute, the only
7424 // exceptions being inline function definitions (except for function
7425 // templates), local extern declarations, qualified friend declarations or
7426 // special MSVC extension: in the last case, the declaration is treated as if
7427 // it were marked dllexport.
7428 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7429 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7430 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7431 // Ignore static data because out-of-line definitions are diagnosed
7432 // separately.
7433 IsStaticDataMember = VD->isStaticDataMember();
7434 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7436 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7437 IsInline = FD->isInlined();
7438 IsQualifiedFriend = FD->getQualifier() &&
7439 FD->getFriendObjectKind() == Decl::FOK_Declared;
7440 }
7441
7442 if (OldImportAttr && !HasNewAttr &&
7443 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7444 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7445 if (IsMicrosoftABI && IsDefinition) {
7446 if (IsSpecialization) {
7447 S.Diag(
7448 NewDecl->getLocation(),
7449 diag::err_attribute_dllimport_function_specialization_definition);
7450 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7451 NewDecl->dropAttr<DLLImportAttr>();
7452 } else {
7453 S.Diag(NewDecl->getLocation(),
7454 diag::warn_redeclaration_without_import_attribute)
7455 << NewDecl;
7456 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7457 NewDecl->dropAttr<DLLImportAttr>();
7458 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7459 S.Context, NewImportAttr->getRange()));
7460 }
7461 } else if (IsMicrosoftABI && IsSpecialization) {
7462 assert(!IsDefinition);
7463 // MSVC allows this. Keep the inherited attribute.
7464 } else {
7465 S.Diag(NewDecl->getLocation(),
7466 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7467 << NewDecl << OldImportAttr;
7468 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7469 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7470 OldDecl->dropAttr<DLLImportAttr>();
7471 NewDecl->dropAttr<DLLImportAttr>();
7472 }
7473 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7474 // In MinGW, seeing a function declared inline drops the dllimport
7475 // attribute.
7476 OldDecl->dropAttr<DLLImportAttr>();
7477 NewDecl->dropAttr<DLLImportAttr>();
7478 S.Diag(NewDecl->getLocation(),
7479 diag::warn_dllimport_dropped_from_inline_function)
7480 << NewDecl << OldImportAttr;
7481 }
7482
7483 // A specialization of a class template member function is processed here
7484 // since it's a redeclaration. If the parent class is dllexport, the
7485 // specialization inherits that attribute. This doesn't happen automatically
7486 // since the parent class isn't instantiated until later.
7487 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7488 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7489 !NewImportAttr && !NewExportAttr) {
7490 if (const DLLExportAttr *ParentExportAttr =
7491 MD->getParent()->getAttr<DLLExportAttr>()) {
7492 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7493 NewAttr->setInherited(true);
7494 NewDecl->addAttr(NewAttr);
7495 }
7496 }
7497 }
7498}
7499
7500/// Given that we are within the definition of the given function,
7501/// will that definition behave like C99's 'inline', where the
7502/// definition is discarded except for optimization purposes?
7504 // Try to avoid calling GetGVALinkageForFunction.
7505
7506 // All cases of this require the 'inline' keyword.
7507 if (!FD->isInlined()) return false;
7508
7509 // This is only possible in C++ with the gnu_inline attribute.
7510 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7511 return false;
7512
7513 // Okay, go ahead and call the relatively-more-expensive function.
7515}
7516
7517/// Determine whether a variable is extern "C" prior to attaching
7518/// an initializer. We can't just call isExternC() here, because that
7519/// will also compute and cache whether the declaration is externally
7520/// visible, which might change when we attach the initializer.
7521///
7522/// This can only be used if the declaration is known to not be a
7523/// redeclaration of an internal linkage declaration.
7524///
7525/// For instance:
7526///
7527/// auto x = []{};
7528///
7529/// Attaching the initializer here makes this declaration not externally
7530/// visible, because its type has internal linkage.
7531///
7532/// FIXME: This is a hack.
7533template<typename T>
7534static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7535 if (S.getLangOpts().CPlusPlus) {
7536 // In C++, the overloadable attribute negates the effects of extern "C".
7537 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7538 return false;
7539
7540 // So do CUDA's host/device attributes.
7541 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7542 D->template hasAttr<CUDAHostAttr>()))
7543 return false;
7544 }
7545 return D->isExternC();
7546}
7547
7548static bool shouldConsiderLinkage(const VarDecl *VD) {
7549 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7552 return VD->hasExternalStorage();
7553 if (DC->isFileContext())
7554 return true;
7555 if (DC->isRecord())
7556 return false;
7557 if (DC->getDeclKind() == Decl::HLSLBuffer)
7558 return false;
7559
7561 return false;
7562 llvm_unreachable("Unexpected context");
7563}
7564
7565static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7566 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7567 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7569 return true;
7570 if (DC->isRecord() || isa<CXXExpansionStmtDecl>(DC))
7571 return false;
7572 llvm_unreachable("Unexpected context");
7573}
7574
7575static bool hasParsedAttr(Scope *S, const Declarator &PD,
7576 ParsedAttr::Kind Kind) {
7577 // Check decl attributes on the DeclSpec.
7578 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7579 return true;
7580
7581 // Walk the declarator structure, checking decl attributes that were in a type
7582 // position to the decl itself.
7583 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7584 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7585 return true;
7586 }
7587
7588 // Finally, check attributes on the decl itself.
7589 return PD.getAttributes().hasAttribute(Kind) ||
7591}
7592
7594 if (!DC->isFunctionOrMethod())
7595 return false;
7596
7597 // If this is a local extern function or variable declared within a function
7598 // template, don't add it into the enclosing namespace scope until it is
7599 // instantiated; it might have a dependent type right now.
7600 if (DC->isDependentContext())
7601 return true;
7602
7603 // C++11 [basic.link]p7:
7604 // When a block scope declaration of an entity with linkage is not found to
7605 // refer to some other declaration, then that entity is a member of the
7606 // innermost enclosing namespace.
7607 //
7608 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7609 // semantically-enclosing namespace, not a lexically-enclosing one.
7610 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7611 DC = DC->getParent();
7612 return true;
7613}
7614
7615/// Returns true if given declaration has external C language linkage.
7616static bool isDeclExternC(const Decl *D) {
7617 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7618 return FD->isExternC();
7619 if (const auto *VD = dyn_cast<VarDecl>(D))
7620 return VD->isExternC();
7621
7622 llvm_unreachable("Unknown type of decl!");
7623}
7624
7625/// Returns true if there hasn't been any invalid type diagnosed.
7626static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7627 DeclContext *DC = NewVD->getDeclContext();
7628 QualType R = NewVD->getType();
7629
7630 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7631 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7632 // argument.
7633 if (R->isImageType() || R->isPipeType()) {
7634 Se.Diag(NewVD->getLocation(),
7635 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7636 << R;
7637 NewVD->setInvalidDecl();
7638 return false;
7639 }
7640
7641 // OpenCL v1.2 s6.9.r:
7642 // The event type cannot be used to declare a program scope variable.
7643 // OpenCL v2.0 s6.9.q:
7644 // The clk_event_t and reserve_id_t types cannot be declared in program
7645 // scope.
7646 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7647 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7648 Se.Diag(NewVD->getLocation(),
7649 diag::err_invalid_type_for_program_scope_var)
7650 << R;
7651 NewVD->setInvalidDecl();
7652 return false;
7653 }
7654 }
7655
7656 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7657 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7658 Se.getLangOpts())) {
7659 QualType NR = R.getCanonicalType();
7660 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7661 NR->isReferenceType()) {
7664 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7665 << NR->isReferenceType();
7666 NewVD->setInvalidDecl();
7667 return false;
7668 }
7669 NR = NR->getPointeeType();
7670 }
7671 }
7672
7673 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7674 Se.getLangOpts())) {
7675 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7676 // half array type (unless the cl_khr_fp16 extension is enabled).
7677 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7678 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7679 NewVD->setInvalidDecl();
7680 return false;
7681 }
7682 }
7683
7684 // OpenCL v1.2 s6.9.r:
7685 // The event type cannot be used with the __local, __constant and __global
7686 // address space qualifiers.
7687 if (R->isEventT()) {
7688 if (R.getAddressSpace() != LangAS::opencl_private) {
7689 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7690 NewVD->setInvalidDecl();
7691 return false;
7692 }
7693 }
7694
7695 if (R->isSamplerT()) {
7696 // OpenCL v1.2 s6.9.b p4:
7697 // The sampler type cannot be used with the __local and __global address
7698 // space qualifiers.
7699 if (R.getAddressSpace() == LangAS::opencl_local ||
7700 R.getAddressSpace() == LangAS::opencl_global) {
7701 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7702 NewVD->setInvalidDecl();
7703 }
7704
7705 // OpenCL v1.2 s6.12.14.1:
7706 // A global sampler must be declared with either the constant address
7707 // space qualifier or with the const qualifier.
7708 if (DC->isTranslationUnit() &&
7709 !(R.getAddressSpace() == LangAS::opencl_constant ||
7710 R.isConstQualified())) {
7711 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7712 NewVD->setInvalidDecl();
7713 }
7714 if (NewVD->isInvalidDecl())
7715 return false;
7716 }
7717
7718 return true;
7719}
7720
7721template <typename AttrTy>
7722static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7723 const TypedefNameDecl *TND = TT->getDecl();
7724 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7725 AttrTy *Clone = Attribute->clone(S.Context);
7726 Clone->setInherited(true);
7727 D->addAttr(Clone);
7728 }
7729}
7730
7731// This function emits warning and a corresponding note based on the
7732// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7733// declarations of an annotated type must be const qualified.
7735 QualType VarType = VD->getType().getCanonicalType();
7736
7737 // Ignore local declarations (for now) and those with const qualification.
7738 // TODO: Local variables should not be allowed if their type declaration has
7739 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7740 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7741 return;
7742
7743 if (VarType->isArrayType()) {
7744 // Retrieve element type for array declarations.
7745 VarType = S.getASTContext().getBaseElementType(VarType);
7746 }
7747
7748 const RecordDecl *RD = VarType->getAsRecordDecl();
7749
7750 // Check if the record declaration is present and if it has any attributes.
7751 if (RD == nullptr)
7752 return;
7753
7754 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7755 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7756 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7757 return;
7758 }
7759}
7760
7762 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7763 "NewD is not a function or variable");
7764
7765 if (PendingExportedNames.empty())
7766 return;
7767 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(NewD)) {
7768 if (getLangOpts().CPlusPlus && !FD->isExternC())
7769 return;
7770 }
7771 IdentifierInfo *IdentName = NewD->getIdentifier();
7772 if (IdentName == nullptr)
7773 return;
7774 auto PendingName = PendingExportedNames.find(IdentName);
7775 if (PendingName != PendingExportedNames.end()) {
7776 auto &Label = PendingName->second;
7777 if (!Label.Used) {
7778 Label.Used = true;
7779 if (NewD->hasExternalFormalLinkage())
7780 mergeVisibilityType(NewD, Label.NameLoc, VisibilityAttr::Default);
7781 else
7782 Diag(Label.NameLoc, diag::warn_pragma_not_applied) << "export" << NewD;
7783 }
7784 }
7785}
7786
7787// Checks if VD is declared at global scope or with C language linkage.
7788static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7789 return Name.getAsIdentifierInfo() &&
7790 Name.getAsIdentifierInfo()->isStr("main") &&
7791 !VD->getDescribedVarTemplate() &&
7792 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7793 VD->isExternC());
7794}
7795
7796void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7797 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7798
7799 // Quickly return if the function does not have an `asm` attribute.
7800 if (E == nullptr)
7801 return;
7802
7803 // The parser guarantees this is a string.
7804 StringLiteral *SE = cast<StringLiteral>(E);
7805 StringRef Label = SE->getString();
7806 QualType R = TInfo->getType();
7807 if (R->isIncompleteType())
7808 return;
7809 if (S->getFnParent() != nullptr) {
7810 switch (SC) {
7811 case SC_None:
7812 case SC_Auto:
7813 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7814 break;
7815 case SC_Register:
7816 // Local Named register
7817 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7819 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7820 break;
7821 case SC_Static:
7822 case SC_Extern:
7823 case SC_PrivateExtern:
7824 break;
7825 }
7826 } else if (SC == SC_Register) {
7827 // Global Named register
7828 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7829 const auto &TI = Context.getTargetInfo();
7830 bool HasSizeMismatch;
7831
7832 if (!TI.isValidGCCRegisterName(Label))
7833 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7834 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7835 HasSizeMismatch))
7836 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7837 else if (HasSizeMismatch)
7838 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7839 }
7840
7841 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7842 Diag(TInfo->getTypeLoc().getBeginLoc(),
7843 diag::err_asm_unsupported_register_type)
7844 << TInfo->getTypeLoc().getSourceRange();
7845 NewVD->setInvalidDecl(true);
7846 }
7847 }
7848}
7849
7851 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7852 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7853 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7854 QualType R = TInfo->getType();
7856
7858 bool IsPlaceholderVariable = false;
7859
7860 if (D.isDecompositionDeclarator()) {
7861 // Take the name of the first declarator as our name for diagnostic
7862 // purposes.
7863 auto &Decomp = D.getDecompositionDeclarator();
7864 if (!Decomp.bindings().empty()) {
7865 II = Decomp.bindings()[0].Name;
7866 Name = II;
7867 }
7868 } else if (!II) {
7869 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7870 return nullptr;
7871 }
7872
7873
7876 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7877 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7878
7879 IsPlaceholderVariable = true;
7880
7881 if (!Previous.empty()) {
7882 NamedDecl *PrevDecl = *Previous.begin();
7883 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7884 DC->getRedeclContext());
7885 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7886 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7887 if (IsPlaceholderVariable)
7889 }
7890 }
7891 }
7892
7893 // dllimport globals without explicit storage class are treated as extern. We
7894 // have to change the storage class this early to get the right DeclContext.
7895 if (SC == SC_None && !DC->isRecord() &&
7896 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7897 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7898 SC = SC_Extern;
7899
7900 DeclContext *OriginalDC = DC;
7901 bool IsLocalExternDecl = SC == SC_Extern &&
7903
7904 if (SCSpec == DeclSpec::SCS_mutable) {
7905 // mutable can only appear on non-static class members, so it's always
7906 // an error here
7907 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7908 D.setInvalidType();
7909 SC = SC_None;
7910 }
7911
7912 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7913 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7915 // In C++11, the 'register' storage class specifier is deprecated.
7916 // Suppress the warning in system macros, it's used in macros in some
7917 // popular C system headers, such as in glibc's htonl() macro.
7919 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7920 : diag::warn_deprecated_register)
7922 }
7923
7925
7926 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7927 // C99 6.9p2: The storage-class specifiers auto and register shall not
7928 // appear in the declaration specifiers in an external declaration.
7929 // Global Register+Asm is a GNU extension we support.
7930 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7931 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7932 D.setInvalidType();
7933 }
7934 }
7935
7936 // If this variable has a VLA type and an initializer, try to
7937 // fold to a constant-sized type. This is otherwise invalid.
7938 if (D.hasInitializer() && R->isVariableArrayType())
7940 /*DiagID=*/0);
7941
7942 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7943 const AutoType *AT = TL.getTypePtr();
7944 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7945 }
7946
7947 bool IsMemberSpecialization = false;
7948 bool IsVariableTemplateSpecialization = false;
7949 bool IsPartialSpecialization = false;
7950 bool IsVariableTemplate = false;
7951 VarDecl *NewVD = nullptr;
7952 VarTemplateDecl *NewTemplate = nullptr;
7953 TemplateParameterList *TemplateParams = nullptr;
7954 if (!getLangOpts().CPlusPlus) {
7956 II, R, TInfo, SC);
7957
7958 if (R->getContainedDeducedType())
7959 ParsingInitForAutoVars.insert(NewVD);
7960
7961 if (D.isInvalidType())
7962 NewVD->setInvalidDecl();
7963
7965 NewVD->hasLocalStorage())
7966 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7968 } else {
7969 bool Invalid = false;
7970 // Match up the template parameter lists with the scope specifier, then
7971 // determine whether we have a template or a template specialization.
7974 D.getCXXScopeSpec(),
7976 ? D.getName().TemplateId
7977 : nullptr,
7978 TemplateParamLists,
7979 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7980
7981 if (TemplateParams) {
7982 if (DC->isDependentContext()) {
7983 ContextRAII SavedContext(*this, DC);
7985 Invalid = true;
7986 }
7987
7988 if (!TemplateParams->size() &&
7990 // There is an extraneous 'template<>' for this variable. Complain
7991 // about it, but allow the declaration of the variable.
7992 Diag(TemplateParams->getTemplateLoc(),
7993 diag::err_template_variable_noparams)
7994 << II
7995 << SourceRange(TemplateParams->getTemplateLoc(),
7996 TemplateParams->getRAngleLoc());
7997 TemplateParams = nullptr;
7998 } else {
7999 // Check that we can declare a template here.
8000 if (CheckTemplateDeclScope(S, TemplateParams))
8001 return nullptr;
8002
8004 // This is an explicit specialization or a partial specialization.
8005 IsVariableTemplateSpecialization = true;
8006 IsPartialSpecialization = TemplateParams->size() > 0;
8007 } else { // if (TemplateParams->size() > 0)
8008 // This is a template declaration.
8009 IsVariableTemplate = true;
8010
8011 // Only C++1y supports variable templates (N3651).
8012 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
8013 }
8014 }
8015 } else {
8016 // Check that we can declare a member specialization here.
8017 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
8018 CheckTemplateDeclScope(S, TemplateParamLists.back()))
8019 return nullptr;
8020 assert((Invalid ||
8022 "should have a 'template<>' for this decl");
8023 }
8024
8025 bool IsExplicitSpecialization =
8026 IsVariableTemplateSpecialization && !IsPartialSpecialization;
8027
8028 // C++ [temp.expl.spec]p2:
8029 // The declaration in an explicit-specialization shall not be an
8030 // export-declaration. An explicit specialization shall not use a
8031 // storage-class-specifier other than thread_local.
8032 //
8033 // We use the storage-class-specifier from DeclSpec because we may have
8034 // added implicit 'extern' for declarations with __declspec(dllimport)!
8035 if (SCSpec != DeclSpec::SCS_unspecified &&
8036 (IsExplicitSpecialization || IsMemberSpecialization)) {
8038 diag::ext_explicit_specialization_storage_class)
8040 }
8041
8042 if (CurContext->isRecord()) {
8043 if (SC == SC_Static) {
8044 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
8045 // Walk up the enclosing DeclContexts to check for any that are
8046 // incompatible with static data members.
8047 const DeclContext *FunctionOrMethod = nullptr;
8048 const CXXRecordDecl *AnonStruct = nullptr;
8049 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
8050 if (Ctxt->isFunctionOrMethod()) {
8051 FunctionOrMethod = Ctxt;
8052 break;
8053 }
8054 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
8055 if (ParentDecl && !ParentDecl->getDeclName()) {
8056 AnonStruct = ParentDecl;
8057 break;
8058 }
8059 }
8060 if (FunctionOrMethod) {
8061 // C++ [class.static.data]p5: A local class shall not have static
8062 // data members.
8064 diag::err_static_data_member_not_allowed_in_local_class)
8065 << Name << RD->getDeclName() << RD->getTagKind();
8066 Invalid = true;
8067 } else if (AnonStruct) {
8068 // C++ [class.static.data]p4: Unnamed classes and classes contained
8069 // directly or indirectly within unnamed classes shall not contain
8070 // static data members.
8072 diag::err_static_data_member_not_allowed_in_anon_struct)
8073 << Name << AnonStruct->getTagKind();
8074 Invalid = true;
8075 } else if (RD->isUnion()) {
8076 // C++98 [class.union]p1: If a union contains a static data member,
8077 // the program is ill-formed. C++11 drops this restriction.
8079 diag_compat::static_data_member_in_union)
8080 << Name;
8081 }
8082 }
8083 } else if (IsVariableTemplate || IsPartialSpecialization) {
8084 // There is no such thing as a member field template.
8085 Diag(D.getIdentifierLoc(), diag::err_template_member)
8086 << II << TemplateParams->getSourceRange();
8087 // Recover by pretending this is a static data member template.
8088 SC = SC_Static;
8089 }
8090 } else if (DC->isRecord()) {
8091 // This is an out-of-line definition of a static data member.
8092 switch (SC) {
8093 case SC_None:
8094 break;
8095 case SC_Static:
8097 diag::err_static_out_of_line)
8100 break;
8101 case SC_Auto:
8102 case SC_Register:
8103 case SC_Extern:
8104 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8105 // to names of variables declared in a block or to function parameters.
8106 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8107 // of class members
8108
8110 diag::err_storage_class_for_static_member)
8113 break;
8114 case SC_PrivateExtern:
8115 llvm_unreachable("C storage class in c++!");
8116 }
8117 }
8118
8119 if (IsVariableTemplateSpecialization) {
8120 SourceLocation TemplateKWLoc =
8121 TemplateParamLists.size() > 0
8122 ? TemplateParamLists[0]->getTemplateLoc()
8123 : SourceLocation();
8125 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8127 if (Res.isInvalid())
8128 return nullptr;
8129 NewVD = cast<VarDecl>(Res.get());
8130 AddToScope = false;
8131 } else if (D.isDecompositionDeclarator()) {
8133 D.getIdentifierLoc(), D.getEndLoc(), R,
8134 TInfo, SC, Bindings);
8135 } else
8136 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
8137 D.getIdentifierLoc(), II, R, TInfo, SC);
8138
8139 // If this is supposed to be a variable template, create it as such.
8140 if (IsVariableTemplate) {
8141 NewTemplate =
8143 TemplateParams, NewVD);
8144 NewVD->setDescribedVarTemplate(NewTemplate);
8145 }
8146
8147 // If this decl has an auto type in need of deduction, make a note of the
8148 // Decl so we can diagnose uses of it in its own initializer.
8149 if (R->getContainedDeducedType())
8150 ParsingInitForAutoVars.insert(NewVD);
8151
8152 if (D.isInvalidType() || Invalid) {
8153 NewVD->setInvalidDecl();
8154 if (NewTemplate)
8155 NewTemplate->setInvalidDecl();
8156 }
8157
8158 SetNestedNameSpecifier(*this, NewVD, D);
8159
8160 // If we have any template parameter lists that don't directly belong to
8161 // the variable (matching the scope specifier), store them.
8162 // An explicit variable template specialization does not own any template
8163 // parameter lists.
8164 unsigned VDTemplateParamLists =
8165 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8166 if (TemplateParamLists.size() > VDTemplateParamLists)
8168 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8169 }
8170
8171 if (D.getDeclSpec().isInlineSpecified()) {
8172 if (!getLangOpts().CPlusPlus) {
8173 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8174 << 0;
8175 } else if (CurContext->isFunctionOrMethod()) {
8176 // 'inline' is not allowed on block scope variable declaration.
8178 diag::err_inline_declaration_block_scope) << Name
8180 } else {
8182 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8183 : diag::compat_pre_cxx17_inline_variable);
8184 NewVD->setInlineSpecified();
8185 }
8186 }
8187
8188 // Set the lexical context. If the declarator has a C++ scope specifier, the
8189 // lexical context will be different from the semantic context.
8191 if (NewTemplate)
8192 NewTemplate->setLexicalDeclContext(CurContext);
8193
8194 if (IsLocalExternDecl) {
8196 for (auto *B : Bindings)
8197 B->setLocalExternDecl();
8198 else
8199 NewVD->setLocalExternDecl();
8200 }
8201
8202 bool EmitTLSUnsupportedError = false;
8204 // C++11 [dcl.stc]p4:
8205 // When thread_local is applied to a variable of block scope the
8206 // storage-class-specifier static is implied if it does not appear
8207 // explicitly.
8208 // Core issue: 'static' is not implied if the variable is declared
8209 // 'extern'.
8210 if (NewVD->hasLocalStorage() &&
8211 (SCSpec != DeclSpec::SCS_unspecified ||
8213 !DC->isFunctionOrMethod()))
8215 diag::err_thread_non_global)
8217 else if (!Context.getTargetInfo().isTLSSupported()) {
8218 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8219 // Postpone error emission until we've collected attributes required to
8220 // figure out whether it's a host or device variable and whether the
8221 // error should be ignored.
8222 EmitTLSUnsupportedError = true;
8223 // We still need to mark the variable as TLS so it shows up in AST with
8224 // proper storage class for other tools to use even if we're not going
8225 // to emit any code for it.
8226 NewVD->setTSCSpec(TSCS);
8227 } else
8229 diag::err_thread_unsupported);
8230 } else
8231 NewVD->setTSCSpec(TSCS);
8232 }
8233
8234 switch (D.getDeclSpec().getConstexprSpecifier()) {
8236 break;
8237
8240 diag::err_constexpr_wrong_decl_kind)
8241 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8242 [[fallthrough]];
8243
8245 NewVD->setConstexpr(true);
8246 // C++1z [dcl.spec.constexpr]p1:
8247 // A static data member declared with the constexpr specifier is
8248 // implicitly an inline variable.
8249 if (NewVD->isStaticDataMember() &&
8251 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8252 NewVD->setImplicitlyInline();
8253 break;
8254
8256 if (!NewVD->hasGlobalStorage())
8258 diag::err_constinit_local_variable);
8259 else
8260 NewVD->addAttr(
8261 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8262 ConstInitAttr::Keyword_constinit));
8263 break;
8264 }
8265
8266 // C99 6.7.4p3
8267 // An inline definition of a function with external linkage shall
8268 // not contain a definition of a modifiable object with static or
8269 // thread storage duration...
8270 // We only apply this when the function is required to be defined
8271 // elsewhere, i.e. when the function is not 'extern inline'. Note
8272 // that a local variable with thread storage duration still has to
8273 // be marked 'static'. Also note that it's possible to get these
8274 // semantics in C++ using __attribute__((gnu_inline)).
8275 if (SC == SC_Static && S->getFnParent() != nullptr &&
8276 !NewVD->getType().isConstQualified()) {
8278 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8280 diag::warn_static_local_in_extern_inline);
8282 }
8283 }
8284
8286 if (IsVariableTemplateSpecialization)
8287 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8288 << (IsPartialSpecialization ? 1 : 0)
8291 else if (IsMemberSpecialization)
8292 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8293 << 2
8295 else if (NewVD->hasLocalStorage())
8296 Diag(NewVD->getLocation(), diag::err_module_private_local)
8297 << 0 << NewVD
8301 else {
8302 NewVD->setModulePrivate();
8303 if (NewTemplate)
8304 NewTemplate->setModulePrivate();
8305 for (auto *B : Bindings)
8306 B->setModulePrivate();
8307 }
8308 }
8309
8310 if (getLangOpts().OpenCL) {
8312
8314 if (TSC != TSCS_unspecified) {
8316 diag::err_opencl_unknown_type_specifier)
8318 << DeclSpec::getSpecifierName(TSC) << 1;
8319 NewVD->setInvalidDecl();
8320 }
8321 }
8322
8323 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8324 // address space if the table has local storage (semantic checks elsewhere
8325 // will produce an error anyway).
8326 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8327 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8328 !NewVD->hasLocalStorage()) {
8329 QualType Type = Context.getAddrSpaceQualType(
8330 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8331 NewVD->setType(Type);
8332 }
8333 }
8334
8336
8337 if (Expr *E = D.getAsmLabel()) {
8338 // The parser guarantees this is a string.
8340 StringRef Label = SE->getString();
8341
8342 // Insert the asm attribute.
8343 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8344 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8345 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8347 if (I != ExtnameUndeclaredIdentifiers.end()) {
8348 if (isDeclExternC(NewVD)) {
8349 NewVD->addAttr(I->second);
8351 } else if (NewVD->getDeclContext()
8354 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8355 << /*Variable*/ 1 << NewVD;
8356 }
8357 }
8358
8359 // Handle attributes prior to checking for duplicates in MergeVarDecl
8360 ProcessDeclAttributes(S, NewVD, D);
8361
8362 if (getLangOpts().HLSL)
8364
8365 if (getLangOpts().OpenACC)
8367
8368 // FIXME: This is probably the wrong location to be doing this and we should
8369 // probably be doing this for more attributes (especially for function
8370 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8371 // the code to copy attributes would be generated by TableGen.
8372 if (R->isFunctionPointerType())
8373 if (const auto *TT = R->getAs<TypedefType>())
8375
8376 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8377 if (EmitTLSUnsupportedError &&
8379 (getLangOpts().OpenMPIsTargetDevice &&
8380 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8382 diag::err_thread_unsupported);
8383
8384 if (EmitTLSUnsupportedError &&
8385 (LangOpts.SYCLIsDevice ||
8386 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8387 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8388 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8389 // storage [duration]."
8390 if (SC == SC_None && S->getFnParent() != nullptr &&
8391 (NewVD->hasAttr<CUDASharedAttr>() ||
8392 NewVD->hasAttr<CUDAConstantAttr>())) {
8393 NewVD->setStorageClass(SC_Static);
8394 }
8395 }
8396
8397 // Ensure that dllimport globals without explicit storage class are treated as
8398 // extern. The storage class is set above using parsed attributes. Now we can
8399 // check the VarDecl itself.
8400 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8401 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8402 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8403
8404 // In auto-retain/release, infer strong retension for variables of
8405 // retainable type.
8406 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8407 NewVD->setInvalidDecl();
8408
8409 // Check the ASM label here, as we need to know all other attributes of the
8410 // Decl first. Otherwise, we can't know if the asm label refers to the
8411 // host or device in a CUDA context. The device has other registers than
8412 // host and we must know where the function will be placed.
8413 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8414
8415 // Find the shadowed declaration before filtering for scope.
8416 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8418 : nullptr;
8419
8420 // Don't consider existing declarations that are in a different
8421 // scope and are out-of-semantic-context declarations (if the new
8422 // declaration has linkage).
8425 IsMemberSpecialization ||
8426 IsVariableTemplateSpecialization);
8427
8428 // Check whether the previous declaration is in the same block scope. This
8429 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8430 if (getLangOpts().CPlusPlus &&
8431 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8433 Previous.isSingleResult() && !Previous.isShadowed() &&
8434 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8435
8436 if (!getLangOpts().CPlusPlus) {
8438 } else {
8439 // If this is an explicit specialization of a static data member, check it.
8440 if (IsMemberSpecialization && !IsVariableTemplate &&
8441 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8443 NewVD->setInvalidDecl();
8444
8445 // Merge the decl with the existing one if appropriate.
8446 if (!Previous.empty()) {
8447 if (Previous.isSingleResult() &&
8448 isa<FieldDecl>(Previous.getFoundDecl()) &&
8449 D.getCXXScopeSpec().isSet()) {
8450 // The user tried to define a non-static data member
8451 // out-of-line (C++ [dcl.meaning]p1).
8452 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8453 << D.getCXXScopeSpec().getRange();
8454 Previous.clear();
8455 NewVD->setInvalidDecl();
8456 }
8457 } else if (D.getCXXScopeSpec().isSet() &&
8458 !IsVariableTemplateSpecialization) {
8459 // No previous declaration in the qualifying scope.
8460 Diag(D.getIdentifierLoc(), diag::err_no_member)
8461 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8462 << D.getCXXScopeSpec().getRange();
8463 NewVD->setInvalidDecl();
8464
8465 // if this is a member specialization, we don't have any primary template
8466 // to be instantiated from. We set ourselves to a 'fake' clone of this so
8467 // that anything that attempts to refer to this invalid declaration can
8468 // act as if there IS a primary instantiation.
8469 if (NewTemplate && IsMemberSpecialization) {
8470 VarDecl *FakeVD =
8472 II, R, TInfo, SC);
8473 FakeVD->setInvalidDecl();
8474 VarTemplateDecl *FakeInstantiatedFrom = VarTemplateDecl::Create(
8475 Context, DC, D.getIdentifierLoc(), Name, TemplateParams, FakeVD);
8476 FakeInstantiatedFrom->setInvalidDecl();
8477 NewTemplate->setInstantiatedFromMemberTemplate(FakeInstantiatedFrom);
8478 }
8479 }
8480
8481 if (!IsPlaceholderVariable)
8483
8484 // CheckVariableDeclaration will set NewVD as invalid if something is in
8485 // error like WebAssembly tables being declared as arrays with a non-zero
8486 // size, but then parsing continues and emits further errors on that line.
8487 // To avoid that we check here if it happened and return nullptr.
8488 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8489 return nullptr;
8490
8491 if (NewTemplate) {
8492 VarTemplateDecl *PrevVarTemplate =
8493 NewVD->getPreviousDecl()
8495 : nullptr;
8496
8497 // Check the template parameter list of this declaration, possibly
8498 // merging in the template parameter list from the previous variable
8499 // template declaration.
8501 TemplateParams,
8502 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8503 : nullptr,
8504 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8505 DC->isDependentContext())
8507 : TPC_Other))
8508 NewVD->setInvalidDecl();
8509 }
8510 }
8511
8512 if (IsMemberSpecialization) {
8513 if (NewTemplate && NewVD->getPreviousDecl()) {
8514 NewTemplate->setMemberSpecialization();
8515 } else if (IsPartialSpecialization) {
8517 ->setMemberSpecialization();
8518 }
8519 }
8520
8521 // Diagnose shadowed variables iff this isn't a redeclaration.
8522 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8523 CheckShadow(NewVD, ShadowedDecl, Previous);
8524
8525 ProcessPragmaWeak(S, NewVD);
8526 ProcessPragmaExport(NewVD);
8527
8528 // If this is the first declaration of an extern C variable, update
8529 // the map of such variables.
8530 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8531 isIncompleteDeclExternC(*this, NewVD))
8533
8534 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8536 Decl *ManglingContextDecl;
8537 std::tie(MCtx, ManglingContextDecl) =
8539 if (MCtx) {
8540 Context.setManglingNumber(
8541 NewVD, MCtx->getManglingNumber(
8542 NewVD, getMSManglingNumber(getLangOpts(), S)));
8543 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8544 }
8545 }
8546
8547 // Special handling of variable named 'main'.
8548 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8549 // C++ [basic.start.main]p3:
8550 // A program that declares
8551 // - a variable main at global scope, or
8552 // - an entity named main with C language linkage (in any namespace)
8553 // is ill-formed
8554 if (getLangOpts().CPlusPlus)
8555 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8556 << NewVD->isExternC();
8557
8558 // In C, and external-linkage variable named main results in undefined
8559 // behavior.
8560 else if (NewVD->hasExternalFormalLinkage())
8561 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8562 }
8563
8564 if (D.isRedeclaration() && !Previous.empty()) {
8565 NamedDecl *Prev = Previous.getRepresentativeDecl();
8566 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8568 }
8569
8570 if (NewTemplate) {
8571 if (NewVD->isInvalidDecl())
8572 NewTemplate->setInvalidDecl();
8573 ActOnDocumentableDecl(NewTemplate);
8574 return NewTemplate;
8575 }
8576
8577 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8579
8581
8582 return NewVD;
8583}
8584
8585/// Enum describing the %select options in diag::warn_decl_shadow.
8595
8596/// Determine what kind of declaration we're shadowing.
8598 const DeclContext *OldDC) {
8599 if (isa<TypeAliasDecl>(ShadowedDecl))
8600 return SDK_Using;
8601 else if (isa<TypedefDecl>(ShadowedDecl))
8602 return SDK_Typedef;
8603 else if (isa<BindingDecl>(ShadowedDecl))
8604 return SDK_StructuredBinding;
8605 else if (isa<RecordDecl>(OldDC))
8606 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8607
8608 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8609}
8610
8611/// Return the location of the capture if the given lambda captures the given
8612/// variable \p VD, or an invalid source location otherwise.
8614 const ValueDecl *VD) {
8615 for (const Capture &Capture : LSI->Captures) {
8617 return Capture.getLocation();
8618 }
8619 return SourceLocation();
8620}
8621
8623 const LookupResult &R) {
8624 // Only diagnose if we're shadowing an unambiguous field or variable.
8625 if (R.getResultKind() != LookupResultKind::Found)
8626 return false;
8627
8628 // Return false if warning is ignored.
8629 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8630}
8631
8633 const LookupResult &R) {
8635 return nullptr;
8636
8637 // Don't diagnose declarations at file scope.
8638 if (D->hasGlobalStorage() && !D->isStaticLocal())
8639 return nullptr;
8640
8641 NamedDecl *ShadowedDecl = R.getFoundDecl();
8642 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8643 : nullptr;
8644}
8645
8647 const LookupResult &R) {
8648 // Don't warn if typedef declaration is part of a class
8649 if (D->getDeclContext()->isRecord())
8650 return nullptr;
8651
8653 return nullptr;
8654
8655 NamedDecl *ShadowedDecl = R.getFoundDecl();
8656 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8657}
8658
8660 const LookupResult &R) {
8662 return nullptr;
8663
8664 NamedDecl *ShadowedDecl = R.getFoundDecl();
8665 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8666 : nullptr;
8667}
8668
8670 const LookupResult &R) {
8671 DeclContext *NewDC = D->getDeclContext();
8672
8673 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8675 if (const auto *MD = dyn_cast<CXXMethodDecl>(FnDC)) {
8676 // Fields aren't shadowed in C++ static members or in member functions
8677 // with an explicit object parameter.
8678 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8679 return;
8680 } else if (isa<FunctionDecl>(FnDC)) {
8681 // A FunctionDecl here (not a CXXMethodDecl) can only be an
8682 // inline-defined friend function, since that's the only way to
8683 // introduce a non-member function inside a class body. Friends have
8684 // no implicit `this`, so nothing here can shadow a field.
8685 return;
8686 }
8687 // Fields shadowed by constructor parameters are a special case. Usually
8688 // the constructor initializes the field with the parameter.
8689 if (isa<CXXConstructorDecl>(NewDC))
8690 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8691 // Remember that this was shadowed so we can either warn about its
8692 // modification or its existence depending on warning settings.
8693 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8694 return;
8695 }
8696 }
8697
8698 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8699 if (shadowedVar->isExternC()) {
8700 // For shadowing external vars, make sure that we point to the global
8701 // declaration, not a locally scoped extern declaration.
8702 for (auto *I : shadowedVar->redecls())
8703 if (I->isFileVarDecl()) {
8704 ShadowedDecl = I;
8705 break;
8706 }
8707 }
8708
8709 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8710
8711 unsigned WarningDiag = diag::warn_decl_shadow;
8712 SourceLocation CaptureLoc;
8713 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8714 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8715 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8716 // Handle both VarDecl and BindingDecl in lambda contexts
8717 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8718 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8719 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8720 if (RD->getLambdaCaptureDefault() == LCD_None) {
8721 // Try to avoid warnings for lambdas with an explicit capture
8722 // list. Warn only when the lambda captures the shadowed decl
8723 // explicitly.
8724 CaptureLoc = getCaptureLocation(LSI, VD);
8725 if (CaptureLoc.isInvalid())
8726 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8727 } else {
8728 // Remember that this was shadowed so we can avoid the warning if
8729 // the shadowed decl isn't captured and the warning settings allow
8730 // it.
8732 ->ShadowingDecls.push_back({D, VD});
8733 return;
8734 }
8735 }
8736 if (isa<FieldDecl>(ShadowedDecl)) {
8737 // If lambda can capture this, then emit default shadowing warning,
8738 // Otherwise it is not really a shadowing case since field is not
8739 // available in lambda's body.
8740 // At this point we don't know that lambda can capture this, so
8741 // remember that this was shadowed and delay until we know.
8743 ->ShadowingDecls.push_back({D, ShadowedDecl});
8744 return;
8745 }
8746 }
8747 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8748 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8749 bool HasLocalStorage = false;
8750 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8751 HasLocalStorage = VD->hasLocalStorage();
8752 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8753 HasLocalStorage =
8754 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8755
8756 if (HasLocalStorage) {
8757 // A variable can't shadow a local variable or binding in an enclosing
8758 // scope, if they are separated by a non-capturing declaration
8759 // context.
8760 for (DeclContext *ParentDC = NewDC;
8761 ParentDC && !ParentDC->Equals(OldDC);
8762 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8763 // Only block literals, captured statements, and lambda expressions
8764 // can capture; other scopes don't.
8765 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8766 !isLambdaCallOperator(ParentDC))
8767 return;
8768 }
8769 }
8770 }
8771 }
8772 }
8773
8774 // Never warn about shadowing a placeholder variable.
8775 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8776 return;
8777
8778 // Only warn about certain kinds of shadowing for class members.
8779 if (NewDC) {
8780 // In particular, don't warn about shadowing non-class members.
8781 if (NewDC->isRecord() && !OldDC->isRecord())
8782 return;
8783
8784 // Skip shadowing check if we're in a class scope, dealing with an enum
8785 // constant in a different context.
8786 DeclContext *ReDC = NewDC->getRedeclContext();
8787 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8788 return;
8789
8790 // TODO: should we warn about static data members shadowing
8791 // static data members from base classes?
8792
8793 // TODO: don't diagnose for inaccessible shadowed members.
8794 // This is hard to do perfectly because we might friend the
8795 // shadowing context, but that's just a false negative.
8796 }
8797
8798 DeclarationName Name = R.getLookupName();
8799
8800 // Emit warning and note.
8801 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8802 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8803 if (!CaptureLoc.isInvalid())
8804 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8805 << Name << /*explicitly*/ 1;
8806 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8807}
8808
8810 for (const auto &Shadow : LSI->ShadowingDecls) {
8811 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8812 // Try to avoid the warning when the shadowed decl isn't captured.
8813 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8814 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8815 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8816 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8817 Diag(Shadow.VD->getLocation(),
8818 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8819 : diag::warn_decl_shadow)
8820 << Shadow.VD->getDeclName()
8821 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8822 if (CaptureLoc.isValid())
8823 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8824 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8825 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8826 } else if (isa<FieldDecl>(ShadowedDecl)) {
8827 Diag(Shadow.VD->getLocation(),
8828 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8829 : diag::warn_decl_shadow_uncaptured_local)
8830 << Shadow.VD->getDeclName()
8831 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8832 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8833 }
8834 }
8835}
8836
8838 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8839 return;
8840
8841 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8844 LookupName(R, S);
8845 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8846 CheckShadow(D, ShadowedDecl, R);
8847}
8848
8849/// Check if 'E', which is an expression that is about to be modified, refers
8850/// to a constructor parameter that shadows a field.
8852 // Quickly ignore expressions that can't be shadowing ctor parameters.
8853 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8854 return;
8855 E = E->IgnoreParenImpCasts();
8856 auto *DRE = dyn_cast<DeclRefExpr>(E);
8857 if (!DRE)
8858 return;
8859 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8860 auto I = ShadowingDecls.find(D);
8861 if (I == ShadowingDecls.end())
8862 return;
8863 const NamedDecl *ShadowedDecl = I->second;
8864 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8865 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8866 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8867 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8868
8869 // Avoid issuing multiple warnings about the same decl.
8870 ShadowingDecls.erase(I);
8871}
8872
8873/// Check for conflict between this global or extern "C" declaration and
8874/// previous global or extern "C" declarations. This is only used in C++.
8875template<typename T>
8877 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8878 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8879 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8880
8881 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8882 // The common case: this global doesn't conflict with any extern "C"
8883 // declaration.
8884 return false;
8885 }
8886
8887 if (Prev) {
8888 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8889 // Both the old and new declarations have C language linkage. This is a
8890 // redeclaration.
8891 Previous.clear();
8892 Previous.addDecl(Prev);
8893 return true;
8894 }
8895
8896 // This is a global, non-extern "C" declaration, and there is a previous
8897 // non-global extern "C" declaration. Diagnose if this is a variable
8898 // declaration.
8899 if (!isa<VarDecl>(ND))
8900 return false;
8901 } else {
8902 // The declaration is extern "C". Check for any declaration in the
8903 // translation unit which might conflict.
8904 if (IsGlobal) {
8905 // We have already performed the lookup into the translation unit.
8906 IsGlobal = false;
8907 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8908 I != E; ++I) {
8909 if (isa<VarDecl>(*I)) {
8910 Prev = *I;
8911 break;
8912 }
8913 }
8914 } else {
8916 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8917 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8918 I != E; ++I) {
8919 if (isa<VarDecl>(*I)) {
8920 Prev = *I;
8921 break;
8922 }
8923 // FIXME: If we have any other entity with this name in global scope,
8924 // the declaration is ill-formed, but that is a defect: it breaks the
8925 // 'stat' hack, for instance. Only variables can have mangled name
8926 // clashes with extern "C" declarations, so only they deserve a
8927 // diagnostic.
8928 }
8929 }
8930
8931 if (!Prev)
8932 return false;
8933 }
8934
8935 // Use the first declaration's location to ensure we point at something which
8936 // is lexically inside an extern "C" linkage-spec.
8937 assert(Prev && "should have found a previous declaration to diagnose");
8938 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8939 Prev = FD->getFirstDecl();
8940 else
8941 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8942
8943 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8944 << IsGlobal << ND;
8945 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8946 << IsGlobal;
8947 return false;
8948}
8949
8950/// Apply special rules for handling extern "C" declarations. Returns \c true
8951/// if we have found that this is a redeclaration of some prior entity.
8952///
8953/// Per C++ [dcl.link]p6:
8954/// Two declarations [for a function or variable] with C language linkage
8955/// with the same name that appear in different scopes refer to the same
8956/// [entity]. An entity with C language linkage shall not be declared with
8957/// the same name as an entity in global scope.
8958template<typename T>
8961 if (!S.getLangOpts().CPlusPlus) {
8962 // In C, when declaring a global variable, look for a corresponding 'extern'
8963 // variable declared in function scope. We don't need this in C++, because
8964 // we find local extern decls in the surrounding file-scope DeclContext.
8965 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8966 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8967 Previous.clear();
8968 Previous.addDecl(Prev);
8969 return true;
8970 }
8971 }
8972 return false;
8973 }
8974
8975 // A declaration in the translation unit can conflict with an extern "C"
8976 // declaration.
8977 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8978 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8979
8980 // An extern "C" declaration can conflict with a declaration in the
8981 // translation unit or can be a redeclaration of an extern "C" declaration
8982 // in another scope.
8983 if (isIncompleteDeclExternC(S,ND))
8984 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8985
8986 // Neither global nor extern "C": nothing to do.
8987 return false;
8988}
8989
8990static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8991 QualType T) {
8992 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8993 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8994 // any of its members, even recursively, shall not have an atomic type, or a
8995 // variably modified type, or a type that is volatile or restrict qualified.
8996 if (CanonT->isVariablyModifiedType()) {
8997 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8998 return true;
8999 }
9000
9001 // Arrays are qualified by their element type, so get the base type (this
9002 // works on non-arrays as well).
9003 CanonT = SemaRef.Context.getBaseElementType(CanonT);
9004
9005 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
9006 CanonT.isRestrictQualified()) {
9007 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
9008 return true;
9009 }
9010
9011 if (CanonT->isRecordType()) {
9012 const RecordDecl *RD = CanonT->getAsRecordDecl();
9013 if (!RD->isInvalidDecl() &&
9014 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
9015 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
9016 }))
9017 return true;
9018 }
9019
9020 return false;
9021}
9022
9024 return AS >= LangAS::sycl_global && AS <= LangAS::sycl_constant;
9025}
9026
9028 // If the decl is already known invalid, don't check it.
9029 if (NewVD->isInvalidDecl())
9030 return;
9031
9032 QualType T = NewVD->getType();
9033
9034 // Defer checking an 'auto' type until its initializer is attached.
9035 if (T->isUndeducedType())
9036 return;
9037
9038 if (NewVD->hasAttrs())
9040
9041 if (T->isObjCObjectType()) {
9042 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
9043 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
9044 T = Context.getObjCObjectPointerType(T);
9045 NewVD->setType(T);
9046 }
9047
9048 // The top-level type of a variable declaration cannot have a SYCL address
9049 // space qualifier.
9050 if (getLangOpts().isSYCL()) {
9051 LangAS AS = Context.getBaseElementType(T).getAddressSpace();
9052 if (isSYCLAddressSpace(AS)) {
9053 Diag(NewVD->getLocation(), diag::err_sycl_address_space_qualified_object)
9055 NewVD->setInvalidDecl();
9056 return;
9057 }
9058 }
9059
9060 // Emit an error if an address space was applied to decl with local storage.
9061 // This includes arrays of objects with address space qualifiers, but not
9062 // automatic variables that point to other address spaces.
9063 // ISO/IEC TR 18037 S5.1.2
9064 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
9065 T.getAddressSpace() != LangAS::Default) {
9066 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
9067 NewVD->setInvalidDecl();
9068 return;
9069 }
9070
9071 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
9072 // scope.
9073 if (getLangOpts().OpenCLVersion == 120 &&
9074 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
9075 getLangOpts()) &&
9076 NewVD->isStaticLocal()) {
9077 Diag(NewVD->getLocation(), diag::err_static_function_scope);
9078 NewVD->setInvalidDecl();
9079 return;
9080 }
9081
9082 if (getLangOpts().OpenCL) {
9083 if (!diagnoseOpenCLTypes(*this, NewVD))
9084 return;
9085
9086 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
9087 if (NewVD->hasAttr<BlocksAttr>()) {
9088 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
9089 return;
9090 }
9091
9092 if (T->isBlockPointerType()) {
9093 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
9094 // can't use 'extern' storage class.
9095 if (!T.isConstQualified()) {
9096 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
9097 << 0 /*const*/;
9098 NewVD->setInvalidDecl();
9099 return;
9100 }
9101 if (NewVD->hasExternalStorage()) {
9102 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
9103 NewVD->setInvalidDecl();
9104 return;
9105 }
9106 }
9107
9108 // FIXME: Adding local AS in C++ for OpenCL might make sense.
9109 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
9110 NewVD->hasExternalStorage()) {
9111 if (!T->isSamplerT() && !T->isDependentType() &&
9112 !(T.getAddressSpace() == LangAS::opencl_constant ||
9113 (T.getAddressSpace() == LangAS::opencl_global &&
9114 getOpenCLOptions().areProgramScopeVariablesSupported(
9115 getLangOpts())))) {
9116 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
9117 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
9118 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
9119 << Scope << "global or constant";
9120 else
9121 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
9122 << Scope << "constant";
9123 NewVD->setInvalidDecl();
9124 return;
9125 }
9126 } else {
9127 if (T.getAddressSpace() == LangAS::opencl_global) {
9128 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9129 << 1 /*is any function*/ << "global";
9130 NewVD->setInvalidDecl();
9131 return;
9132 }
9133 // When this extension is enabled, 'local' variables are permitted in
9134 // non-kernel functions and within nested scopes of kernel functions,
9135 // bypassing standard OpenCL address space restrictions.
9136 bool AllowFunctionScopeLocalVariables =
9137 T.getAddressSpace() == LangAS::opencl_local &&
9139 "__cl_clang_function_scope_local_variables", getLangOpts());
9140 if (AllowFunctionScopeLocalVariables) {
9141 // Direct pass: No further diagnostics needed for this specific case.
9142 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9143 T.getAddressSpace() == LangAS::opencl_local) {
9145 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9146 // in functions.
9147 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9148 if (T.getAddressSpace() == LangAS::opencl_constant)
9149 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9150 << 0 /*non-kernel only*/ << "constant";
9151 else
9152 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9153 << 0 /*non-kernel only*/ << "local";
9154 NewVD->setInvalidDecl();
9155 return;
9156 }
9157 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9158 // in the outermost scope of a kernel function.
9159 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9160 if (!getCurScope()->isFunctionScope()) {
9161 if (T.getAddressSpace() == LangAS::opencl_constant)
9162 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9163 << "constant";
9164 else
9165 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9166 << "local";
9167 NewVD->setInvalidDecl();
9168 return;
9169 }
9170 }
9171 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9172 // If we are parsing a template we didn't deduce an addr
9173 // space yet.
9174 T.getAddressSpace() != LangAS::Default) {
9175 // Do not allow other address spaces on automatic variable.
9176 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
9177 NewVD->setInvalidDecl();
9178 return;
9179 }
9180 }
9181 }
9182
9183 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9184 && !NewVD->hasAttr<BlocksAttr>()) {
9185 if (getLangOpts().getGC() != LangOptions::NonGC)
9186 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
9187 else {
9188 assert(!getLangOpts().ObjCAutoRefCount);
9189 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
9190 }
9191 }
9192
9193 // WebAssembly tables must be static with a zero length and can't be
9194 // declared within functions.
9195 if (T->isWebAssemblyTableType()) {
9196 if (getCurScope()->getParent()) { // Parent is null at top-level
9197 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9198 NewVD->setInvalidDecl();
9199 return;
9200 }
9201 if (NewVD->getStorageClass() != SC_Static) {
9202 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9203 NewVD->setInvalidDecl();
9204 return;
9205 }
9206 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9207 if (!ATy || ATy->getZExtSize() != 0) {
9208 Diag(NewVD->getLocation(),
9209 diag::err_typecheck_wasm_table_must_have_zero_length);
9210 NewVD->setInvalidDecl();
9211 return;
9212 }
9213 }
9214
9215 // zero sized static arrays are not allowed in HIP device functions
9216 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9217 if (FunctionDecl *FD = getCurFunctionDecl();
9218 FD &&
9219 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9220 if (const ConstantArrayType *ArrayT =
9221 getASTContext().getAsConstantArrayType(T);
9222 ArrayT && ArrayT->isZeroSize()) {
9223 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9224 }
9225 }
9226 }
9227
9228 bool isVM = T->isVariablyModifiedType();
9229 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9230 NewVD->hasAttr<BlocksAttr>())
9232
9233 if ((isVM && NewVD->hasLinkage()) ||
9234 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9235 bool SizeIsNegative;
9236 llvm::APSInt Oversized;
9238 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9239 QualType FixedT;
9240 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9241 FixedT = FixedTInfo->getType();
9242 else if (FixedTInfo) {
9243 // Type and type-as-written are canonically different. We need to fix up
9244 // both types separately.
9245 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9246 Oversized);
9247 }
9248 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9249 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9250 // FIXME: This won't give the correct result for
9251 // int a[10][n];
9252 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9253
9254 if (NewVD->isFileVarDecl())
9255 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9256 << SizeRange;
9257 else if (NewVD->isStaticLocal())
9258 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9259 << SizeRange;
9260 else
9261 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9262 << SizeRange;
9263 NewVD->setInvalidDecl();
9264 return;
9265 }
9266
9267 if (!FixedTInfo) {
9268 if (NewVD->isFileVarDecl())
9269 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9270 else
9271 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9272 NewVD->setInvalidDecl();
9273 return;
9274 }
9275
9276 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9277 NewVD->setType(FixedT);
9278 NewVD->setTypeSourceInfo(FixedTInfo);
9279 }
9280
9281 if (T->isVoidType()) {
9282 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9283 // of objects and functions.
9285 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9286 << T;
9287 NewVD->setInvalidDecl();
9288 return;
9289 }
9290 }
9291
9292 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9293 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9294 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9295 NewVD->setInvalidDecl();
9296 return;
9297 }
9298
9299 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9300 Diag(NewVD->getLocation(), diag::err_block_not_allowed_on)
9301 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9302 NewVD->setInvalidDecl();
9303 return;
9304 }
9305
9306 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9307 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9308 NewVD->setInvalidDecl();
9309 return;
9310 }
9311
9312 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9313 !T->isDependentType() &&
9315 diag::err_constexpr_var_non_literal)) {
9316 NewVD->setInvalidDecl();
9317 return;
9318 }
9319
9320 // PPC MMA non-pointer types are not allowed as non-local variable types.
9321 if (Context.getTargetInfo().getTriple().isPPC64() &&
9322 !NewVD->isLocalVarDecl() &&
9323 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9324 NewVD->setInvalidDecl();
9325 return;
9326 }
9327
9328 // Check that SVE types are only used in functions with SVE available.
9329 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9331 llvm::StringMap<bool> CallerFeatureMap;
9332 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9333 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9334 CallerFeatureMap)) {
9335 NewVD->setInvalidDecl();
9336 return;
9337 }
9338 }
9339
9340 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9342 llvm::StringMap<bool> CallerFeatureMap;
9343 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9345 CallerFeatureMap);
9346 }
9347
9348 if (Context.getTargetInfo().hasAMDGPUTypes()) {
9349 if (!AMDGPU().checkAMDGPUTypeSupport(T, NewVD->getLocation())) {
9350 NewVD->setInvalidDecl();
9351 return;
9352 }
9353 }
9354
9355 if (T.hasAddressSpace() &&
9356 !CheckVarDeclSizeAddressSpace(NewVD, T.getAddressSpace())) {
9357 NewVD->setInvalidDecl();
9358 return;
9359 }
9360}
9361
9364
9365 // If the decl is already known invalid, don't check it.
9366 if (NewVD->isInvalidDecl())
9367 return false;
9368
9369 // If we did not find anything by this name, look for a non-visible
9370 // extern "C" declaration with the same name.
9371 if (Previous.empty() &&
9373 Previous.setShadowed();
9374
9375 if (!Previous.empty()) {
9376 MergeVarDecl(NewVD, Previous);
9377 return true;
9378 }
9379 return false;
9380}
9381
9384
9385 // Look for methods in base classes that this method might override.
9386 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9387 /*DetectVirtual=*/false);
9388 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9389 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9390 DeclarationName Name = MD->getDeclName();
9391
9393 // We really want to find the base class destructor here.
9394 Name = Context.DeclarationNames.getCXXDestructorName(
9395 Context.getCanonicalTagType(BaseRecord));
9396 }
9397
9398 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9399 CXXMethodDecl *BaseMD =
9400 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9401 if (!BaseMD || !BaseMD->isVirtual() ||
9402 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9403 /*ConsiderCudaAttrs=*/true))
9404 continue;
9405 if (!CheckExplicitObjectOverride(MD, BaseMD))
9406 continue;
9407 if (Overridden.insert(BaseMD).second) {
9408 MD->addOverriddenMethod(BaseMD);
9413 }
9414
9415 // A method can only override one function from each base class. We
9416 // don't track indirectly overridden methods from bases of bases.
9417 return true;
9418 }
9419
9420 return false;
9421 };
9422
9423 DC->lookupInBases(VisitBase, Paths);
9424 return !Overridden.empty();
9425}
9426
9427namespace {
9428 // Struct for holding all of the extra arguments needed by
9429 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9430 struct ActOnFDArgs {
9431 Scope *S;
9432 Declarator &D;
9433 MultiTemplateParamsArg TemplateParamLists;
9434 bool AddToScope;
9435 };
9436} // end anonymous namespace
9437
9438namespace {
9439
9440// Callback to only accept typo corrections that have a non-zero edit distance.
9441// Also only accept corrections that have the same parent decl.
9442class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9443 public:
9444 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9445 CXXRecordDecl *Parent)
9446 : Context(Context), OriginalFD(TypoFD),
9447 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9448
9449 bool ValidateCandidate(const TypoCorrection &candidate) override {
9450 if (candidate.getEditDistance() == 0)
9451 return false;
9452
9453 SmallVector<unsigned, 1> MismatchedParams;
9454 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9455 CDeclEnd = candidate.end();
9456 CDecl != CDeclEnd; ++CDecl) {
9457 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9458
9459 if (FD && !FD->hasBody() &&
9460 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9461 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9462 CXXRecordDecl *Parent = MD->getParent();
9463 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9464 return true;
9465 } else if (!ExpectedParent) {
9466 return true;
9467 }
9468 }
9469 }
9470
9471 return false;
9472 }
9473
9474 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9475 return std::make_unique<DifferentNameValidatorCCC>(*this);
9476 }
9477
9478 private:
9479 ASTContext &Context;
9480 FunctionDecl *OriginalFD;
9481 CXXRecordDecl *ExpectedParent;
9482};
9483
9484} // end anonymous namespace
9485
9489
9490/// Generate diagnostics for an invalid function redeclaration.
9491///
9492/// This routine handles generating the diagnostic messages for an invalid
9493/// function redeclaration, including finding possible similar declarations
9494/// or performing typo correction if there are no previous declarations with
9495/// the same name.
9496///
9497/// Returns a NamedDecl iff typo correction was performed and substituting in
9498/// the new declaration name does not cause new errors.
9500 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9501 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9502 DeclarationName Name = NewFD->getDeclName();
9503 DeclContext *NewDC = NewFD->getDeclContext();
9504 SmallVector<unsigned, 1> MismatchedParams;
9506 TypoCorrection Correction;
9507 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9508 unsigned DiagMsg =
9509 IsLocalFriend ? diag::err_no_matching_local_friend :
9510 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9511 diag::err_member_decl_does_not_match;
9512 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9513 IsLocalFriend ? Sema::LookupLocalFriendName
9516
9517 NewFD->setInvalidDecl();
9518 if (IsLocalFriend)
9519 SemaRef.LookupName(Prev, S);
9520 else
9521 SemaRef.LookupQualifiedName(Prev, NewDC);
9522 assert(!Prev.isAmbiguous() &&
9523 "Cannot have an ambiguity in previous-declaration lookup");
9524 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9525 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9526 MD ? MD->getParent() : nullptr);
9527 if (!Prev.empty()) {
9528 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9529 Func != FuncEnd; ++Func) {
9530 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9531 if (FD &&
9532 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9533 // Add 1 to the index so that 0 can mean the mismatch didn't
9534 // involve a parameter
9535 unsigned ParamNum =
9536 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9537 NearMatches.push_back(std::make_pair(FD, ParamNum));
9538 }
9539 }
9540 // If the qualified name lookup yielded nothing, try typo correction
9541 } else if ((Correction = SemaRef.CorrectTypo(
9542 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9543 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9545 IsLocalFriend ? nullptr : NewDC))) {
9546 // Set up everything for the call to ActOnFunctionDeclarator
9547 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9548 ExtraArgs.D.getIdentifierLoc());
9549 Previous.clear();
9550 Previous.setLookupName(Correction.getCorrection());
9551 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9552 CDeclEnd = Correction.end();
9553 CDecl != CDeclEnd; ++CDecl) {
9554 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9555 if (FD && !FD->hasBody() &&
9556 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9557 Previous.addDecl(FD);
9558 }
9559 }
9560 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9561
9563 // Retry building the function declaration with the new previous
9564 // declarations, and with errors suppressed.
9565 {
9566 // Trap errors.
9567 Sema::SFINAETrap Trap(SemaRef);
9568
9569 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9570 // pieces need to verify the typo-corrected C++ declaration and hopefully
9571 // eliminate the need for the parameter pack ExtraArgs.
9573 ExtraArgs.S, ExtraArgs.D,
9574 Correction.getCorrectionDecl()->getDeclContext(),
9575 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9576 ExtraArgs.AddToScope);
9577
9578 if (Trap.hasErrorOccurred())
9579 Result = nullptr;
9580 }
9581
9582 if (Result) {
9583 // Determine which correction we picked.
9584 Decl *Canonical = Result->getCanonicalDecl();
9585 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9586 I != E; ++I)
9587 if ((*I)->getCanonicalDecl() == Canonical)
9588 Correction.setCorrectionDecl(*I);
9589
9590 // Let Sema know about the correction.
9592 SemaRef.diagnoseTypo(
9593 Correction,
9594 SemaRef.PDiag(IsLocalFriend
9595 ? diag::err_no_matching_local_friend_suggest
9596 : diag::err_member_decl_does_not_match_suggest)
9597 << Name << NewDC << IsDefinition);
9598 return Result;
9599 }
9600
9601 // Pretend the typo correction never occurred
9602 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9603 ExtraArgs.D.getIdentifierLoc());
9604 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9605 Previous.clear();
9606 Previous.setLookupName(Name);
9607 }
9608
9609 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9610 << Name << NewDC << IsDefinition << NewFD->getLocation();
9611
9612 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9613 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9614 CXXRecordDecl *RD = NewMD->getParent();
9615 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9616 << RD->getName() << RD->getLocation();
9617 }
9618
9619 bool NewFDisConst = NewMD && NewMD->isConst();
9620
9621 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9622 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9623 NearMatch != NearMatchEnd; ++NearMatch) {
9624 FunctionDecl *FD = NearMatch->first;
9625 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9626 bool FDisConst = MD && MD->isConst();
9627 bool IsMember = MD || !IsLocalFriend;
9628
9629 // FIXME: These notes are poorly worded for the local friend case.
9630 if (unsigned Idx = NearMatch->second) {
9631 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9632 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9633 if (Loc.isInvalid()) Loc = FD->getLocation();
9634 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9635 : diag::note_local_decl_close_param_match)
9636 << Idx << FDParam->getType()
9637 << NewFD->getParamDecl(Idx - 1)->getType();
9638 } else if (FDisConst != NewFDisConst) {
9639 auto DB = SemaRef.Diag(FD->getLocation(),
9640 diag::note_member_def_close_const_match)
9641 << NewFDisConst << FD->getSourceRange().getEnd();
9642 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9643 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9644 " const");
9645 else if (FTI.hasMethodTypeQualifiers() &&
9646 FTI.getConstQualifierLoc().isValid())
9647 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9648 } else {
9649 SemaRef.Diag(FD->getLocation(),
9650 IsMember ? diag::note_member_def_close_match
9651 : diag::note_local_decl_close_match);
9652 }
9653 }
9654 return nullptr;
9655}
9656
9658 switch (D.getDeclSpec().getStorageClassSpec()) {
9659 default: llvm_unreachable("Unknown storage class!");
9660 case DeclSpec::SCS_auto:
9664 diag::err_typecheck_sclass_func);
9666 D.setInvalidType();
9667 break;
9668 case DeclSpec::SCS_unspecified: break;
9671 return SC_None;
9672 return SC_Extern;
9673 case DeclSpec::SCS_static: {
9675 // C99 6.7.1p5:
9676 // The declaration of an identifier for a function that has
9677 // block scope shall have no explicit storage-class specifier
9678 // other than extern
9679 // See also (C++ [dcl.stc]p4).
9681 diag::err_static_block_func);
9682 break;
9683 } else
9684 return SC_Static;
9685 }
9687 }
9688
9689 // No explicit storage class has already been returned
9690 return SC_None;
9691}
9692
9694 DeclContext *DC, QualType &R,
9695 TypeSourceInfo *TInfo,
9696 StorageClass SC,
9697 bool &IsVirtualOkay) {
9698 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9699 DeclarationName Name = NameInfo.getName();
9700
9701 FunctionDecl *NewFD = nullptr;
9702 bool isInline = D.getDeclSpec().isInlineSpecified();
9703
9705 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9706 (SemaRef.getLangOpts().C23 &&
9707 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9708
9709 if (SemaRef.getLangOpts().C23)
9710 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9711 diag::err_c23_constexpr_not_variable);
9712 else
9713 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9714 diag::err_constexpr_wrong_decl_kind)
9715 << static_cast<int>(ConstexprKind);
9716 ConstexprKind = ConstexprSpecKind::Unspecified;
9718 }
9719
9720 if (!SemaRef.getLangOpts().CPlusPlus) {
9721 // Determine whether the function was written with a prototype. This is
9722 // true when:
9723 // - there is a prototype in the declarator, or
9724 // - the type R of the function is some kind of typedef or other non-
9725 // attributed reference to a type name (which eventually refers to a
9726 // function type). Note, we can't always look at the adjusted type to
9727 // check this case because attributes may cause a non-function
9728 // declarator to still have a function type. e.g.,
9729 // typedef void func(int a);
9730 // __attribute__((noreturn)) func other_func; // This has a prototype
9731 bool HasPrototype =
9733 (D.getDeclSpec().isTypeRep() &&
9734 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9735 ->isFunctionProtoType()) ||
9736 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9737 assert(
9738 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9739 "Strict prototypes are required");
9740
9741 NewFD = FunctionDecl::Create(
9742 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9743 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9745 /*TrailingRequiresClause=*/{});
9746 if (D.isInvalidType())
9747 NewFD->setInvalidDecl();
9748
9749 return NewFD;
9750 }
9751
9753 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9754
9755 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9756
9758 // This is a C++ constructor declaration.
9759 assert(DC->isRecord() &&
9760 "Constructors can only be declared in a member context");
9761
9762 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9764 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9766 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9767 InheritedConstructor(), TrailingRequiresClause);
9768
9769 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9770 // This is a C++ destructor declaration.
9771 if (DC->isRecord()) {
9772 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9775 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9776 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9777 /*isImplicitlyDeclared=*/false, ConstexprKind,
9778 TrailingRequiresClause);
9779 // User defined destructors start as not selected if the class definition is still
9780 // not done.
9781 if (Record->isBeingDefined())
9782 NewDD->setIneligibleOrNotSelected(true);
9783
9784 // If the destructor needs an implicit exception specification, set it
9785 // now. FIXME: It'd be nice to be able to create the right type to start
9786 // with, but the type needs to reference the destructor declaration.
9787 if (SemaRef.getLangOpts().CPlusPlus11)
9788 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9789
9790 IsVirtualOkay = true;
9791 return NewDD;
9792
9793 } else {
9794 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9795 D.setInvalidType();
9796
9797 // Create a FunctionDecl to satisfy the function definition parsing
9798 // code path.
9799 return FunctionDecl::Create(
9800 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9801 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9802 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9803 }
9804
9806 if (!DC->isRecord()) {
9807 SemaRef.Diag(D.getIdentifierLoc(),
9808 diag::err_conv_function_not_member);
9809 return nullptr;
9810 }
9811
9812 SemaRef.CheckConversionDeclarator(D, R, SC);
9813 if (D.isInvalidType())
9814 return nullptr;
9815
9816 IsVirtualOkay = true;
9818 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9819 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9820 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9821 TrailingRequiresClause);
9822
9824 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9825 return nullptr;
9827 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9828 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9829 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9830 } else if (DC->isRecord()) {
9831 // If the name of the function is the same as the name of the record,
9832 // then this must be an invalid constructor that has a return type.
9833 // (The parser checks for a return type and makes the declarator a
9834 // constructor if it has no return type).
9835 if (Name.getAsIdentifierInfo() &&
9836 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9837 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9840 return nullptr;
9841 }
9842
9843 // This is a C++ method declaration.
9845 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9846 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9847 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9848 IsVirtualOkay = !Ret->isStatic();
9849 return Ret;
9850 } else {
9851 bool isFriend =
9852 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9853 if (!isFriend && SemaRef.CurContext->isRecord())
9854 return nullptr;
9855
9856 // Determine whether the function was written with a
9857 // prototype. This true when:
9858 // - we're in C++ (where every function has a prototype),
9859 return FunctionDecl::Create(
9860 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9861 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9862 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9863 }
9864}
9865
9874
9876 // Size dependent types are just typedefs to normal integer types
9877 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9878 // integers other than by their names.
9879 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9880
9881 // Remove typedefs one by one until we reach a typedef
9882 // for a size dependent type.
9883 QualType DesugaredTy = Ty;
9884 do {
9885 ArrayRef<StringRef> Names(SizeTypeNames);
9886 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9887 if (Names.end() != Match)
9888 return true;
9889
9890 Ty = DesugaredTy;
9891 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9892 } while (DesugaredTy != Ty);
9893
9894 return false;
9895}
9896
9898 if (PT->isDependentType())
9899 return InvalidKernelParam;
9900
9901 if (PT->isPointerOrReferenceType()) {
9902 QualType PointeeType = PT->getPointeeType();
9903 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9904 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9905 PointeeType.getAddressSpace() == LangAS::Default)
9907
9908 if (PointeeType->isPointerType()) {
9909 // This is a pointer to pointer parameter.
9910 // Recursively check inner type.
9911 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9912 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9913 ParamKind == InvalidKernelParam)
9914 return ParamKind;
9915
9916 // OpenCL v3.0 s6.11.a:
9917 // A restriction to pass pointers to pointers only applies to OpenCL C
9918 // v1.2 or below.
9920 return ValidKernelParam;
9921
9922 return PtrPtrKernelParam;
9923 }
9924
9925 // C++ for OpenCL v1.0 s2.4:
9926 // Moreover the types used in parameters of the kernel functions must be:
9927 // Standard layout types for pointer parameters. The same applies to
9928 // reference if an implementation supports them in kernel parameters.
9929 if (S.getLangOpts().OpenCLCPlusPlus &&
9931 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9932 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9933 bool IsStandardLayoutType = true;
9934 if (CXXRec) {
9935 // If template type is not ODR-used its definition is only available
9936 // in the template definition not its instantiation.
9937 // FIXME: This logic doesn't work for types that depend on template
9938 // parameter (PR58590).
9939 if (!CXXRec->hasDefinition())
9940 CXXRec = CXXRec->getTemplateInstantiationPattern();
9941 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9942 IsStandardLayoutType = false;
9943 }
9944 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9945 !IsStandardLayoutType)
9946 return InvalidKernelParam;
9947 }
9948
9949 // OpenCL v1.2 s6.9.p:
9950 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9952 return ValidKernelParam;
9953
9954 return PtrKernelParam;
9955 }
9956
9957 // OpenCL v1.2 s6.9.k:
9958 // Arguments to kernel functions in a program cannot be declared with the
9959 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9960 // uintptr_t or a struct and/or union that contain fields declared to be one
9961 // of these built-in scalar types.
9963 return InvalidKernelParam;
9964
9965 if (PT->isImageType())
9966 return PtrKernelParam;
9967
9968 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9969 return InvalidKernelParam;
9970
9971 // OpenCL extension spec v1.2 s9.5:
9972 // This extension adds support for half scalar and vector types as built-in
9973 // types that can be used for arithmetic operations, conversions etc.
9974 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9975 PT->isHalfType())
9976 return InvalidKernelParam;
9977
9978 // Look into an array argument to check if it has a forbidden type.
9979 if (PT->isArrayType()) {
9980 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9981 // Call ourself to check an underlying type of an array. Since the
9982 // getPointeeOrArrayElementType returns an innermost type which is not an
9983 // array, this recursive call only happens once.
9984 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9985 }
9986
9987 // C++ for OpenCL v1.0 s2.4:
9988 // Moreover the types used in parameters of the kernel functions must be:
9989 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9990 // types) for parameters passed by value;
9991 if (S.getLangOpts().OpenCLCPlusPlus &&
9993 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9994 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9995 return InvalidKernelParam;
9996
9997 if (PT->isRecordType())
9998 return RecordKernelParam;
9999
10000 return ValidKernelParam;
10001}
10002
10004 Sema &S,
10005 Declarator &D,
10006 ParmVarDecl *Param,
10007 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
10008 QualType PT = Param->getType();
10009
10010 // Cache the valid types we encounter to avoid rechecking structs that are
10011 // used again
10012 if (ValidTypes.count(PT.getTypePtr()))
10013 return;
10014
10015 switch (getOpenCLKernelParameterType(S, PT)) {
10016 case PtrPtrKernelParam:
10017 // OpenCL v3.0 s6.11.a:
10018 // A kernel function argument cannot be declared as a pointer to a pointer
10019 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
10020 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
10021 D.setInvalidType();
10022 return;
10023
10025 // OpenCL v1.0 s6.5:
10026 // __kernel function arguments declared to be a pointer of a type can point
10027 // to one of the following address spaces only : __global, __local or
10028 // __constant.
10029 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
10030 D.setInvalidType();
10031 return;
10032
10033 // OpenCL v1.2 s6.9.k:
10034 // Arguments to kernel functions in a program cannot be declared with the
10035 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
10036 // uintptr_t or a struct and/or union that contain fields declared to be
10037 // one of these built-in scalar types.
10038
10039 case InvalidKernelParam:
10040 // OpenCL v1.2 s6.8 n:
10041 // A kernel function argument cannot be declared
10042 // of event_t type.
10043 // Do not diagnose half type since it is diagnosed as invalid argument
10044 // type for any function elsewhere.
10045 if (!PT->isHalfType()) {
10046 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
10047
10048 // Explain what typedefs are involved.
10049 const TypedefType *Typedef = nullptr;
10050 while ((Typedef = PT->getAs<TypedefType>())) {
10051 SourceLocation Loc = Typedef->getDecl()->getLocation();
10052 // SourceLocation may be invalid for a built-in type.
10053 if (Loc.isValid())
10054 S.Diag(Loc, diag::note_entity_declared_at) << PT;
10055 PT = Typedef->desugar();
10056 }
10057 }
10058
10059 D.setInvalidType();
10060 return;
10061
10062 case PtrKernelParam:
10063 case ValidKernelParam:
10064 ValidTypes.insert(PT.getTypePtr());
10065 return;
10066
10067 case RecordKernelParam:
10068 break;
10069 }
10070
10071 // Track nested structs we will inspect
10073
10074 // Track where we are in the nested structs. Items will migrate from
10075 // VisitStack to HistoryStack as we do the DFS for bad field.
10077 HistoryStack.push_back(nullptr);
10078
10079 // At this point we already handled everything except of a RecordType.
10080 assert(PT->isRecordType() && "Unexpected type.");
10081 const auto *PD = PT->castAsRecordDecl();
10082 VisitStack.push_back(PD);
10083 assert(VisitStack.back() && "First decl null?");
10084
10085 do {
10086 const Decl *Next = VisitStack.pop_back_val();
10087 if (!Next) {
10088 assert(!HistoryStack.empty());
10089 // Found a marker, we have gone up a level
10090 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
10091 ValidTypes.insert(Hist->getType().getTypePtr());
10092
10093 continue;
10094 }
10095
10096 // Adds everything except the original parameter declaration (which is not a
10097 // field itself) to the history stack.
10098 const RecordDecl *RD;
10099 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
10100 HistoryStack.push_back(Field);
10101
10102 QualType FieldTy = Field->getType();
10103 // Other field types (known to be valid or invalid) are handled while we
10104 // walk around RecordDecl::fields().
10105 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
10106 "Unexpected type.");
10107 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
10108
10109 RD = FieldRecTy->castAsRecordDecl();
10110 } else {
10111 RD = cast<RecordDecl>(Next);
10112 }
10113
10114 // Add a null marker so we know when we've gone back up a level
10115 VisitStack.push_back(nullptr);
10116
10117 for (const auto *FD : RD->fields()) {
10118 QualType QT = FD->getType();
10119
10120 if (ValidTypes.count(QT.getTypePtr()))
10121 continue;
10122
10124 if (ParamType == ValidKernelParam)
10125 continue;
10126
10127 if (ParamType == RecordKernelParam) {
10128 VisitStack.push_back(FD);
10129 continue;
10130 }
10131
10132 // OpenCL v1.2 s6.9.p:
10133 // Arguments to kernel functions that are declared to be a struct or union
10134 // do not allow OpenCL objects to be passed as elements of the struct or
10135 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10136 // of SVM.
10137 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10138 ParamType == InvalidAddrSpacePtrKernelParam) {
10139 S.Diag(Param->getLocation(),
10140 diag::err_record_with_pointers_kernel_param)
10141 << PT->isUnionType()
10142 << PT;
10143 } else {
10144 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
10145 }
10146
10147 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
10148 << PD->getDeclName();
10149
10150 // We have an error, now let's go back up through history and show where
10151 // the offending field came from
10153 I = HistoryStack.begin() + 1,
10154 E = HistoryStack.end();
10155 I != E; ++I) {
10156 const FieldDecl *OuterField = *I;
10157 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
10158 << OuterField->getType();
10159 }
10160
10161 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
10162 << QT->isPointerType()
10163 << QT;
10164 D.setInvalidType();
10165 return;
10166 }
10167 } while (!VisitStack.empty());
10168}
10169
10170/// Find the DeclContext in which a tag is implicitly declared if we see an
10171/// elaborated type specifier in the specified context, and lookup finds
10172/// nothing.
10174 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10175 DC = DC->getParent();
10176 return DC;
10177}
10178
10179/// Find the Scope in which a tag is implicitly declared if we see an
10180/// elaborated type specifier in the specified context, and lookup finds
10181/// nothing.
10182static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10183 while (S->isClassScope() ||
10184 (LangOpts.CPlusPlus &&
10186 ((S->getFlags() & Scope::DeclScope) == 0) ||
10187 (S->getEntity() && S->getEntity()->isTransparentContext()))
10188 S = S->getParent();
10189 return S;
10190}
10191
10192/// Determine whether a declaration matches a known function in namespace std.
10194 unsigned BuiltinID) {
10195 switch (BuiltinID) {
10196 case Builtin::BI__GetExceptionInfo:
10197 // No type checking whatsoever.
10198 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10199
10200 case Builtin::BIaddressof:
10201 case Builtin::BI__addressof:
10202 case Builtin::BIforward:
10203 case Builtin::BIforward_like:
10204 case Builtin::BImove:
10205 case Builtin::BImove_if_noexcept:
10206 case Builtin::BIas_const: {
10207 // Ensure that we don't treat the algorithm
10208 // OutputIt std::move(InputIt, InputIt, OutputIt)
10209 // as the builtin std::move.
10210 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10211 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10212 }
10213
10214 default:
10215 return false;
10216 }
10217}
10218
10220 const auto *FT = FD->getType()->getAs<FunctionType>();
10221 if (!FT)
10222 return;
10223
10224 StringRef Tag;
10225 switch (FT->getCallConv()) {
10226#define CC_VLS_CASE(ABI_VLEN) \
10227 case CC_RISCVVLSCall_##ABI_VLEN: \
10228 Tag = "riscv_vls_cc_" #ABI_VLEN; \
10229 break;
10230 CC_VLS_CASE(32)
10231 CC_VLS_CASE(64)
10232 CC_VLS_CASE(128)
10233 CC_VLS_CASE(256)
10234 CC_VLS_CASE(512)
10235 CC_VLS_CASE(1024)
10236 CC_VLS_CASE(2048)
10237 CC_VLS_CASE(4096)
10238 CC_VLS_CASE(8192)
10239 CC_VLS_CASE(16384)
10240 CC_VLS_CASE(32768)
10241 CC_VLS_CASE(65536)
10242#undef CC_VLS_CASE
10243 default:
10244 return;
10245 }
10246
10247 SmallVector<AbiTagAttr *, 2> Existing(FD->specific_attrs<AbiTagAttr>());
10248 AbiTagAttr *Old = Existing.empty() ? nullptr : Existing.front();
10249
10251 if (Old)
10252 llvm::append_range(Tags, Old->tags());
10253 if (llvm::is_contained(Tags, Tag))
10254 return;
10255 Tags.push_back(Tag);
10256
10257 AbiTagAttr *Merged =
10258 Old ? AbiTagAttr::Create(Context, Tags.data(), Tags.size(), *Old)
10259 : AbiTagAttr::CreateImplicit(Context, Tags.data(), Tags.size(),
10260 FD->getLocation());
10261 FD->dropAttr<AbiTagAttr>();
10262 FD->addAttr(Merged);
10263 for (size_t I = 1, E = Existing.size(); I < E; ++I)
10264 FD->addAttr(Existing[I]);
10265}
10266
10267NamedDecl*
10270 MultiTemplateParamsArg TemplateParamListsRef,
10271 bool &AddToScope) {
10272 QualType R = TInfo->getType();
10273
10274 assert(R->isFunctionType());
10275 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10276 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10277
10278 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10279 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10281 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10282 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10283 TemplateParamLists.back() = Invented;
10284 else
10285 TemplateParamLists.push_back(Invented);
10286 }
10287
10288 // TODO: consider using NameInfo for diagnostic.
10290 DeclarationName Name = NameInfo.getName();
10292
10295 diag::err_invalid_thread)
10297
10302
10303 bool isFriend = false;
10305 bool isMemberSpecialization = false;
10306 bool isFunctionTemplateSpecialization = false;
10307
10308 bool HasExplicitTemplateArgs = false;
10309 TemplateArgumentListInfo TemplateArgs;
10310
10311 bool isVirtualOkay = false;
10312
10313 DeclContext *OriginalDC = DC;
10314 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10315
10316 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10317 isVirtualOkay);
10318 if (!NewFD) return nullptr;
10319
10320 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10322
10323 // Set the lexical context. If this is a function-scope declaration, or has a
10324 // C++ scope specifier, or is the object of a friend declaration, the lexical
10325 // context will be different from the semantic context.
10327
10328 if (IsLocalExternDecl)
10329 NewFD->setLocalExternDecl();
10330
10331 if (getLangOpts().CPlusPlus) {
10332 // The rules for implicit inlines changed in C++20 for methods and friends
10333 // with an in-class definition (when such a definition is not attached to
10334 // the global module). This does not affect declarations that are already
10335 // inline (whether explicitly or implicitly by being declared constexpr,
10336 // consteval, etc).
10337 // FIXME: We need a better way to separate C++ standard and clang modules.
10338 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10339 !NewFD->getOwningModule() ||
10340 NewFD->isFromGlobalModule() ||
10342 bool isInline = D.getDeclSpec().isInlineSpecified();
10343 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10344 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10345 isFriend = D.getDeclSpec().isFriendSpecified();
10346 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10347 // Pre-C++20 [class.friend]p5
10348 // A function can be defined in a friend declaration of a
10349 // class . . . . Such a function is implicitly inline.
10350 // Post C++20 [class.friend]p7
10351 // Such a function is implicitly an inline function if it is attached
10352 // to the global module.
10353 NewFD->setImplicitlyInline();
10354 }
10355
10356 // If this is a method defined in an __interface, and is not a constructor
10357 // or an overloaded operator, then set the pure flag (isVirtual will already
10358 // return true).
10359 if (const CXXRecordDecl *Parent =
10360 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10361 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10362 NewFD->setIsPureVirtual(true);
10363
10364 // C++ [class.union]p2
10365 // A union can have member functions, but not virtual functions.
10366 if (isVirtual && Parent->isUnion()) {
10367 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10368 NewFD->setInvalidDecl();
10369 }
10370 if ((Parent->isClass() || Parent->isStruct()) &&
10371 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10372 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10373 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10374 if (auto *Def = Parent->getDefinition())
10375 Def->setInitMethod(true);
10376 }
10377 }
10378
10379 SetNestedNameSpecifier(*this, NewFD, D);
10380 isMemberSpecialization = false;
10381 isFunctionTemplateSpecialization = false;
10382 if (D.isInvalidType())
10383 NewFD->setInvalidDecl();
10384
10385 // Match up the template parameter lists with the scope specifier, then
10386 // determine whether we have a template or a template specialization.
10387 bool Invalid = false;
10388 TemplateIdAnnotation *TemplateId =
10390 ? D.getName().TemplateId
10391 : nullptr;
10392 TemplateParameterList *TemplateParams =
10395 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10396 isMemberSpecialization, Invalid);
10397 if (TemplateParams) {
10398 // Check that we can declare a template here.
10399 if (CheckTemplateDeclScope(S, TemplateParams))
10400 NewFD->setInvalidDecl();
10401
10402 if (TemplateParams->size() > 0) {
10403 // This is a function template
10404
10405 // A destructor cannot be a template.
10407 Diag(NewFD->getLocation(), diag::err_destructor_template);
10408 NewFD->setInvalidDecl();
10409 // Function template with explicit template arguments.
10410 } else if (TemplateId) {
10411 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10412 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10413 NewFD->setInvalidDecl();
10414 }
10415
10416 // If we're adding a template to a dependent context, we may need to
10417 // rebuilding some of the types used within the template parameter list,
10418 // now that we know what the current instantiation is.
10419 if (DC->isDependentContext()) {
10420 ContextRAII SavedContext(*this, DC);
10422 Invalid = true;
10423 }
10424
10426 NewFD->getLocation(),
10427 Name, TemplateParams,
10428 NewFD);
10429 FunctionTemplate->setLexicalDeclContext(CurContext);
10431
10432 // For source fidelity, store the other template param lists.
10433 if (TemplateParamLists.size() > 1) {
10435 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10436 .drop_back(1));
10437 }
10438 } else {
10439 // This is a function template specialization.
10440 isFunctionTemplateSpecialization = true;
10441 // For source fidelity, store all the template param lists.
10442 if (TemplateParamLists.size() > 0)
10443 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10444
10445 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10446 if (isFriend) {
10447 // We want to remove the "template<>", found here.
10448 SourceRange RemoveRange = TemplateParams->getSourceRange();
10449
10450 // If we remove the template<> and the name is not a
10451 // template-id, we're actually silently creating a problem:
10452 // the friend declaration will refer to an untemplated decl,
10453 // and clearly the user wants a template specialization. So
10454 // we need to insert '<>' after the name.
10455 SourceLocation InsertLoc;
10457 InsertLoc = D.getName().getSourceRange().getEnd();
10458 InsertLoc = getLocForEndOfToken(InsertLoc);
10459 }
10460
10461 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10462 << Name << RemoveRange
10463 << FixItHint::CreateRemoval(RemoveRange)
10464 << FixItHint::CreateInsertion(InsertLoc, "<>");
10465 Invalid = true;
10466
10467 // Recover by faking up an empty template argument list.
10468 HasExplicitTemplateArgs = true;
10469 TemplateArgs.setLAngleLoc(InsertLoc);
10470 TemplateArgs.setRAngleLoc(InsertLoc);
10471 }
10472 }
10473 } else {
10474 // Check that we can declare a template here.
10475 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10476 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10477 NewFD->setInvalidDecl();
10478
10479 // All template param lists were matched against the scope specifier:
10480 // this is NOT (an explicit specialization of) a template.
10481 if (TemplateParamLists.size() > 0)
10482 // For source fidelity, store all the template param lists.
10483 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10484
10485 // "friend void foo<>(int);" is an implicit specialization decl.
10486 if (isFriend && TemplateId)
10487 isFunctionTemplateSpecialization = true;
10488 }
10489
10490 // If this is a function template specialization and the unqualified-id of
10491 // the declarator-id is a template-id, convert the template argument list
10492 // into our AST format and check for unexpanded packs.
10493 if (isFunctionTemplateSpecialization && TemplateId) {
10494 HasExplicitTemplateArgs = true;
10495
10496 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10497 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10498 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10499 TemplateId->NumArgs);
10500 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10501
10502 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10503 // declaration of a function template partial specialization? Should we
10504 // consider the unexpanded pack context to be a partial specialization?
10505 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10507 ArgLoc, isFriend ? UPPC_FriendDeclaration
10509 NewFD->setInvalidDecl();
10510 }
10511 }
10512
10513 if (Invalid) {
10514 NewFD->setInvalidDecl();
10515 if (FunctionTemplate)
10516 FunctionTemplate->setInvalidDecl();
10517 }
10518
10519 // C++ [dcl.fct.spec]p5:
10520 // The virtual specifier shall only be used in declarations of
10521 // nonstatic class member functions that appear within a
10522 // member-specification of a class declaration; see 10.3.
10523 //
10524 if (isVirtual && !NewFD->isInvalidDecl()) {
10525 if (!isVirtualOkay) {
10527 diag::err_virtual_non_function);
10528 } else if (!CurContext->isRecord()) {
10529 // 'virtual' was specified outside of the class.
10531 diag::err_virtual_out_of_class)
10533 } else if (NewFD->getDescribedFunctionTemplate()) {
10534 // C++ [temp.mem]p3:
10535 // A member function template shall not be virtual.
10537 diag::err_virtual_member_function_template)
10539 } else {
10540 // Okay: Add virtual to the method.
10541 NewFD->setVirtualAsWritten(true);
10542 }
10543
10544 if (getLangOpts().CPlusPlus14 &&
10545 NewFD->getReturnType()->isUndeducedType())
10546 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10547 }
10548
10549 // C++ [dcl.fct.spec]p3:
10550 // The inline specifier shall not appear on a block scope function
10551 // declaration.
10552 if (isInline && !NewFD->isInvalidDecl()) {
10553 if (CurContext->isFunctionOrMethod()) {
10554 // 'inline' is not allowed on block scope function declaration.
10556 diag::err_inline_declaration_block_scope) << Name
10558 }
10559 }
10560
10561 // C++ [dcl.fct.spec]p6:
10562 // The explicit specifier shall be used only in the declaration of a
10563 // constructor or conversion function within its class definition;
10564 // see 12.3.1 and 12.3.2.
10565 if (hasExplicit && !NewFD->isInvalidDecl() &&
10567 if (!CurContext->isRecord()) {
10568 // 'explicit' was specified outside of the class.
10570 diag::err_explicit_out_of_class)
10572 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10573 !isa<CXXConversionDecl>(NewFD)) {
10574 // 'explicit' was specified on a function that wasn't a constructor
10575 // or conversion function.
10577 diag::err_explicit_non_ctor_or_conv_function)
10579 }
10580 }
10581
10583 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10584 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10585 // are implicitly inline.
10586 NewFD->setImplicitlyInline();
10587
10588 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10589 // be either constructors or to return a literal type. Therefore,
10590 // destructors cannot be declared constexpr.
10591 if (isa<CXXDestructorDecl>(NewFD) &&
10593 ConstexprKind == ConstexprSpecKind::Consteval)) {
10594 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10595 << static_cast<int>(ConstexprKind);
10599 }
10600 // C++20 [dcl.constexpr]p2: An allocation function, or a
10601 // deallocation function shall not be declared with the consteval
10602 // specifier.
10603 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10606 diag::err_invalid_consteval_decl_kind)
10607 << NewFD;
10609 }
10610 }
10611
10612 // If __module_private__ was specified, mark the function accordingly.
10614 if (isFunctionTemplateSpecialization) {
10615 SourceLocation ModulePrivateLoc
10617 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10618 << 0
10619 << FixItHint::CreateRemoval(ModulePrivateLoc);
10620 } else {
10621 NewFD->setModulePrivate();
10622 if (FunctionTemplate)
10623 FunctionTemplate->setModulePrivate();
10624 }
10625 }
10626
10627 if (isFriend) {
10628 if (FunctionTemplate) {
10629 FunctionTemplate->setObjectOfFriendDecl();
10630 FunctionTemplate->setAccess(AS_public);
10631 }
10632 NewFD->setObjectOfFriendDecl();
10633 NewFD->setAccess(AS_public);
10634 }
10635
10636 // If a function is defined as defaulted or deleted, mark it as such now.
10637 // We'll do the relevant checks on defaulted / deleted functions later.
10638 switch (D.getFunctionDefinitionKind()) {
10641 break;
10642
10644 NewFD->setDefaulted();
10645 break;
10646
10648 NewFD->setDeletedAsWritten();
10649 break;
10650 }
10651
10652 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10654 // Pre C++20 [class.mfct]p2:
10655 // A member function may be defined (8.4) in its class definition, in
10656 // which case it is an inline member function (7.1.2)
10657 // Post C++20 [class.mfct]p1:
10658 // If a member function is attached to the global module and is defined
10659 // in its class definition, it is inline.
10660 NewFD->setImplicitlyInline();
10661 }
10662
10663 if (!isFriend && SC != SC_None) {
10664 // C++ [temp.expl.spec]p2:
10665 // The declaration in an explicit-specialization shall not be an
10666 // export-declaration. An explicit specialization shall not use a
10667 // storage-class-specifier other than thread_local.
10668 //
10669 // We diagnose friend declarations with storage-class-specifiers
10670 // elsewhere.
10671 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10673 diag::ext_explicit_specialization_storage_class)
10676 }
10677
10678 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10679 assert(isa<CXXMethodDecl>(NewFD) &&
10680 "Out-of-line member function should be a CXXMethodDecl");
10681 // C++ [class.static]p1:
10682 // A data or function member of a class may be declared static
10683 // in a class definition, in which case it is a static member of
10684 // the class.
10685
10686 // Complain about the 'static' specifier if it's on an out-of-line
10687 // member function definition.
10688
10689 // MSVC permits the use of a 'static' storage specifier on an
10690 // out-of-line member function template declaration and class member
10691 // template declaration (MSVC versions before 2015), warn about this.
10693 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10694 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10695 (getLangOpts().MSVCCompat &&
10697 ? diag::ext_static_out_of_line
10698 : diag::err_static_out_of_line)
10701 }
10702 }
10703
10704 // C++11 [except.spec]p15:
10705 // A deallocation function with no exception-specification is treated
10706 // as if it were specified with noexcept(true).
10707 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10708 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10709 !FPT->hasExceptionSpec())
10710 NewFD->setType(Context.getFunctionType(
10711 FPT->getReturnType(), FPT->getParamTypes(),
10713
10714 // C++20 [dcl.inline]/7
10715 // If an inline function or variable that is attached to a named module
10716 // is declared in a definition domain, it shall be defined in that
10717 // domain.
10718 // So, if the current declaration does not have a definition, we must
10719 // check at the end of the TU (or when the PMF starts) to see that we
10720 // have a definition at that point.
10721 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10722 NewFD->isInNamedModule()) {
10723 PendingInlineFuncDecls.insert(NewFD);
10724 }
10725 }
10726
10727 // Filter out previous declarations that don't match the scope.
10730 isMemberSpecialization ||
10731 isFunctionTemplateSpecialization);
10732
10734
10735 // Handle GNU asm-label extension (encoded as an attribute).
10736 if (Expr *E = D.getAsmLabel()) {
10737 // The parser guarantees this is a string.
10739 NewFD->addAttr(
10740 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10741 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10742 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10744 if (I != ExtnameUndeclaredIdentifiers.end()) {
10745 if (isDeclExternC(NewFD)) {
10746 NewFD->addAttr(I->second);
10748 } else if (NewFD->getDeclContext()
10751 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10752 << /*Variable*/0 << NewFD;
10753 }
10754 }
10755
10756 // Copy the parameter declarations from the declarator D to the function
10757 // declaration NewFD, if they are available. First scavenge them into Params.
10759 unsigned FTIIdx;
10760 if (D.isFunctionDeclarator(FTIIdx)) {
10762
10763 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10764 // function that takes no arguments, not a function that takes a
10765 // single void argument.
10766 // We let through "const void" here because Sema::GetTypeForDeclarator
10767 // already checks for that case.
10768 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10769 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10770 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10771 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10772 Param->setDeclContext(NewFD);
10773 Params.push_back(Param);
10774
10775 if (Param->isInvalidDecl())
10776 NewFD->setInvalidDecl();
10777 }
10778 }
10779
10780 if (!getLangOpts().CPlusPlus) {
10781 // In C, find all the tag declarations from the prototype and move them
10782 // into the function DeclContext. Remove them from the surrounding tag
10783 // injection context of the function, which is typically but not always
10784 // the TU.
10785 DeclContext *PrototypeTagContext =
10787 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10788 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10789
10790 // We don't want to reparent enumerators. Look at their parent enum
10791 // instead.
10792 if (!TD) {
10793 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10794 TD = cast<EnumDecl>(ECD->getDeclContext());
10795 }
10796 if (!TD)
10797 continue;
10798 DeclContext *TagDC = TD->getLexicalDeclContext();
10799 if (!TagDC->containsDecl(TD))
10800 continue;
10801 TagDC->removeDecl(TD);
10802 TD->setDeclContext(NewFD);
10803 NewFD->addDecl(TD);
10804
10805 // Preserve the lexical DeclContext if it is not the surrounding tag
10806 // injection context of the FD. In this example, the semantic context of
10807 // E will be f and the lexical context will be S, while both the
10808 // semantic and lexical contexts of S will be f:
10809 // void f(struct S { enum E { a } f; } s);
10810 if (TagDC != PrototypeTagContext)
10811 TD->setLexicalDeclContext(TagDC);
10812 }
10813 }
10814 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10815 // When we're declaring a function with a typedef, typeof, etc as in the
10816 // following example, we'll need to synthesize (unnamed)
10817 // parameters for use in the declaration.
10818 //
10819 // @code
10820 // typedef void fn(int);
10821 // fn f;
10822 // @endcode
10823
10824 // Synthesize a parameter for each argument type.
10825 for (const auto &AI : FT->param_types()) {
10826 ParmVarDecl *Param =
10828 Param->setScopeInfo(0, Params.size());
10829 Params.push_back(Param);
10830 }
10831 } else {
10832 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10833 "Should not need args for typedef of non-prototype fn");
10834 }
10835
10836 // Finally, we know we have the right number of parameters, install them.
10837 NewFD->setParams(Params);
10838
10839 // If this declarator is a declaration and not a definition, its parameters
10840 // will not be pushed onto a scope chain. That means we will not issue any
10841 // reserved identifier warnings for the declaration, but we will for the
10842 // definition. Handle those here.
10843 if (!D.isFunctionDefinition()) {
10844 for (const ParmVarDecl *PVD : Params)
10846 }
10847
10849 NewFD->addAttr(
10850 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10851
10852 // Functions returning a variably modified type violate C99 6.7.5.2p2
10853 // because all functions have linkage.
10854 if (!NewFD->isInvalidDecl() &&
10856 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10857 NewFD->setInvalidDecl();
10858 }
10859
10860 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10862 !NewFD->hasAttr<SectionAttr>())
10863 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10864 Context, PragmaClangTextSection.SectionName,
10865 PragmaClangTextSection.PragmaLocation));
10866
10867 // Apply an implicit SectionAttr if #pragma code_seg is active.
10868 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10869 !NewFD->hasAttr<SectionAttr>()) {
10870 NewFD->addAttr(SectionAttr::CreateImplicit(
10871 Context, CodeSegStack.CurrentValue->getString(),
10872 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10873 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10876 NewFD))
10877 NewFD->dropAttr<SectionAttr>();
10878 }
10879
10880 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10881 // active.
10882 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10883 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10884 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10885 Context, PragmaClangTextSection.PragmaLocation));
10886
10887 // Apply an implicit CodeSegAttr from class declspec or
10888 // apply an implicit SectionAttr from #pragma code_seg if active.
10889 if (!NewFD->hasAttr<CodeSegAttr>()) {
10891 D.isFunctionDefinition())) {
10892 NewFD->addAttr(SAttr);
10893 }
10894 }
10895
10896 // Handle attributes.
10897 ProcessDeclAttributes(S, NewFD, D);
10899 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10900 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10901 !NewTVA->isDefaultVersion() &&
10902 !Context.getTargetInfo().hasFeature("fmv")) {
10903 // Don't add to scope fmv functions declarations if fmv disabled
10904 AddToScope = false;
10905 return NewFD;
10906 }
10907
10908 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10909 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10910 // type.
10911 //
10912 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10913 // type declaration will generate a compilation error.
10914 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10915 if (AddressSpace != LangAS::Default) {
10916 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10917 NewFD->setInvalidDecl();
10918 }
10919 }
10920
10921 if (!getLangOpts().CPlusPlus) {
10922 // Perform semantic checking on the function declaration.
10923 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10924 CheckMain(NewFD, D.getDeclSpec());
10925
10926 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10927 CheckMSVCRTEntryPoint(NewFD);
10928
10929 if (!NewFD->isInvalidDecl())
10931 isMemberSpecialization,
10933 else if (!Previous.empty())
10934 // Recover gracefully from an invalid redeclaration.
10935 D.setRedeclaration(true);
10936 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10937 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10938 "previous declaration set still overloaded");
10939
10940 // Diagnose no-prototype function declarations with calling conventions that
10941 // don't support variadic calls. Only do this in C and do it after merging
10942 // possibly prototyped redeclarations.
10943 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10945 CallingConv CC = FT->getExtInfo().getCC();
10946 if (!supportsVariadicCall(CC)) {
10947 // Windows system headers sometimes accidentally use stdcall without
10948 // (void) parameters, so we relax this to a warning.
10949 int DiagID =
10950 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10951 Diag(NewFD->getLocation(), DiagID)
10953 }
10954 }
10955
10959 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10961 } else {
10962 // C++11 [replacement.functions]p3:
10963 // The program's definitions shall not be specified as inline.
10964 //
10965 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10966 //
10967 // Suppress the diagnostic if the function is __attribute__((used)), since
10968 // that forces an external definition to be emitted.
10969 if (D.getDeclSpec().isInlineSpecified() &&
10971 !NewFD->hasAttr<UsedAttr>())
10973 diag::ext_operator_new_delete_declared_inline)
10974 << NewFD->getDeclName();
10975
10976 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10977 // C++20 [dcl.decl.general]p4:
10978 // The optional requires-clause in an init-declarator or
10979 // member-declarator shall be present only if the declarator declares a
10980 // templated function.
10981 //
10982 // C++20 [temp.pre]p8:
10983 // An entity is templated if it is
10984 // - a template,
10985 // - an entity defined or created in a templated entity,
10986 // - a member of a templated entity,
10987 // - an enumerator for an enumeration that is a templated entity, or
10988 // - the closure type of a lambda-expression appearing in the
10989 // declaration of a templated entity.
10990 //
10991 // [Note 6: A local class, a local or block variable, or a friend
10992 // function defined in a templated entity is a templated entity.
10993 // — end note]
10994 //
10995 // A templated function is a function template or a function that is
10996 // templated. A templated class is a class template or a class that is
10997 // templated. A templated variable is a variable template or a variable
10998 // that is templated.
10999 if (!FunctionTemplate) {
11000 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
11001 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
11002 // An explicit specialization shall not have a trailing
11003 // requires-clause unless it declares a function template.
11004 //
11005 // Since a friend function template specialization cannot be
11006 // definition, and since a non-template friend declaration with a
11007 // trailing requires-clause must be a definition, we diagnose
11008 // friend function template specializations with trailing
11009 // requires-clauses on the same path as explicit specializations
11010 // even though they aren't necessarily prohibited by the same
11011 // language rule.
11012 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
11013 << isFriend;
11014 } else if (isFriend && NewFD->isTemplated() &&
11015 !D.isFunctionDefinition()) {
11016 // C++ [temp.friend]p9:
11017 // A non-template friend declaration with a requires-clause shall be
11018 // a definition.
11019 Diag(NewFD->getBeginLoc(),
11020 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
11021 NewFD->setInvalidDecl();
11022 } else if (!NewFD->isTemplated() ||
11023 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
11024 Diag(TRC->getBeginLoc(),
11025 diag::err_constrained_non_templated_function);
11026 }
11027 }
11028 }
11029
11030 // We do not add HD attributes to specializations here because
11031 // they may have different constexpr-ness compared to their
11032 // templates and, after maybeAddHostDeviceAttrs() is applied,
11033 // may end up with different effective targets. Instead, a
11034 // specialization inherits its target attributes from its template
11035 // in the CheckFunctionTemplateSpecialization() call below.
11036 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
11038
11039 // Handle explicit specializations of function templates
11040 // and friend function declarations with an explicit
11041 // template argument list.
11042 if (isFunctionTemplateSpecialization) {
11043 bool isDependentSpecialization = false;
11044 if (isFriend) {
11045 // For friend function specializations, this is a dependent
11046 // specialization if its semantic context is dependent, its
11047 // qualifier is dependent, its type is dependent, or its template-id is
11048 // dependent.
11049 isDependentSpecialization =
11050 DC->isDependentContext() || NewFD->getQualifier().isDependent() ||
11051 NewFD->getType()->isDependentType() ||
11052 (HasExplicitTemplateArgs &&
11053 TemplateSpecializationType::
11054 anyInstantiationDependentTemplateArguments(
11055 TemplateArgs.arguments()));
11056 assert((!isDependentSpecialization ||
11057 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
11058 "dependent friend function specialization without template "
11059 "args");
11060 } else {
11061 // For class-scope explicit specializations of function templates,
11062 // if the lexical context is dependent, then the specialization
11063 // is dependent.
11064 isDependentSpecialization =
11065 CurContext->isRecord() && CurContext->isDependentContext();
11066 }
11067
11068 TemplateArgumentListInfo *ExplicitTemplateArgs =
11069 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
11070 if (isDependentSpecialization) {
11071 // If it's a dependent specialization, it may not be possible
11072 // to determine the primary template (for explicit specializations)
11073 // or befriended declaration (for friends) until the enclosing
11074 // template is instantiated. In such cases, we store the declarations
11075 // found by name lookup and defer resolution until instantiation.
11077 NewFD, ExplicitTemplateArgs, Previous))
11078 NewFD->setInvalidDecl();
11079 } else if (!NewFD->isInvalidDecl()) {
11080 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
11081 Previous))
11082 NewFD->setInvalidDecl();
11083 }
11084 } else if (isMemberSpecialization && !FunctionTemplate) {
11086 NewFD->setInvalidDecl();
11087 }
11088
11089 // Perform semantic checking on the function declaration.
11090 if (!NewFD->isInvalidDecl() && NewFD->isMain())
11091 CheckMain(NewFD, D.getDeclSpec());
11092
11093 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
11094 CheckMSVCRTEntryPoint(NewFD);
11095
11096 if (!NewFD->isInvalidDecl())
11098 isMemberSpecialization,
11100 else if (!Previous.empty())
11101 // Recover gracefully from an invalid redeclaration.
11102 D.setRedeclaration(true);
11103
11104 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
11105 !D.isRedeclaration() ||
11106 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
11107 "previous declaration set still overloaded");
11108
11109 NamedDecl *PrincipalDecl = (FunctionTemplate
11111 : NewFD);
11112
11113 if (isFriend && NewFD->getPreviousDecl()) {
11114 AccessSpecifier Access = AS_public;
11115 if (!NewFD->isInvalidDecl())
11116 Access = NewFD->getPreviousDecl()->getAccess();
11117
11118 NewFD->setAccess(Access);
11119 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
11120 }
11121
11122 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
11124 PrincipalDecl->setNonMemberOperator();
11125
11126 // If we have a function template, check the template parameter
11127 // list. This will check and merge default template arguments.
11128 if (FunctionTemplate) {
11129 FunctionTemplateDecl *PrevTemplate =
11130 FunctionTemplate->getPreviousDecl();
11131 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
11132 PrevTemplate ? PrevTemplate->getTemplateParameters()
11133 : nullptr,
11138 : (D.getCXXScopeSpec().isSet() &&
11139 DC && DC->isRecord() &&
11140 DC->isDependentContext())
11143 }
11144
11145 if (NewFD->isInvalidDecl()) {
11146 // Ignore all the rest of this.
11147 } else if (!D.isRedeclaration()) {
11148 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
11149 AddToScope };
11150 // Fake up an access specifier if it's supposed to be a class member.
11151 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
11152 NewFD->setAccess(AS_public);
11153
11154 // Qualified decls generally require a previous declaration.
11155 if (D.getCXXScopeSpec().isSet()) {
11156 // ...with the major exception of templated-scope or
11157 // dependent-scope friend declarations.
11158
11159 // TODO: we currently also suppress this check in dependent
11160 // contexts because (1) the parameter depth will be off when
11161 // matching friend templates and (2) we might actually be
11162 // selecting a friend based on a dependent factor. But there
11163 // are situations where these conditions don't apply and we
11164 // can actually do this check immediately.
11165 //
11166 // Unless the scope is dependent, it's always an error if qualified
11167 // redeclaration lookup found nothing at all. Diagnose that now;
11168 // nothing will diagnose that error later.
11169 if (isFriend &&
11171 (!Previous.empty() && CurContext->isDependentContext()))) {
11172 // ignore these
11173 } else if (NewFD->isCPUDispatchMultiVersion() ||
11174 NewFD->isCPUSpecificMultiVersion()) {
11175 // ignore this, we allow the redeclaration behavior here to create new
11176 // versions of the function.
11177 } else {
11178 // The user tried to provide an out-of-line definition for a
11179 // function that is a member of a class or namespace, but there
11180 // was no such member function declared (C++ [class.mfct]p2,
11181 // C++ [namespace.memdef]p2). For example:
11182 //
11183 // class X {
11184 // void f() const;
11185 // };
11186 //
11187 // void X::f() { } // ill-formed
11188 //
11189 // Complain about this problem, and attempt to suggest close
11190 // matches (e.g., those that differ only in cv-qualifiers and
11191 // whether the parameter types are references).
11192
11194 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
11195 AddToScope = ExtraArgs.AddToScope;
11196 return Result;
11197 }
11198 }
11199
11200 // Unqualified local friend declarations are required to resolve
11201 // to something.
11202 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
11204 *this, Previous, NewFD, ExtraArgs, true, S)) {
11205 AddToScope = ExtraArgs.AddToScope;
11206 return Result;
11207 }
11208 }
11209 } else if (!D.isFunctionDefinition() &&
11210 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
11211 !isFriend && !isFunctionTemplateSpecialization &&
11212 !isMemberSpecialization) {
11213 // An out-of-line member function declaration must also be a
11214 // definition (C++ [class.mfct]p2).
11215 // Note that this is not the case for explicit specializations of
11216 // function templates or member functions of class templates, per
11217 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11218 // extension for compatibility with old SWIG code which likes to
11219 // generate them.
11220 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
11221 << D.getCXXScopeSpec().getRange();
11222 }
11223 }
11224
11225 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11226 // Any top level function could potentially be specified as an entry.
11227 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11228 HLSL().ActOnTopLevelFunction(NewFD);
11229
11230 if (NewFD->hasAttr<HLSLShaderAttr>())
11231 HLSL().CheckEntryPoint(NewFD);
11232
11233 // Resources cannot be passed to functions that are not inlined.
11234 if (const NoInlineAttr *NoInline = NewFD->getAttr<NoInlineAttr>()) {
11235 for (const ParmVarDecl *PVD : NewFD->parameters()) {
11236 QualType ParamTy = PVD->getType().getNonReferenceType();
11237 QualType EltTy = Context.getBaseElementType(ParamTy);
11238 // `isCompleteType` forces completion of the element type without
11239 // reporting an error (diagnosed elsewhere) so the resource parameter
11240 // check is valid.
11241 if (!EltTy->isDependentType() &&
11242 isCompleteType(PVD->getLocation(), EltTy) &&
11243 ParamTy->isHLSLIntangibleType()) {
11244 Diag(PVD->getLocation(),
11245 diag::err_hlsl_resource_param_in_noinline_function)
11246 << ParamTy;
11247 Diag(NoInline->getLocation(), diag::note_attribute);
11248 }
11249 }
11250 }
11251 }
11252
11253 // If this is the first declaration of a library builtin function, add
11254 // attributes as appropriate.
11255 if (!D.isRedeclaration()) {
11256 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11257 if (unsigned BuiltinID = II->getBuiltinID()) {
11258 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
11259 if (!InStdNamespace &&
11261 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11262 // Validate the type matches unless this builtin is specified as
11263 // matching regardless of its declared type.
11264 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
11265 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11266 } else {
11268 LookupNecessaryTypesForBuiltin(S, BuiltinID);
11269 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
11270
11271 if (!Error && !BuiltinType.isNull() &&
11272 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11273 NewFD->getType(), BuiltinType))
11274 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11275 }
11276 }
11277 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11278 isStdBuiltin(Context, NewFD, BuiltinID)) {
11279 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11280 }
11281 }
11282 }
11283 }
11284
11285 ProcessPragmaWeak(S, NewFD);
11286 ProcessPragmaExport(NewFD);
11287 checkAttributesAfterMerging(*this, *NewFD);
11288
11290 // The above can add the format attribute for known builtin/library functions
11291 // which is required by the modular_format attribute, thus
11292 // validate modular_format now after those attributes have been added.
11293 checkModularFormatAttr(*this, *NewFD);
11294
11295 if (NewFD->hasAttr<OverloadableAttr>() &&
11296 !NewFD->getType()->getAs<FunctionProtoType>()) {
11297 Diag(NewFD->getLocation(),
11298 diag::err_attribute_overloadable_no_prototype)
11299 << NewFD;
11300 NewFD->dropAttr<OverloadableAttr>();
11301 }
11302
11303 // If there's a #pragma GCC visibility in scope, and this isn't a class
11304 // member, set the visibility of this function.
11305 if (!DC->isRecord() && NewFD->isExternallyVisible())
11307
11308 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11309 // marking the function.
11310 ObjC().AddCFAuditedAttribute(NewFD);
11311
11312 // If this is a function definition, check if we have to apply any
11313 // attributes (i.e. optnone and no_builtin) due to a pragma.
11314 if (D.isFunctionDefinition()) {
11315 AddRangeBasedOptnone(NewFD);
11317 AddSectionMSAllocText(NewFD);
11319 }
11320
11321 // If this is the first declaration of an extern C variable, update
11322 // the map of such variables.
11323 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11324 isIncompleteDeclExternC(*this, NewFD))
11326
11327 // Set this FunctionDecl's range up to the right paren.
11328 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11329
11330 if (D.isRedeclaration() && !Previous.empty()) {
11331 NamedDecl *Prev = Previous.getRepresentativeDecl();
11332 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11333 isMemberSpecialization ||
11334 isFunctionTemplateSpecialization,
11336 }
11337
11338 if (getLangOpts().CUDA) {
11339 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11340 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11342 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11343 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11345 Context.setcudaConfigureCallDecl(NewFD);
11346 }
11347 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11348 !NewFD->isInvalidDecl() &&
11350 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11351 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11353 Context.setcudaGetParameterBufferDecl(NewFD);
11354 }
11355 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11356 !NewFD->isInvalidDecl() &&
11358 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11359 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11361 Context.setcudaLaunchDeviceDecl(NewFD);
11362 }
11363 }
11364 }
11365
11367
11368 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11369 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11370 if (SC == SC_Static) {
11371 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11372 D.setInvalidType();
11373 }
11374
11375 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11376 if (!NewFD->getReturnType()->isVoidType()) {
11377 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11378 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11379 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11380 : FixItHint());
11381 D.setInvalidType();
11382 }
11383
11385 for (auto *Param : NewFD->parameters())
11386 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11387
11388 if (getLangOpts().OpenCLCPlusPlus) {
11389 if (DC->isRecord()) {
11390 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11391 D.setInvalidType();
11392 }
11393 if (FunctionTemplate) {
11394 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11395 D.setInvalidType();
11396 }
11397 }
11398 }
11399
11400 if (getLangOpts().CPlusPlus) {
11401 // Precalculate whether this is a friend function template with a constraint
11402 // that depends on an enclosing template, per [temp.friend]p9.
11403 if (isFriend && FunctionTemplate &&
11406
11407 // C++ [temp.friend]p9:
11408 // A friend function template with a constraint that depends on a
11409 // template parameter from an enclosing template shall be a definition.
11410 if (!D.isFunctionDefinition()) {
11411 Diag(NewFD->getBeginLoc(),
11412 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11413 NewFD->setInvalidDecl();
11414 }
11415 }
11416
11417 if (FunctionTemplate) {
11418 if (NewFD->isInvalidDecl())
11419 FunctionTemplate->setInvalidDecl();
11420 return FunctionTemplate;
11421 }
11422
11423 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11425 }
11426
11427 for (const ParmVarDecl *Param : NewFD->parameters()) {
11428 QualType PT = Param->getType();
11429
11430 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11431 // types.
11432 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11433 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11434 QualType ElemTy = PipeTy->getElementType();
11435 if (ElemTy->isPointerOrReferenceType()) {
11436 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11437 D.setInvalidType();
11438 }
11439 }
11440 }
11441 // WebAssembly tables can't be used as function parameters.
11442 if (Context.getTargetInfo().getTriple().isWasm()) {
11444 Diag(Param->getTypeSpecStartLoc(),
11445 diag::err_wasm_table_as_function_parameter);
11446 D.setInvalidType();
11447 }
11448 }
11449 }
11450
11451 // Diagnose availability attributes. Availability cannot be used on functions
11452 // that are run during load/unload.
11453 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11454 if (NewFD->hasAttr<ConstructorAttr>()) {
11455 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11456 << 1;
11457 NewFD->dropAttr<AvailabilityAttr>();
11458 }
11459 if (NewFD->hasAttr<DestructorAttr>()) {
11460 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11461 << 2;
11462 NewFD->dropAttr<AvailabilityAttr>();
11463 }
11464 }
11465
11466 // Diagnose no_builtin attribute on function declaration that are not a
11467 // definition.
11468 // FIXME: We should really be doing this in
11469 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11470 // the FunctionDecl and at this point of the code
11471 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11472 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11473 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11474 switch (D.getFunctionDefinitionKind()) {
11477 Diag(NBA->getLocation(),
11478 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11479 << NBA->getSpelling();
11480 break;
11482 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11483 << NBA->getSpelling();
11484 break;
11486 break;
11487 }
11488
11489 // Similar to no_builtin logic above, at this point of the code
11490 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11491 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11492 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11493 !NewFD->isInvalidDecl() &&
11495 ExternalDeclarations.push_back(NewFD);
11496
11497 // Used for a warning on the 'next' declaration when used with a
11498 // `routine(name)`.
11499 if (getLangOpts().OpenACC)
11501
11502 return NewFD;
11503}
11504
11505/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11506/// when __declspec(code_seg) "is applied to a class, all member functions of
11507/// the class and nested classes -- this includes compiler-generated special
11508/// member functions -- are put in the specified segment."
11509/// The actual behavior is a little more complicated. The Microsoft compiler
11510/// won't check outer classes if there is an active value from #pragma code_seg.
11511/// The CodeSeg is always applied from the direct parent but only from outer
11512/// classes when the #pragma code_seg stack is empty. See:
11513/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11514/// available since MS has removed the page.
11516 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11517 if (!Method)
11518 return nullptr;
11519 const CXXRecordDecl *Parent = Method->getParent();
11520 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11521 Attr *NewAttr = SAttr->clone(S.getASTContext());
11522 NewAttr->setImplicit(true);
11523 return NewAttr;
11524 }
11525
11526 // The Microsoft compiler won't check outer classes for the CodeSeg
11527 // when the #pragma code_seg stack is active.
11528 if (S.CodeSegStack.CurrentValue)
11529 return nullptr;
11530
11531 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11532 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11533 Attr *NewAttr = SAttr->clone(S.getASTContext());
11534 NewAttr->setImplicit(true);
11535 return NewAttr;
11536 }
11537 }
11538 return nullptr;
11539}
11540
11542 bool IsDefinition) {
11543 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11544 return A;
11545 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11546 CodeSegStack.CurrentValue)
11547 return SectionAttr::CreateImplicit(
11548 getASTContext(), CodeSegStack.CurrentValue->getString(),
11549 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11550 return nullptr;
11551}
11552
11554 QualType NewT, QualType OldT) {
11556 return true;
11557
11558 // For dependently-typed local extern declarations and friends, we can't
11559 // perform a correct type check in general until instantiation:
11560 //
11561 // int f();
11562 // template<typename T> void g() { T f(); }
11563 //
11564 // (valid if g() is only instantiated with T = int).
11565 if (NewT->isDependentType() &&
11566 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11567 return false;
11568
11569 // Similarly, if the previous declaration was a dependent local extern
11570 // declaration, we don't really know its type yet.
11571 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11572 return false;
11573
11574 return true;
11575}
11576
11579 return true;
11580
11581 // Don't chain dependent friend function definitions until instantiation, to
11582 // permit cases like
11583 //
11584 // void func();
11585 // template<typename T> class C1 { friend void func() {} };
11586 // template<typename T> class C2 { friend void func() {} };
11587 //
11588 // ... which is valid if only one of C1 and C2 is ever instantiated.
11589 //
11590 // FIXME: This need only apply to function definitions. For now, we proxy
11591 // this by checking for a file-scope function. We do not want this to apply
11592 // to friend declarations nominating member functions, because that gets in
11593 // the way of access checks.
11595 return false;
11596
11597 auto *VD = dyn_cast<ValueDecl>(D);
11598 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11599 return !VD || !PrevVD ||
11600 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11601 PrevVD->getType());
11602}
11603
11604/// Check the target or target_version attribute of the function for
11605/// MultiVersion validity.
11606///
11607/// Returns true if there was an error, false otherwise.
11608static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11609 const auto *TA = FD->getAttr<TargetAttr>();
11610 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11611
11612 assert((TA || TVA) && "Expecting target or target_version attribute");
11613
11615 enum ErrType { Feature = 0, Architecture = 1 };
11616
11617 if (TA) {
11618 ParsedTargetAttr ParseInfo =
11619 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11620 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11621 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11622 << Architecture << ParseInfo.CPU;
11623 return true;
11624 }
11625 for (const auto &Feat : ParseInfo.Features) {
11626 auto BareFeat = StringRef{Feat}.substr(1);
11627 if (Feat[0] == '-') {
11628 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11629 << Feature << ("no-" + BareFeat);
11630 return true;
11631 }
11632
11633 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11634 !TargetInfo.isValidFeatureName(BareFeat) ||
11635 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11636 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11637 << Feature << BareFeat;
11638 return true;
11639 }
11640 }
11641 }
11642
11643 if (TVA) {
11645 ParsedTargetAttr ParseInfo;
11646 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11647 ParseInfo =
11648 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11649 for (auto &Feat : ParseInfo.Features)
11650 Feats.push_back(StringRef{Feat}.substr(1));
11651 } else {
11652 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11653 TVA->getFeatures(Feats);
11654 }
11655 for (const auto &Feat : Feats) {
11656 if (!TargetInfo.validateCpuSupports(Feat)) {
11657 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11658 << Feature << Feat;
11659 return true;
11660 }
11661 }
11662 }
11663 return false;
11664}
11665
11666// Provide a white-list of attributes that are allowed to be combined with
11667// multiversion functions.
11669 MultiVersionKind MVKind) {
11670 // Note: this list/diagnosis must match the list in
11671 // checkMultiversionAttributesAllSame.
11672 switch (Kind) {
11673 default:
11674 return false;
11675 case attr::ArmLocallyStreaming:
11676 return MVKind == MultiVersionKind::TargetVersion ||
11678 case attr::Used:
11679 return MVKind == MultiVersionKind::Target;
11680 case attr::NonNull:
11681 case attr::NoThrow:
11682 return true;
11683 }
11684}
11685
11687 const FunctionDecl *FD,
11688 const FunctionDecl *CausedFD,
11689 MultiVersionKind MVKind) {
11690 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11691 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11692 << static_cast<unsigned>(MVKind) << A;
11693 if (CausedFD)
11694 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11695 return true;
11696 };
11697
11698 for (const Attr *A : FD->attrs()) {
11699 switch (A->getKind()) {
11700 case attr::CPUDispatch:
11701 case attr::CPUSpecific:
11702 if (MVKind != MultiVersionKind::CPUDispatch &&
11704 return Diagnose(S, A);
11705 break;
11706 case attr::Target:
11707 if (MVKind != MultiVersionKind::Target)
11708 return Diagnose(S, A);
11709 break;
11710 case attr::TargetVersion:
11711 if (MVKind != MultiVersionKind::TargetVersion &&
11713 return Diagnose(S, A);
11714 break;
11715 case attr::TargetClones:
11716 if (MVKind != MultiVersionKind::TargetClones &&
11718 return Diagnose(S, A);
11719 break;
11720 default:
11721 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11722 return Diagnose(S, A);
11723 break;
11724 }
11725 }
11726 return false;
11727}
11728
11730 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11731 const PartialDiagnostic &NoProtoDiagID,
11732 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11733 const PartialDiagnosticAt &NoSupportDiagIDAt,
11734 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11735 bool ConstexprSupported, bool CLinkageMayDiffer) {
11736 enum DoesntSupport {
11737 FuncTemplates = 0,
11738 VirtFuncs = 1,
11739 DeducedReturn = 2,
11740 Constructors = 3,
11741 Destructors = 4,
11742 DeletedFuncs = 5,
11743 DefaultedFuncs = 6,
11744 ConstexprFuncs = 7,
11745 ConstevalFuncs = 8,
11746 Lambda = 9,
11747 };
11748 enum Different {
11749 CallingConv = 0,
11750 ReturnType = 1,
11751 ConstexprSpec = 2,
11752 InlineSpec = 3,
11753 Linkage = 4,
11754 LanguageLinkage = 5,
11755 };
11756
11757 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11758 !OldFD->getType()->getAs<FunctionProtoType>()) {
11759 Diag(OldFD->getLocation(), NoProtoDiagID);
11760 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11761 return true;
11762 }
11763
11764 if (NoProtoDiagID.getDiagID() != 0 &&
11765 !NewFD->getType()->getAs<FunctionProtoType>())
11766 return Diag(NewFD->getLocation(), NoProtoDiagID);
11767
11768 if (!TemplatesSupported &&
11770 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11771 << FuncTemplates;
11772
11773 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11774 if (NewCXXFD->isVirtual())
11775 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11776 << VirtFuncs;
11777
11778 if (isa<CXXConstructorDecl>(NewCXXFD))
11779 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11780 << Constructors;
11781
11782 if (isa<CXXDestructorDecl>(NewCXXFD))
11783 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11784 << Destructors;
11785 }
11786
11787 if (NewFD->isDeleted())
11788 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11789 << DeletedFuncs;
11790
11791 if (NewFD->isDefaulted())
11792 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11793 << DefaultedFuncs;
11794
11795 if (!ConstexprSupported && NewFD->isConstexpr())
11796 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11797 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11798
11799 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11800 const auto *NewType = cast<FunctionType>(NewQType);
11801 QualType NewReturnType = NewType->getReturnType();
11802
11803 if (NewReturnType->isUndeducedType())
11804 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11805 << DeducedReturn;
11806
11807 // Ensure the return type is identical.
11808 if (OldFD) {
11809 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11810 const auto *OldType = cast<FunctionType>(OldQType);
11811 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11812 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11813
11814 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11815 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11816
11817 bool ArmStreamingCCMismatched = false;
11818 if (OldFPT && NewFPT) {
11819 unsigned Diff =
11820 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11821 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11822 // cannot be mixed.
11825 ArmStreamingCCMismatched = true;
11826 }
11827
11828 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11829 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11830
11831 QualType OldReturnType = OldType->getReturnType();
11832
11833 if (OldReturnType != NewReturnType)
11834 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11835
11836 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11837 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11838
11839 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11840 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11841
11842 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11843 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11844
11845 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11846 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11847
11848 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11849 NewFD->getLocation()))
11850 return true;
11851 }
11852 return false;
11853}
11854
11856 const FunctionDecl *NewFD,
11857 bool CausesMV,
11858 MultiVersionKind MVKind) {
11860 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11861 if (OldFD)
11862 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11863 return true;
11864 }
11865
11866 bool IsCPUSpecificCPUDispatchMVKind =
11869
11870 if (CausesMV && OldFD &&
11871 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11872 return true;
11873
11874 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11875 return true;
11876
11877 // Only allow transition to MultiVersion if it hasn't been used.
11878 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11879 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11880 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11881 return true;
11882 }
11883
11885 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11887 S.PDiag(diag::note_multiversioning_caused_here)),
11889 S.PDiag(diag::err_multiversion_doesnt_support)
11890 << static_cast<unsigned>(MVKind)),
11892 S.PDiag(diag::err_multiversion_diff)),
11893 /*TemplatesSupported=*/false,
11894 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11895 /*CLinkageMayDiffer=*/false);
11896}
11897
11898/// Check the validity of a multiversion function declaration that is the
11899/// first of its kind. Also sets the multiversion'ness' of the function itself.
11900///
11901/// This sets NewFD->isInvalidDecl() to true if there was an error.
11902///
11903/// Returns true if there was an error, false otherwise.
11906 assert(MVKind != MultiVersionKind::None &&
11907 "Function lacks multiversion attribute");
11908 const auto *TA = FD->getAttr<TargetAttr>();
11909 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11910 // The target attribute only causes MV if this declaration is the default,
11911 // otherwise it is treated as a normal function.
11912 if (TA && !TA->isDefaultVersion())
11913 return false;
11914
11915 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11916 FD->setInvalidDecl();
11917 return true;
11918 }
11919
11920 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11921 FD->setInvalidDecl();
11922 return true;
11923 }
11924
11925 FD->setIsMultiVersion();
11926 return false;
11927}
11928
11930 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11932 return true;
11933 }
11934
11935 return false;
11936}
11937
11939 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11940 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11941 return;
11942
11943 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11944 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11945
11946 if (MVKindTo == MultiVersionKind::None &&
11947 (MVKindFrom == MultiVersionKind::TargetVersion ||
11948 MVKindFrom == MultiVersionKind::TargetClones))
11949 To->addAttr(TargetVersionAttr::CreateImplicit(
11950 To->getASTContext(), "default", To->getSourceRange()));
11951}
11952
11954 FunctionDecl *NewFD,
11955 bool &Redeclaration,
11956 NamedDecl *&OldDecl,
11958 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11959
11960 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11961 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11962 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11963 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11964
11965 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11966
11967 // The definitions should be allowed in any order. If we have discovered
11968 // a new target version and the preceeding was the default, then add the
11969 // corresponding attribute to it.
11970 patchDefaultTargetVersion(NewFD, OldFD);
11971
11972 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11973 // to change, this is a simple redeclaration.
11974 if (NewTA && !NewTA->isDefaultVersion() &&
11975 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11976 return false;
11977
11978 // Otherwise, this decl causes MultiVersioning.
11979 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11982 NewFD->setInvalidDecl();
11983 return true;
11984 }
11985
11986 if (CheckMultiVersionValue(S, NewFD)) {
11987 NewFD->setInvalidDecl();
11988 return true;
11989 }
11990
11991 // If this is 'default', permit the forward declaration.
11992 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11993 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11994 Redeclaration = true;
11995 OldDecl = OldFD;
11996 OldFD->setIsMultiVersion();
11997 NewFD->setIsMultiVersion();
11998 return false;
11999 }
12000
12001 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
12002 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
12003 NewFD->setInvalidDecl();
12004 return true;
12005 }
12006
12007 if (NewTA) {
12008 ParsedTargetAttr OldParsed =
12010 OldTA->getFeaturesStr());
12011 llvm::sort(OldParsed.Features);
12012 ParsedTargetAttr NewParsed =
12014 NewTA->getFeaturesStr());
12015 // Sort order doesn't matter, it just needs to be consistent.
12016 llvm::sort(NewParsed.Features);
12017 if (OldParsed == NewParsed) {
12018 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12019 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
12020 NewFD->setInvalidDecl();
12021 return true;
12022 }
12023 }
12024
12025 for (const auto *FD : OldFD->redecls()) {
12026 const auto *CurTA = FD->getAttr<TargetAttr>();
12027 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
12028 // We allow forward declarations before ANY multiversioning attributes, but
12029 // nothing after the fact.
12031 ((NewTA && (!CurTA || CurTA->isInherited())) ||
12032 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
12033 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
12034 << (NewTA ? 0 : 2);
12035 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
12036 NewFD->setInvalidDecl();
12037 return true;
12038 }
12039 }
12040
12041 OldFD->setIsMultiVersion();
12042 NewFD->setIsMultiVersion();
12043 Redeclaration = false;
12044 OldDecl = nullptr;
12045 Previous.clear();
12046 return false;
12047}
12048
12050 MultiVersionKind OldKind = Old->getMultiVersionKind();
12051 MultiVersionKind NewKind = New->getMultiVersionKind();
12052
12053 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
12054 NewKind == MultiVersionKind::None)
12055 return true;
12056
12057 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
12058 switch (OldKind) {
12060 return NewKind == MultiVersionKind::TargetClones;
12062 return NewKind == MultiVersionKind::TargetVersion;
12063 default:
12064 return false;
12065 }
12066 } else {
12067 switch (OldKind) {
12069 return NewKind == MultiVersionKind::CPUSpecific;
12071 return NewKind == MultiVersionKind::CPUDispatch;
12072 default:
12073 return false;
12074 }
12075 }
12076}
12077
12078/// Check the validity of a new function declaration being added to an existing
12079/// multiversioned declaration collection.
12081 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
12082 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
12083 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
12085
12086 // Disallow mixing of multiversioning types.
12087 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
12088 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
12089 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
12090 NewFD->setInvalidDecl();
12091 return true;
12092 }
12093
12094 // Add the default target_version attribute if it's missing.
12095 patchDefaultTargetVersion(OldFD, NewFD);
12096 patchDefaultTargetVersion(NewFD, OldFD);
12097
12098 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12099 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12100 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
12101 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
12102
12103 ParsedTargetAttr NewParsed;
12104 if (NewTA) {
12106 NewTA->getFeaturesStr());
12107 llvm::sort(NewParsed.Features);
12108 }
12110 if (NewTVA) {
12111 NewTVA->getFeatures(NewFeats);
12112 llvm::sort(NewFeats);
12113 }
12114
12115 bool UseMemberUsingDeclRules =
12116 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
12117
12118 bool MayNeedOverloadableChecks =
12120
12121 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
12122 // of a previous member of the MultiVersion set.
12123 for (NamedDecl *ND : Previous) {
12124 FunctionDecl *CurFD = ND->getAsFunction();
12125 if (!CurFD || CurFD->isInvalidDecl())
12126 continue;
12127 if (MayNeedOverloadableChecks &&
12128 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
12129 continue;
12130
12131 switch (NewMVKind) {
12133 assert(OldMVKind == MultiVersionKind::TargetClones &&
12134 "Only target_clones can be omitted in subsequent declarations");
12135 break;
12137 const auto *CurTA = CurFD->getAttr<TargetAttr>();
12138 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
12139 NewFD->setIsMultiVersion();
12140 Redeclaration = true;
12141 OldDecl = ND;
12142 return false;
12143 }
12144
12145 ParsedTargetAttr CurParsed =
12147 CurTA->getFeaturesStr());
12148 llvm::sort(CurParsed.Features);
12149 if (CurParsed == NewParsed) {
12150 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12151 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12152 NewFD->setInvalidDecl();
12153 return true;
12154 }
12155 break;
12156 }
12158 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12159 if (CurTVA->getName() == NewTVA->getName()) {
12160 NewFD->setIsMultiVersion();
12161 Redeclaration = true;
12162 OldDecl = ND;
12163 return false;
12164 }
12166 CurTVA->getFeatures(CurFeats);
12167 llvm::sort(CurFeats);
12168
12169 if (CurFeats == NewFeats) {
12170 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12171 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12172 NewFD->setInvalidDecl();
12173 return true;
12174 }
12175 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12176 // Default
12177 if (NewFeats.empty())
12178 break;
12179
12180 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
12182 CurClones->getFeatures(CurFeats, I);
12183 llvm::sort(CurFeats);
12184
12185 if (CurFeats == NewFeats) {
12186 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12187 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12188 NewFD->setInvalidDecl();
12189 return true;
12190 }
12191 }
12192 }
12193 break;
12194 }
12196 assert(NewClones && "MultiVersionKind does not match attribute type");
12197 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12198 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
12199 !std::equal(CurClones->featuresStrs_begin(),
12200 CurClones->featuresStrs_end(),
12201 NewClones->featuresStrs_begin())) {
12202 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
12203 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12204 NewFD->setInvalidDecl();
12205 return true;
12206 }
12207 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12209 CurTVA->getFeatures(CurFeats);
12210 llvm::sort(CurFeats);
12211
12212 // Default
12213 if (CurFeats.empty())
12214 break;
12215
12216 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12217 NewFeats.clear();
12218 NewClones->getFeatures(NewFeats, I);
12219 llvm::sort(NewFeats);
12220
12221 if (CurFeats == NewFeats) {
12222 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12223 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12224 NewFD->setInvalidDecl();
12225 return true;
12226 }
12227 }
12228 break;
12229 }
12230 Redeclaration = true;
12231 OldDecl = CurFD;
12232 NewFD->setIsMultiVersion();
12233 return false;
12234 }
12237 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12238 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12239 // Handle CPUDispatch/CPUSpecific versions.
12240 // Only 1 CPUDispatch function is allowed, this will make it go through
12241 // the redeclaration errors.
12242 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12243 CurFD->hasAttr<CPUDispatchAttr>()) {
12244 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12245 std::equal(
12246 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
12247 NewCPUDisp->cpus_begin(),
12248 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12249 return Cur->getName() == New->getName();
12250 })) {
12251 NewFD->setIsMultiVersion();
12252 Redeclaration = true;
12253 OldDecl = ND;
12254 return false;
12255 }
12256
12257 // If the declarations don't match, this is an error condition.
12258 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
12259 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12260 NewFD->setInvalidDecl();
12261 return true;
12262 }
12263 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12264 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12265 std::equal(
12266 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
12267 NewCPUSpec->cpus_begin(),
12268 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12269 return Cur->getName() == New->getName();
12270 })) {
12271 NewFD->setIsMultiVersion();
12272 Redeclaration = true;
12273 OldDecl = ND;
12274 return false;
12275 }
12276
12277 // Only 1 version of CPUSpecific is allowed for each CPU.
12278 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12279 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12280 if (CurII == NewII) {
12281 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12282 << NewII;
12283 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12284 NewFD->setInvalidDecl();
12285 return true;
12286 }
12287 }
12288 }
12289 }
12290 break;
12291 }
12292 }
12293 }
12294
12295 // Redeclarations of a target_clones function may omit the attribute, in which
12296 // case it will be inherited during declaration merging.
12297 if (NewMVKind == MultiVersionKind::None &&
12298 OldMVKind == MultiVersionKind::TargetClones) {
12299 NewFD->setIsMultiVersion();
12300 Redeclaration = true;
12301 OldDecl = OldFD;
12302 return false;
12303 }
12304
12305 // Else, this is simply a non-redecl case. Checking the 'value' is only
12306 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12307 // handled in the attribute adding step.
12308 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12309 NewFD->setInvalidDecl();
12310 return true;
12311 }
12312
12313 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12314 !OldFD->isMultiVersion(), NewMVKind)) {
12315 NewFD->setInvalidDecl();
12316 return true;
12317 }
12318
12319 // Permit forward declarations in the case where these two are compatible.
12320 if (!OldFD->isMultiVersion()) {
12321 OldFD->setIsMultiVersion();
12322 NewFD->setIsMultiVersion();
12323 Redeclaration = true;
12324 OldDecl = OldFD;
12325 return false;
12326 }
12327
12328 NewFD->setIsMultiVersion();
12329 Redeclaration = false;
12330 OldDecl = nullptr;
12331 Previous.clear();
12332 return false;
12333}
12334
12335/// Check the validity of a mulitversion function declaration.
12336/// Also sets the multiversion'ness' of the function itself.
12337///
12338/// This sets NewFD->isInvalidDecl() to true if there was an error.
12339///
12340/// Returns true if there was an error, false otherwise.
12342 bool &Redeclaration, NamedDecl *&OldDecl,
12344 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12345
12346 // Check if FMV is disabled.
12347 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12348 return false;
12349
12350 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12351 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12352 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12353 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12354 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12355 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12356
12357 // Main isn't allowed to become a multiversion function, however it IS
12358 // permitted to have 'main' be marked with the 'target' optimization hint,
12359 // for 'target_version' only default is allowed.
12360 if (NewFD->isMain()) {
12361 if (MVKind != MultiVersionKind::None &&
12362 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12363 !(MVKind == MultiVersionKind::TargetVersion &&
12364 NewTVA->isDefaultVersion())) {
12365 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12366 NewFD->setInvalidDecl();
12367 return true;
12368 }
12369 return false;
12370 }
12371
12372 // Target attribute on AArch64 is not used for multiversioning
12373 if (NewTA && TI.getTriple().isAArch64())
12374 return false;
12375
12376 // Target attribute on RISCV is not used for multiversioning
12377 if (NewTA && TI.getTriple().isRISCV())
12378 return false;
12379
12380 if (!OldDecl || !OldDecl->getAsFunction() ||
12381 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12382 NewFD->getDeclContext()->getRedeclContext())) {
12383 // If there's no previous declaration, AND this isn't attempting to cause
12384 // multiversioning, this isn't an error condition.
12385 if (MVKind == MultiVersionKind::None)
12386 return false;
12387 return CheckMultiVersionFirstFunction(S, NewFD);
12388 }
12389
12390 FunctionDecl *OldFD = OldDecl->getAsFunction();
12391
12392 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12393 return false;
12394
12395 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12396 // for target_clones and target_version.
12397 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12400 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12402 NewFD->setInvalidDecl();
12403 return true;
12404 }
12405
12406 if (!OldFD->isMultiVersion()) {
12407 switch (MVKind) {
12411 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12413 if (OldFD->isUsed(false)) {
12414 NewFD->setInvalidDecl();
12415 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12416 }
12417 OldFD->setIsMultiVersion();
12418 break;
12419
12423 break;
12424 }
12425 }
12426
12427 // At this point, we have a multiversion function decl (in OldFD) AND an
12428 // appropriate attribute in the current function decl (unless it's allowed to
12429 // omit the attribute). Resolve that these are still compatible with previous
12430 // declarations.
12431 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12432 NewCPUSpec, NewClones, Redeclaration,
12433 OldDecl, Previous);
12434}
12435
12437 bool IsPure = NewFD->hasAttr<PureAttr>();
12438 bool IsConst = NewFD->hasAttr<ConstAttr>();
12439
12440 // If there are no pure or const attributes, there's nothing to check.
12441 if (!IsPure && !IsConst)
12442 return;
12443
12444 // If the function is marked both pure and const, we retain the const
12445 // attribute because it makes stronger guarantees than the pure attribute, and
12446 // we drop the pure attribute explicitly to prevent later confusion about
12447 // semantics.
12448 if (IsPure && IsConst) {
12449 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12450 NewFD->dropAttrs<PureAttr>();
12451 }
12452
12453 // Constructors and destructors are functions which return void, so are
12454 // handled here as well.
12455 if (NewFD->getReturnType()->isVoidType()) {
12456 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12457 << IsConst;
12458 NewFD->dropAttrs<PureAttr, ConstAttr>();
12459 }
12460}
12461
12464 bool IsMemberSpecialization,
12465 bool DeclIsDefn) {
12466 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12467 "Variably modified return types are not handled here");
12468
12469 // Determine whether the type of this function should be merged with
12470 // a previous visible declaration. This never happens for functions in C++,
12471 // and always happens in C if the previous declaration was visible.
12472 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12473 !Previous.isShadowed();
12474
12475 bool Redeclaration = false;
12476 NamedDecl *OldDecl = nullptr;
12477 bool MayNeedOverloadableChecks = false;
12478
12480 // Merge or overload the declaration with an existing declaration of
12481 // the same name, if appropriate.
12482 if (!Previous.empty()) {
12483 // Determine whether NewFD is an overload of PrevDecl or
12484 // a declaration that requires merging. If it's an overload,
12485 // there's no more work to do here; we'll just add the new
12486 // function to the scope.
12488 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12489 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12490 Redeclaration = true;
12491 OldDecl = Candidate;
12492 }
12493 } else {
12494 MayNeedOverloadableChecks = true;
12495 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12496 /*NewIsUsingDecl*/ false)) {
12498 Redeclaration = true;
12499 break;
12500
12502 Redeclaration = true;
12503 break;
12504
12506 Redeclaration = false;
12507 break;
12508 }
12509 }
12510 }
12511
12512 // Check for a previous extern "C" declaration with this name.
12513 if (!Redeclaration &&
12515 if (!Previous.empty()) {
12516 // This is an extern "C" declaration with the same name as a previous
12517 // declaration, and thus redeclares that entity...
12518 Redeclaration = true;
12519 OldDecl = Previous.getFoundDecl();
12520 MergeTypeWithPrevious = false;
12521
12522 // ... except in the presence of __attribute__((overloadable)).
12523 if (OldDecl->hasAttr<OverloadableAttr>() ||
12524 NewFD->hasAttr<OverloadableAttr>()) {
12525 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12526 MayNeedOverloadableChecks = true;
12527 Redeclaration = false;
12528 OldDecl = nullptr;
12529 }
12530 }
12531 }
12532 }
12533
12534 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12535 return Redeclaration;
12536
12537 // PPC MMA non-pointer types are not allowed as function return types.
12538 if (Context.getTargetInfo().getTriple().isPPC64() &&
12539 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12540 NewFD->setInvalidDecl();
12541 }
12542
12543 CheckConstPureAttributesUsage(*this, NewFD);
12544
12545 // C++ [dcl.spec.auto.general]p12:
12546 // Return type deduction for a templated function with a placeholder in its
12547 // declared type occurs when the definition is instantiated even if the
12548 // function body contains a return statement with a non-type-dependent
12549 // operand.
12550 //
12551 // C++ [temp.dep.expr]p3:
12552 // An id-expression is type-dependent if it is a template-id that is not a
12553 // concept-id and is dependent; or if its terminal name is:
12554 // - [...]
12555 // - associated by name lookup with one or more declarations of member
12556 // functions of a class that is the current instantiation declared with a
12557 // return type that contains a placeholder type,
12558 // - [...]
12559 //
12560 // If this is a templated function with a placeholder in its return type,
12561 // make the placeholder type dependent since it won't be deduced until the
12562 // definition is instantiated. We do this here because it needs to happen
12563 // for implicitly instantiated member functions/member function templates.
12564 if (getLangOpts().CPlusPlus14 &&
12565 (NewFD->isDependentContext() &&
12566 NewFD->getReturnType()->isUndeducedType())) {
12567 const FunctionProtoType *FPT =
12568 NewFD->getType()->castAs<FunctionProtoType>();
12569 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12570 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12571 FPT->getExtProtoInfo()));
12572 }
12573
12574 // C++11 [dcl.constexpr]p8:
12575 // A constexpr specifier for a non-static member function that is not
12576 // a constructor declares that member function to be const.
12577 //
12578 // This needs to be delayed until we know whether this is an out-of-line
12579 // definition of a static member function.
12580 //
12581 // This rule is not present in C++1y, so we produce a backwards
12582 // compatibility warning whenever it happens in C++11.
12583 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12584 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12585 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12587 CXXMethodDecl *OldMD = nullptr;
12588 if (OldDecl)
12589 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12590 if (!OldMD || !OldMD->isStatic()) {
12591 const FunctionProtoType *FPT =
12594 EPI.TypeQuals.addConst();
12595 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12596 FPT->getParamTypes(), EPI));
12597
12598 // Warn that we did this, if we're not performing template instantiation.
12599 // In that case, we'll have warned already when the template was defined.
12600 if (!inTemplateInstantiation()) {
12601 SourceLocation AddConstLoc;
12604 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12605
12606 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12607 << FixItHint::CreateInsertion(AddConstLoc, " const");
12608 }
12609 }
12610 }
12611
12612 if (Redeclaration) {
12613 // NewFD and OldDecl represent declarations that need to be
12614 // merged.
12615 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12616 DeclIsDefn)) {
12617 NewFD->setInvalidDecl();
12618 return Redeclaration;
12619 }
12620
12621 Previous.clear();
12622 Previous.addDecl(OldDecl);
12623
12624 if (FunctionTemplateDecl *OldTemplateDecl =
12625 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12626 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12627 FunctionTemplateDecl *NewTemplateDecl
12629 assert(NewTemplateDecl && "Template/non-template mismatch");
12630
12631 // The call to MergeFunctionDecl above may have created some state in
12632 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12633 // can add it as a redeclaration.
12634 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12635
12636 NewFD->setPreviousDeclaration(OldFD);
12637 if (NewFD->isCXXClassMember()) {
12638 NewFD->setAccess(OldTemplateDecl->getAccess());
12639 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12640 }
12641
12642 // If this is an explicit specialization of a member that is a function
12643 // template, mark it as a member specialization.
12644 if (IsMemberSpecialization &&
12645 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12646 NewTemplateDecl->setMemberSpecialization();
12647 assert(OldTemplateDecl->isMemberSpecialization());
12648 // Explicit specializations of a member template do not inherit deleted
12649 // status from the parent member template that they are specializing.
12650 if (OldFD->isDeleted()) {
12651 // FIXME: This assert will not hold in the presence of modules.
12652 assert(OldFD->getCanonicalDecl() == OldFD);
12653 // FIXME: We need an update record for this AST mutation.
12654 OldFD->setDeletedAsWritten(false);
12655 }
12656 }
12657
12658 } else {
12659 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12660 auto *OldFD = cast<FunctionDecl>(OldDecl);
12661 // This needs to happen first so that 'inline' propagates.
12662 NewFD->setPreviousDeclaration(OldFD);
12663 if (NewFD->isCXXClassMember())
12664 NewFD->setAccess(OldFD->getAccess());
12665 }
12666 }
12667 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12668 !NewFD->getAttr<OverloadableAttr>()) {
12669 assert((Previous.empty() ||
12670 llvm::any_of(Previous,
12671 [](const NamedDecl *ND) {
12672 return ND->hasAttr<OverloadableAttr>();
12673 })) &&
12674 "Non-redecls shouldn't happen without overloadable present");
12675
12676 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12677 const auto *FD = dyn_cast<FunctionDecl>(ND);
12678 return FD && !FD->hasAttr<OverloadableAttr>();
12679 });
12680
12681 if (OtherUnmarkedIter != Previous.end()) {
12682 Diag(NewFD->getLocation(),
12683 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12684 Diag((*OtherUnmarkedIter)->getLocation(),
12685 diag::note_attribute_overloadable_prev_overload)
12686 << false;
12687
12688 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12689 }
12690 }
12691
12692 if (LangOpts.OpenMP)
12694
12695 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12697
12698 if (NewFD->hasAttr<SYCLExternalAttr>())
12700
12701 // Semantic checking for this function declaration (in isolation).
12702
12703 if (getLangOpts().CPlusPlus) {
12704 // C++-specific checks.
12705 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12707 } else if (CXXDestructorDecl *Destructor =
12708 dyn_cast<CXXDestructorDecl>(NewFD)) {
12709 // We check here for invalid destructor names.
12710 // If we have a friend destructor declaration that is dependent, we can't
12711 // diagnose right away because cases like this are still valid:
12712 // template <class T> struct A { friend T::X::~Y(); };
12713 // struct B { struct Y { ~Y(); }; using X = Y; };
12714 // template struct A<B>;
12716 (!Destructor->getFunctionObjectParameterType()->isDependentType() &&
12717 !Destructor->getDeclName().isDependentName())) {
12718 CanQualType ClassType =
12719 Context.getCanonicalTagType(Destructor->getParent());
12720
12721 DeclarationName Name =
12722 Context.DeclarationNames.getCXXDestructorName(ClassType);
12723 if (NewFD->getDeclName() != Name) {
12724 Diag(NewFD->getLocation(), diag::err_destructor_name);
12725 NewFD->setInvalidDecl();
12726 return Redeclaration;
12727 }
12728 }
12729 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12730 if (auto *TD = Guide->getDescribedFunctionTemplate())
12732
12733 // A deduction guide is not on the list of entities that can be
12734 // explicitly specialized.
12735 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12736 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12737 << /*explicit specialization*/ 1;
12738 }
12739
12740 // Find any virtual functions that this function overrides.
12741 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12742 if (!Method->isFunctionTemplateSpecialization() &&
12743 !Method->getDescribedFunctionTemplate() &&
12744 Method->isCanonicalDecl()) {
12745 AddOverriddenMethods(Method->getParent(), Method);
12746 }
12747 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12748 // C++2a [class.virtual]p6
12749 // A virtual method shall not have a requires-clause.
12751 diag::err_constrained_virtual_method);
12752
12753 if (Method->isStatic())
12755 }
12756
12757 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12758 ActOnConversionDeclarator(Conversion);
12759
12760 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12761 if (NewFD->isOverloadedOperator() &&
12763 NewFD->setInvalidDecl();
12764 return Redeclaration;
12765 }
12766
12767 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12768 if (NewFD->getLiteralIdentifier() &&
12770 NewFD->setInvalidDecl();
12771 return Redeclaration;
12772 }
12773
12774 // In C++, check default arguments now that we have merged decls. Unless
12775 // the lexical context is the class, because in this case this is done
12776 // during delayed parsing anyway.
12777 if (!CurContext->isRecord())
12779
12780 // If this function is declared as being extern "C", then check to see if
12781 // the function returns a UDT (class, struct, or union type) that is not C
12782 // compatible, and if it does, warn the user.
12783 // But, issue any diagnostic on the first declaration only.
12784 if (Previous.empty() && NewFD->isExternC()) {
12785 QualType R = NewFD->getReturnType();
12786 if (R->isIncompleteType() && !R->isVoidType())
12787 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12788 << NewFD << R;
12789 else if (!R.isPODType(Context) && !R->isVoidType() &&
12790 !R->isObjCObjectPointerType())
12791 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12792 }
12793
12794 // C++1z [dcl.fct]p6:
12795 // [...] whether the function has a non-throwing exception-specification
12796 // [is] part of the function type
12797 //
12798 // This results in an ABI break between C++14 and C++17 for functions whose
12799 // declared type includes an exception-specification in a parameter or
12800 // return type. (Exception specifications on the function itself are OK in
12801 // most cases, and exception specifications are not permitted in most other
12802 // contexts where they could make it into a mangling.)
12803 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12804 auto HasNoexcept = [&](QualType T) -> bool {
12805 // Strip off declarator chunks that could be between us and a function
12806 // type. We don't need to look far, exception specifications are very
12807 // restricted prior to C++17.
12808 if (auto *RT = T->getAs<ReferenceType>())
12809 T = RT->getPointeeType();
12810 else if (T->isAnyPointerType())
12811 T = T->getPointeeType();
12812 else if (auto *MPT = T->getAs<MemberPointerType>())
12813 T = MPT->getPointeeType();
12814 if (auto *FPT = T->getAs<FunctionProtoType>())
12815 if (FPT->isNothrow())
12816 return true;
12817 return false;
12818 };
12819
12820 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12821 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12822 for (QualType T : FPT->param_types())
12823 AnyNoexcept |= HasNoexcept(T);
12824 if (AnyNoexcept)
12825 Diag(NewFD->getLocation(),
12826 diag::warn_cxx17_compat_exception_spec_in_signature)
12827 << NewFD;
12828 }
12829
12830 if (!Redeclaration && LangOpts.CUDA) {
12831 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12832 for (auto *Parm : NewFD->parameters()) {
12833 if (!Parm->getType()->isDependentType() &&
12834 Parm->hasAttr<CUDAGridConstantAttr>() &&
12835 !(IsKernel && Parm->getType().isConstQualified()))
12836 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12837 diag::err_cuda_grid_constant_not_allowed);
12838 }
12840 }
12841 }
12842
12843 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12845
12846 return Redeclaration;
12847}
12848
12850 // [basic.start.main]p3
12851 // The main function shall not be declared with C linkage-specification.
12852 if (FD->isExternCContext())
12853 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12854
12855 // C++11 [basic.start.main]p3:
12856 // A program that [...] declares main to be inline, static or
12857 // constexpr is ill-formed.
12858 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12859 // appear in a declaration of main.
12860 // static main is not an error under C99, but we should warn about it.
12861 // We accept _Noreturn main as an extension.
12862 if (FD->getStorageClass() == SC_Static)
12864 ? diag::err_static_main : diag::warn_static_main)
12866 if (FD->isInlineSpecified())
12867 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12869 if (DS.isNoreturnSpecified()) {
12870 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12871 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12872 Diag(NoreturnLoc, diag::ext_noreturn_main);
12873 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12874 << FixItHint::CreateRemoval(NoreturnRange);
12875 }
12876 if (FD->isConstexpr()) {
12877 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12878 << FD->isConsteval()
12881 }
12882
12883 if (getLangOpts().OpenCL) {
12884 Diag(FD->getLocation(), diag::err_opencl_no_main)
12885 << FD->hasAttr<DeviceKernelAttr>();
12886 FD->setInvalidDecl();
12887 return;
12888 }
12889
12890 if (FD->hasAttr<SYCLExternalAttr>()) {
12891 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12892 << FD->getAttr<SYCLExternalAttr>();
12893 FD->setInvalidDecl();
12894 return;
12895 }
12896
12897 // Functions named main in hlsl are default entries, but don't have specific
12898 // signatures they are required to conform to.
12899 if (getLangOpts().HLSL)
12900 return;
12901
12902 QualType T = FD->getType();
12903 assert(T->isFunctionType() && "function decl is not of function type");
12904 const FunctionType* FT = T->castAs<FunctionType>();
12905
12906 // Set default calling convention for main()
12907 if (FT->getCallConv() != CC_C) {
12908 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12909 FD->setType(QualType(FT, 0));
12910 T = Context.getCanonicalType(FD->getType());
12911 }
12912
12914 // In C with GNU extensions we allow main() to have non-integer return
12915 // type, but we should warn about the extension, and we disable the
12916 // implicit-return-zero rule.
12917
12918 // GCC in C mode accepts qualified 'int'.
12919 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12920 FD->setHasImplicitReturnZero(true);
12921 else {
12922 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12923 SourceRange RTRange = FD->getReturnTypeSourceRange();
12924 if (RTRange.isValid())
12925 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12926 << FixItHint::CreateReplacement(RTRange, "int");
12927 }
12928 } else {
12929 // In C and C++, main magically returns 0 if you fall off the end;
12930 // set the flag which tells us that.
12931 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12932
12933 // All the standards say that main() should return 'int'.
12934 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12935 FD->setHasImplicitReturnZero(true);
12936 else {
12937 // Otherwise, this is just a flat-out error.
12938 SourceRange RTRange = FD->getReturnTypeSourceRange();
12939 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12940 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12941 : FixItHint());
12942 FD->setInvalidDecl(true);
12943 }
12944
12945 // [basic.start.main]p3:
12946 // A program that declares a function main that belongs to the global scope
12947 // and is attached to a named module is ill-formed.
12948 if (FD->isInNamedModule()) {
12949 const SourceLocation start = FD->getTypeSpecStartLoc();
12950 Diag(start, diag::warn_main_in_named_module)
12951 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12952 }
12953 }
12954
12955 // Treat protoless main() as nullary.
12956 if (isa<FunctionNoProtoType>(FT)) return;
12957
12959 unsigned nparams = FTP->getNumParams();
12960 assert(FD->getNumParams() == nparams);
12961
12962 bool HasExtraParameters = (nparams > 3);
12963
12964 if (FTP->isVariadic()) {
12965 Diag(FD->getLocation(), diag::ext_variadic_main);
12966 // FIXME: if we had information about the location of the ellipsis, we
12967 // could add a FixIt hint to remove it as a parameter.
12968 }
12969
12970 // Darwin passes an undocumented fourth argument of type char**. If
12971 // other platforms start sprouting these, the logic below will start
12972 // getting shifty.
12973 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12974 HasExtraParameters = false;
12975
12976 if (HasExtraParameters) {
12977 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12978 FD->setInvalidDecl(true);
12979 nparams = 3;
12980 }
12981
12982 // FIXME: a lot of the following diagnostics would be improved
12983 // if we had some location information about types.
12984
12985 QualType CharPP =
12986 Context.getPointerType(Context.getPointerType(Context.CharTy));
12987 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12988
12989 for (unsigned i = 0; i < nparams; ++i) {
12990 QualType AT = FTP->getParamType(i);
12991
12992 bool mismatch = true;
12993
12994 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12995 mismatch = false;
12996 else if (Expected[i] == CharPP) {
12997 // As an extension, the following forms are okay:
12998 // char const **
12999 // char const * const *
13000 // char * const *
13001
13003 const PointerType* PT;
13004 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
13005 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
13006 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
13007 Context.CharTy)) {
13008 qs.removeConst();
13009 mismatch = !qs.empty();
13010 }
13011 }
13012
13013 if (mismatch) {
13014 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
13015 // TODO: suggest replacing given type with expected type
13016 FD->setInvalidDecl(true);
13017 }
13018 }
13019
13020 if (nparams == 1 && !FD->isInvalidDecl()) {
13021 Diag(FD->getLocation(), diag::warn_main_one_arg);
13022 }
13023
13024 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13025 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
13026 FD->setInvalidDecl();
13027 }
13028}
13029
13030static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
13031
13032 // Default calling convention for main and wmain is __cdecl
13033 if (FD->getName() == "main" || FD->getName() == "wmain")
13034 return false;
13035
13036 // Default calling convention for MinGW and Cygwin is __cdecl
13037 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
13038 if (T.isOSCygMing())
13039 return false;
13040
13041 // Default calling convention for WinMain, wWinMain and DllMain
13042 // is __stdcall on 32 bit Windows
13043 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
13044 return true;
13045
13046 return false;
13047}
13048
13050 QualType T = FD->getType();
13051 assert(T->isFunctionType() && "function decl is not of function type");
13052 const FunctionType *FT = T->castAs<FunctionType>();
13053
13054 // Set an implicit return of 'zero' if the function can return some integral,
13055 // enumeration, pointer or nullptr type.
13059 // DllMain is exempt because a return value of zero means it failed.
13060 if (FD->getName() != "DllMain")
13061 FD->setHasImplicitReturnZero(true);
13062
13063 // Explicitly specified calling conventions are applied to MSVC entry points
13064 if (!hasExplicitCallingConv(T)) {
13065 if (isDefaultStdCall(FD, *this)) {
13066 if (FT->getCallConv() != CC_X86StdCall) {
13067 FT = Context.adjustFunctionType(
13069 FD->setType(QualType(FT, 0));
13070 }
13071 } else if (FT->getCallConv() != CC_C) {
13072 FT = Context.adjustFunctionType(FT,
13074 FD->setType(QualType(FT, 0));
13075 }
13076 }
13077
13078 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13079 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
13080 FD->setInvalidDecl();
13081 }
13082}
13083
13085 // FIXME: Need strict checking. In C89, we need to check for
13086 // any assignment, increment, decrement, function-calls, or
13087 // commas outside of a sizeof. In C99, it's the same list,
13088 // except that the aforementioned are allowed in unevaluated
13089 // expressions. Everything else falls under the
13090 // "may accept other forms of constant expressions" exception.
13091 //
13092 // Regular C++ code will not end up here (exceptions: language extensions,
13093 // OpenCL C++ etc), so the constant expression rules there don't matter.
13094 if (Init->isValueDependent()) {
13095 assert(Init->containsErrors() &&
13096 "Dependent code should only occur in error-recovery path.");
13097 return true;
13098 }
13099 const Expr *Culprit;
13100 if (Init->isConstantInitializer(Context, /*ForRef=*/false, &Culprit))
13101 return false;
13102
13103 // The culprit reported by isConstantInitializer() may be wrapped in implicit
13104 // casts and parentheses that it does not look through: under ARC an
13105 // object-pointer initializer is an `ImplicitCastExpr
13106 // <ARCReclaimReturnedObject>`, an `id`-typed (or otherwise differently-typed)
13107 // variable adds an `ImplicitCastExpr <BitCast>` on top, and a parenthesized
13108 // initializer such as `(@{...})` adds a `ParenExpr`. Strip all of these so
13109 // the ObjC-specific classification and per-element reporting below can see
13110 // the underlying literal regardless of how it is wrapped.
13111 const Expr *CulpritLiteral = Culprit->IgnoreParenImpCasts();
13112
13113 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
13114 if (getLangOpts().ObjCConstantLiterals &&
13115 isa<ObjCObjectLiteral>(CulpritLiteral)) {
13116
13117 // For collection literals, iterate the elements to point at the specific
13118 // offender. These per-element checks mirror the constant-initializer rules
13119 // applied when the literal was built (see SemaObjC::BuildObjCArrayLiteral
13120 // and SemaObjC::BuildObjCDictionaryLiteral): each element must itself be a
13121 // constant object literal, and dictionary keys must additionally be string
13122 // literals. Elements, keys and values are wrapped in an implicit BitCast to
13123 // `id`, so the isa<> classification is done on the unwrapped expression.
13124 if (const auto *ALE = dyn_cast<ObjCArrayLiteral>(CulpritLiteral)) {
13125 for (const Expr *Elm : ALE->elements()) {
13126 if (!isa<ObjCObjectLiteral>(Elm->IgnoreImpCasts()) ||
13127 !Elm->isConstantInitializer(Context)) {
13128 Diag(Elm->getExprLoc(),
13129 diag::err_objc_literal_nonconstant_at_file_scope)
13130 << ObjC().CheckLiteralKind(Init) << Elm->getSourceRange();
13131 return true;
13132 }
13133 }
13134 }
13135
13136 if (const auto *DLE = dyn_cast<ObjCDictionaryLiteral>(CulpritLiteral)) {
13137 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
13138 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(I);
13139
13140 // Keys must be constant string literals.
13143 Diag(Elm.Key->getExprLoc(),
13144 diag::err_objc_literal_nonconstant_at_file_scope)
13146 return true;
13147 }
13148
13149 // Values must be constant object literals.
13152 Diag(Elm.Value->getExprLoc(),
13153 diag::err_objc_literal_nonconstant_at_file_scope)
13155 return true;
13156 }
13157 }
13158 }
13159
13160 Diag(CulpritLiteral->getExprLoc(),
13161 diag::err_objc_literal_nonconstant_at_file_scope)
13162 << ObjC().CheckLiteralKind(Init) << CulpritLiteral->getSourceRange();
13163 return true;
13164 }
13165
13166 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
13167 return true;
13168}
13169
13170namespace {
13171 // Visits an initialization expression to see if OrigDecl is evaluated in
13172 // its own initialization and throws a warning if it does.
13173 class SelfReferenceChecker
13174 : public EvaluatedExprVisitor<SelfReferenceChecker> {
13175 Sema &S;
13176 Decl *OrigDecl;
13177 bool isRecordType;
13178 bool isPODType;
13179 bool isReferenceType;
13180 bool isInCXXOperatorCall;
13181
13182 bool isInitList;
13183 llvm::SmallVector<unsigned, 4> InitFieldIndex;
13184
13185 public:
13187
13188 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
13189 S(S), OrigDecl(OrigDecl) {
13190 isPODType = false;
13191 isRecordType = false;
13192 isReferenceType = false;
13193 isInCXXOperatorCall = false;
13194 isInitList = false;
13195 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
13196 isPODType = VD->getType().isPODType(S.Context);
13197 isRecordType = VD->getType()->isRecordType();
13198 isReferenceType = VD->getType()->isReferenceType();
13199 }
13200 }
13201
13202 // For most expressions, just call the visitor. For initializer lists,
13203 // track the index of the field being initialized since fields are
13204 // initialized in order allowing use of previously initialized fields.
13205 void CheckExpr(Expr *E) {
13206 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
13207 if (!InitList) {
13208 Visit(E);
13209 return;
13210 }
13211
13212 // Track and increment the index here.
13213 isInitList = true;
13214 InitFieldIndex.push_back(0);
13215 for (auto *Child : InitList->children()) {
13216 CheckExpr(cast<Expr>(Child));
13217 ++InitFieldIndex.back();
13218 }
13219 InitFieldIndex.pop_back();
13220 }
13221
13222 // Returns true if MemberExpr is checked and no further checking is needed.
13223 // Returns false if additional checking is required.
13224 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
13225 llvm::SmallVector<FieldDecl*, 4> Fields;
13226 Expr *Base = E;
13227 bool ReferenceField = false;
13228
13229 // Get the field members used.
13230 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13231 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13232 if (!FD)
13233 return false;
13234 Fields.push_back(FD);
13235 if (FD->getType()->isReferenceType())
13236 ReferenceField = true;
13237 Base = ME->getBase()->IgnoreParenImpCasts();
13238 }
13239
13240 // Keep checking only if the base Decl is the same.
13241 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
13242 if (!DRE || DRE->getDecl() != OrigDecl)
13243 return false;
13244
13245 // A reference field can be bound to an unininitialized field.
13246 if (CheckReference && !ReferenceField)
13247 return true;
13248
13249 // Convert FieldDecls to their index number.
13250 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13251 for (const FieldDecl *I : llvm::reverse(Fields))
13252 UsedFieldIndex.push_back(I->getFieldIndex());
13253
13254 // See if a warning is needed by checking the first difference in index
13255 // numbers. If field being used has index less than the field being
13256 // initialized, then the use is safe.
13257 for (auto UsedIter = UsedFieldIndex.begin(),
13258 UsedEnd = UsedFieldIndex.end(),
13259 OrigIter = InitFieldIndex.begin(),
13260 OrigEnd = InitFieldIndex.end();
13261 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13262 if (*UsedIter < *OrigIter)
13263 return true;
13264 if (*UsedIter > *OrigIter)
13265 break;
13266 }
13267
13268 // TODO: Add a different warning which will print the field names.
13269 HandleDeclRefExpr(DRE);
13270 return true;
13271 }
13272
13273 // For most expressions, the cast is directly above the DeclRefExpr.
13274 // For conditional operators, the cast can be outside the conditional
13275 // operator if both expressions are DeclRefExpr's.
13276 void HandleValue(Expr *E) {
13277 E = E->IgnoreParens();
13278 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
13279 HandleDeclRefExpr(DRE);
13280 return;
13281 }
13282
13283 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
13284 Visit(CO->getCond());
13285 HandleValue(CO->getTrueExpr());
13286 HandleValue(CO->getFalseExpr());
13287 return;
13288 }
13289
13290 if (BinaryConditionalOperator *BCO =
13291 dyn_cast<BinaryConditionalOperator>(E)) {
13292 Visit(BCO->getCond());
13293 HandleValue(BCO->getFalseExpr());
13294 return;
13295 }
13296
13297 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
13298 if (Expr *SE = OVE->getSourceExpr())
13299 HandleValue(SE);
13300 return;
13301 }
13302
13303 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13304 if (BO->getOpcode() == BO_Comma) {
13305 Visit(BO->getLHS());
13306 HandleValue(BO->getRHS());
13307 return;
13308 }
13309 }
13310
13311 if (isa<MemberExpr>(E)) {
13312 if (isInitList) {
13313 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
13314 false /*CheckReference*/))
13315 return;
13316 }
13317
13318 Expr *Base = E->IgnoreParenImpCasts();
13319 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13320 // Check for static member variables and don't warn on them.
13321 if (!isa<FieldDecl>(ME->getMemberDecl()))
13322 return;
13323 Base = ME->getBase()->IgnoreParenImpCasts();
13324 }
13325 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
13326 HandleDeclRefExpr(DRE);
13327 return;
13328 }
13329
13330 Visit(E);
13331 }
13332
13333 // Reference types not handled in HandleValue are handled here since all
13334 // uses of references are bad, not just r-value uses.
13335 void VisitDeclRefExpr(DeclRefExpr *E) {
13336 if (isReferenceType)
13337 HandleDeclRefExpr(E);
13338 }
13339
13340 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13341 if (E->getCastKind() == CK_LValueToRValue) {
13342 HandleValue(E->getSubExpr());
13343 return;
13344 }
13345
13346 Inherited::VisitImplicitCastExpr(E);
13347 }
13348
13349 void VisitMemberExpr(MemberExpr *E) {
13350 if (isInitList) {
13351 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13352 return;
13353 }
13354
13355 // Don't warn on arrays since they can be treated as pointers.
13356 if (E->getType()->canDecayToPointerType()) return;
13357
13358 // Warn when a non-static method call is followed by non-static member
13359 // field accesses, which is followed by a DeclRefExpr.
13360 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13361 bool Warn = (MD && !MD->isStatic());
13362 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13363 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13364 if (!isa<FieldDecl>(ME->getMemberDecl()))
13365 Warn = false;
13366 Base = ME->getBase()->IgnoreParenImpCasts();
13367 }
13368
13369 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13370 if (Warn)
13371 HandleDeclRefExpr(DRE);
13372 return;
13373 }
13374
13375 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13376 // Visit that expression.
13377 Visit(Base);
13378 }
13379
13380 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13381 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13382 Expr *Callee = E->getCallee();
13383
13384 if (isa<UnresolvedLookupExpr>(Callee))
13385 return Inherited::VisitCXXOperatorCallExpr(E);
13386
13387 Visit(Callee);
13388 for (auto Arg: E->arguments())
13389 HandleValue(Arg->IgnoreParenImpCasts());
13390 }
13391
13392 void VisitLambdaExpr(LambdaExpr *E) {
13393 if (!isInCXXOperatorCall) {
13394 Inherited::VisitLambdaExpr(E);
13395 return;
13396 }
13397
13398 for (Expr *Init : E->capture_inits())
13399 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13400 HandleDeclRefExpr(DRE);
13401 else if (Init)
13402 Visit(Init);
13403 }
13404
13405 void VisitUnaryOperator(UnaryOperator *E) {
13406 // For POD record types, addresses of its own members are well-defined.
13407 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13409 if (!isPODType)
13410 HandleValue(E->getSubExpr());
13411 return;
13412 }
13413
13414 if (E->isIncrementDecrementOp()) {
13415 HandleValue(E->getSubExpr());
13416 return;
13417 }
13418
13419 Inherited::VisitUnaryOperator(E);
13420 }
13421
13422 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13423
13424 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13425 if (E->getConstructor()->isCopyConstructor()) {
13426 Expr *ArgExpr = E->getArg(0);
13427 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13428 if (ILE->getNumInits() == 1)
13429 ArgExpr = ILE->getInit(0);
13430 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13431 if (ICE->getCastKind() == CK_NoOp)
13432 ArgExpr = ICE->getSubExpr();
13433 HandleValue(ArgExpr);
13434 return;
13435 }
13436 Inherited::VisitCXXConstructExpr(E);
13437 }
13438
13439 void VisitCallExpr(CallExpr *E) {
13440 // Treat std::move as a use.
13441 if (E->isCallToStdMove()) {
13442 HandleValue(E->getArg(0));
13443 return;
13444 }
13445
13446 Inherited::VisitCallExpr(E);
13447 }
13448
13449 void VisitBinaryOperator(BinaryOperator *E) {
13450 if (E->isCompoundAssignmentOp()) {
13451 HandleValue(E->getLHS());
13452 Visit(E->getRHS());
13453 return;
13454 }
13455
13456 Inherited::VisitBinaryOperator(E);
13457 }
13458
13459 // A custom visitor for BinaryConditionalOperator is needed because the
13460 // regular visitor would check the condition and true expression separately
13461 // but both point to the same place giving duplicate diagnostics.
13462 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13463 Visit(E->getCond());
13464 Visit(E->getFalseExpr());
13465 }
13466
13467 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13468 Decl* ReferenceDecl = DRE->getDecl();
13469 if (OrigDecl != ReferenceDecl) return;
13470 unsigned diag;
13471 if (isReferenceType) {
13472 diag = diag::warn_uninit_self_reference_in_reference_init;
13473 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13474 diag = diag::warn_static_self_reference_in_init;
13475 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13476 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13477 DRE->getDecl()->getType()->isRecordType()) {
13478 diag = diag::warn_uninit_self_reference_in_init;
13479 } else {
13480 // Local variables will be handled by the CFG analysis.
13481 return;
13482 }
13483
13484 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13485 S.PDiag(diag)
13486 << DRE->getDecl() << OrigDecl->getLocation()
13487 << DRE->getSourceRange());
13488 }
13489 };
13490
13491 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13492 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13493 bool DirectInit) {
13494 // Parameters arguments are occassionially constructed with itself,
13495 // for instance, in recursive functions. Skip them.
13496 if (isa<ParmVarDecl>(OrigDecl))
13497 return;
13498
13499 // Skip checking for file-scope constexpr variables - constant evaluation
13500 // will produce appropriate errors without needing runtime diagnostics.
13501 // Local constexpr should still emit runtime warnings.
13502 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13503 VD && VD->isConstexpr() && VD->isFileVarDecl())
13504 return;
13505
13506 E = E->IgnoreParens();
13507
13508 // Skip checking T a = a where T is not a record or reference type.
13509 // Doing so is a way to silence uninitialized warnings.
13510 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13511 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13512 if (ICE->getCastKind() == CK_LValueToRValue)
13513 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13514 if (DRE->getDecl() == OrigDecl)
13515 return;
13516
13517 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13518 }
13519} // end anonymous namespace
13520
13521namespace {
13522 // Simple wrapper to add the name of a variable or (if no variable is
13523 // available) a DeclarationName into a diagnostic.
13524 struct VarDeclOrName {
13525 VarDecl *VDecl;
13526 DeclarationName Name;
13527
13528 friend const Sema::SemaDiagnosticBuilder &
13529 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13530 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13531 }
13532 };
13533} // end anonymous namespace
13534
13537 TypeSourceInfo *TSI,
13538 SourceRange Range, bool DirectInit,
13539 Expr *Init) {
13540 bool IsInitCapture = !VDecl;
13541 assert((!VDecl || !VDecl->isInitCapture()) &&
13542 "init captures are expected to be deduced prior to initialization");
13543
13544 VarDeclOrName VN{VDecl, Name};
13545
13546 DeducedType *Deduced = Type->getContainedDeducedType();
13547 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13548
13549 // Diagnose auto array declarations in C23, unless it's a supported extension.
13550 if (getLangOpts().C23 && Type->isArrayType() &&
13551 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13552 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13553 << (int)Deduced->getContainedAutoType()->getKeyword()
13554 << /*in array decl*/ 23 << Range;
13555 return QualType();
13556 }
13557
13558 // C++11 [dcl.spec.auto]p3
13559 if (!Init) {
13560 assert(VDecl && "no init for init capture deduction?");
13561
13562 // Except for class argument deduction, and then for an initializing
13563 // declaration only, i.e. no static at class scope or extern.
13565 VDecl->hasExternalStorage() ||
13566 VDecl->isStaticDataMember()) {
13567 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13568 << VDecl->getDeclName() << Type;
13569 return QualType();
13570 }
13571 }
13572
13573 ArrayRef<Expr*> DeduceInits;
13574 if (Init)
13575 DeduceInits = Init;
13576
13577 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13578 if (DirectInit && PL)
13579 DeduceInits = PL->exprs();
13580
13582 assert(VDecl && "non-auto type for init capture deduction?");
13585 VDecl->getLocation(), DirectInit, Init);
13586 // FIXME: Initialization should not be taking a mutable list of inits.
13587 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13588 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13589 InitsCopy);
13590 }
13591
13592 if (DirectInit) {
13593 if (auto *IL = dyn_cast<InitListExpr>(Init))
13594 DeduceInits = IL->inits();
13595 }
13596
13597 // Deduction only works if we have exactly one source expression.
13598 if (DeduceInits.empty()) {
13599 // It isn't possible to write this directly, but it is possible to
13600 // end up in this situation with "auto x(some_pack...);"
13601 Diag(Init->getBeginLoc(), IsInitCapture
13602 ? diag::err_init_capture_no_expression
13603 : diag::err_auto_var_init_no_expression)
13604 << VN << Type << Range;
13605 return QualType();
13606 }
13607
13608 if (DeduceInits.size() > 1) {
13609 Diag(DeduceInits[1]->getBeginLoc(),
13610 IsInitCapture ? diag::err_init_capture_multiple_expressions
13611 : diag::err_auto_var_init_multiple_expressions)
13612 << VN << Type << Range;
13613 return QualType();
13614 }
13615
13616 Expr *DeduceInit = DeduceInits[0];
13617 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13618 Diag(Init->getBeginLoc(), IsInitCapture
13619 ? diag::err_init_capture_paren_braces
13620 : diag::err_auto_var_init_paren_braces)
13621 << isa<InitListExpr>(Init) << VN << Type << Range;
13622 return QualType();
13623 }
13624
13625 // Expressions default to 'id' when we're in a debugger.
13626 bool DefaultedAnyToId = false;
13627 if (getLangOpts().DebuggerCastResultToId &&
13628 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13630 if (Result.isInvalid()) {
13631 return QualType();
13632 }
13633 Init = Result.get();
13634 DefaultedAnyToId = true;
13635 }
13636
13637 // C++ [dcl.decomp]p1:
13638 // If the assignment-expression [...] has array type A and no ref-qualifier
13639 // is present, e has type cv A
13640 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13641 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13642 DeduceInit->getType()->isConstantArrayType())
13643 return Context.getQualifiedType(DeduceInit->getType(),
13644 Type.getQualifiers());
13645
13646 QualType DeducedType;
13647 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13649 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13652 if (!IsInitCapture)
13653 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13654 else if (isa<InitListExpr>(Init))
13655 Diag(Range.getBegin(),
13656 diag::err_init_capture_deduction_failure_from_init_list)
13657 << VN
13658 << (DeduceInit->getType().isNull() ? TSI->getType()
13659 : DeduceInit->getType())
13660 << DeduceInit->getSourceRange();
13661 else
13662 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13663 << VN << TSI->getType()
13664 << (DeduceInit->getType().isNull() ? TSI->getType()
13665 : DeduceInit->getType())
13666 << DeduceInit->getSourceRange();
13667 }
13668
13669 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13670 // 'id' instead of a specific object type prevents most of our usual
13671 // checks.
13672 // We only want to warn outside of template instantiations, though:
13673 // inside a template, the 'id' could have come from a parameter.
13674 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13675 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13676 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13677 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13678 }
13679
13680 return DeducedType;
13681}
13682
13684 Expr *Init) {
13685 assert(!Init || !Init->containsErrors());
13687 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13688 VDecl->getSourceRange(), DirectInit, Init);
13689 if (DeducedType.isNull()) {
13690 VDecl->setInvalidDecl();
13691 return true;
13692 }
13693
13694 VDecl->setType(DeducedType);
13695 assert(VDecl->isLinkageValid());
13696
13697 // In ARC, infer lifetime.
13698 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13699 VDecl->setInvalidDecl();
13700
13701 if (getLangOpts().OpenCL)
13703
13704 if (getLangOpts().HLSL)
13705 HLSL().deduceAddressSpace(VDecl);
13706
13707 // If this is a redeclaration, check that the type we just deduced matches
13708 // the previously declared type.
13709 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13710 // We never need to merge the type, because we cannot form an incomplete
13711 // array of auto, nor deduce such a type.
13712 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13713 }
13714
13715 // Check the deduced type is valid for a variable declaration.
13717 return VDecl->isInvalidDecl();
13718}
13719
13721 SourceLocation Loc) {
13722 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13723 Init = EWC->getSubExpr();
13724
13725 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13726 Init = CE->getSubExpr();
13727
13728 QualType InitType = Init->getType();
13731 "shouldn't be called if type doesn't have a non-trivial C struct");
13732 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13733 for (auto *I : ILE->inits()) {
13734 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13735 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13736 continue;
13737 SourceLocation SL = I->getExprLoc();
13738 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13739 }
13740 return;
13741 }
13742
13745 checkNonTrivialCUnion(InitType, Loc,
13747 NTCUK_Init);
13748 } else {
13749 // Assume all other explicit initializers involving copying some existing
13750 // object.
13751 // TODO: ignore any explicit initializers where we can guarantee
13752 // copy-elision.
13755 NTCUK_Copy);
13756 }
13757}
13758
13759namespace {
13760
13761bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13762 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13763 // in the source code or implicitly by the compiler if it is in a union
13764 // defined in a system header and has non-trivial ObjC ownership
13765 // qualifications. We don't want those fields to participate in determining
13766 // whether the containing union is non-trivial.
13767 return FD->hasAttr<UnavailableAttr>();
13768}
13769
13770struct DiagNonTrivalCUnionDefaultInitializeVisitor
13771 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13772 void> {
13773 using Super =
13774 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13775 void>;
13776
13777 DiagNonTrivalCUnionDefaultInitializeVisitor(
13778 QualType OrigTy, SourceLocation OrigLoc,
13779 NonTrivialCUnionContext UseContext, Sema &S)
13780 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13781
13782 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13783 const FieldDecl *FD, bool InNonTrivialUnion) {
13784 if (const auto *AT = S.Context.getAsArrayType(QT))
13785 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13786 InNonTrivialUnion);
13787 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13788 }
13789
13790 void visitARCStrong(QualType QT, const FieldDecl *FD,
13791 bool InNonTrivialUnion) {
13792 if (InNonTrivialUnion)
13793 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13794 << 1 << 0 << QT << FD->getName();
13795 }
13796
13797 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13798 if (InNonTrivialUnion)
13799 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13800 << 1 << 0 << QT << FD->getName();
13801 }
13802
13803 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13804 const auto *RD = QT->castAsRecordDecl();
13805 if (RD->isUnion()) {
13806 if (OrigLoc.isValid()) {
13807 bool IsUnion = false;
13808 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13809 IsUnion = OrigRD->isUnion();
13810 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13811 << 0 << OrigTy << IsUnion << UseContext;
13812 // Reset OrigLoc so that this diagnostic is emitted only once.
13813 OrigLoc = SourceLocation();
13814 }
13815 InNonTrivialUnion = true;
13816 }
13817
13818 if (InNonTrivialUnion)
13819 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13820 << 0 << 0 << QT.getUnqualifiedType() << "";
13821
13822 for (const FieldDecl *FD : RD->fields())
13823 if (!shouldIgnoreForRecordTriviality(FD))
13824 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13825 }
13826
13827 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13828
13829 // The non-trivial C union type or the struct/union type that contains a
13830 // non-trivial C union.
13831 QualType OrigTy;
13832 SourceLocation OrigLoc;
13833 NonTrivialCUnionContext UseContext;
13834 Sema &S;
13835};
13836
13837struct DiagNonTrivalCUnionDestructedTypeVisitor
13838 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13839 using Super =
13840 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13841
13842 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13843 SourceLocation OrigLoc,
13844 NonTrivialCUnionContext UseContext,
13845 Sema &S)
13846 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13847
13848 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13849 const FieldDecl *FD, bool InNonTrivialUnion) {
13850 if (const auto *AT = S.Context.getAsArrayType(QT))
13851 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13852 InNonTrivialUnion);
13853 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13854 }
13855
13856 void visitARCStrong(QualType QT, const FieldDecl *FD,
13857 bool InNonTrivialUnion) {
13858 if (InNonTrivialUnion)
13859 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13860 << 1 << 1 << QT << FD->getName();
13861 }
13862
13863 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13864 if (InNonTrivialUnion)
13865 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13866 << 1 << 1 << QT << FD->getName();
13867 }
13868
13869 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13870 const auto *RD = QT->castAsRecordDecl();
13871 if (RD->isUnion()) {
13872 if (OrigLoc.isValid()) {
13873 bool IsUnion = false;
13874 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13875 IsUnion = OrigRD->isUnion();
13876 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13877 << 1 << OrigTy << IsUnion << UseContext;
13878 // Reset OrigLoc so that this diagnostic is emitted only once.
13879 OrigLoc = SourceLocation();
13880 }
13881 InNonTrivialUnion = true;
13882 }
13883
13884 if (InNonTrivialUnion)
13885 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13886 << 0 << 1 << QT.getUnqualifiedType() << "";
13887
13888 for (const FieldDecl *FD : RD->fields())
13889 if (!shouldIgnoreForRecordTriviality(FD))
13890 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13891 }
13892
13893 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13894 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13895 bool InNonTrivialUnion) {}
13896
13897 // The non-trivial C union type or the struct/union type that contains a
13898 // non-trivial C union.
13899 QualType OrigTy;
13900 SourceLocation OrigLoc;
13901 NonTrivialCUnionContext UseContext;
13902 Sema &S;
13903};
13904
13905struct DiagNonTrivalCUnionCopyVisitor
13906 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13907 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13908
13909 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13910 NonTrivialCUnionContext UseContext, Sema &S)
13911 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13912
13913 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13914 const FieldDecl *FD, bool InNonTrivialUnion) {
13915 if (const auto *AT = S.Context.getAsArrayType(QT))
13916 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13917 InNonTrivialUnion);
13918 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13919 }
13920
13921 void visitARCStrong(QualType QT, const FieldDecl *FD,
13922 bool InNonTrivialUnion) {
13923 if (InNonTrivialUnion)
13924 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13925 << 1 << 2 << QT << FD->getName();
13926 }
13927
13928 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13929 if (InNonTrivialUnion)
13930 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13931 << 1 << 2 << QT << FD->getName();
13932 }
13933
13934 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13935 const auto *RD = QT->castAsRecordDecl();
13936 if (RD->isUnion()) {
13937 if (OrigLoc.isValid()) {
13938 bool IsUnion = false;
13939 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13940 IsUnion = OrigRD->isUnion();
13941 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13942 << 2 << OrigTy << IsUnion << UseContext;
13943 // Reset OrigLoc so that this diagnostic is emitted only once.
13944 OrigLoc = SourceLocation();
13945 }
13946 InNonTrivialUnion = true;
13947 }
13948
13949 if (InNonTrivialUnion)
13950 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13951 << 0 << 2 << QT.getUnqualifiedType() << "";
13952
13953 for (const FieldDecl *FD : RD->fields())
13954 if (!shouldIgnoreForRecordTriviality(FD))
13955 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13956 }
13957
13958 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13959 if (InNonTrivialUnion)
13960 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13961 << 1 << 2 << QT << FD->getName();
13962 }
13963
13964 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13965 const FieldDecl *FD, bool InNonTrivialUnion) {}
13966 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13967 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13968 bool InNonTrivialUnion) {}
13969
13970 // The non-trivial C union type or the struct/union type that contains a
13971 // non-trivial C union.
13972 QualType OrigTy;
13973 SourceLocation OrigLoc;
13974 NonTrivialCUnionContext UseContext;
13975 Sema &S;
13976};
13977
13978} // namespace
13979
13981 NonTrivialCUnionContext UseContext,
13982 unsigned NonTrivialKind) {
13986 "shouldn't be called if type doesn't have a non-trivial C union");
13987
13988 if ((NonTrivialKind & NTCUK_Init) &&
13990 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13991 .visit(QT, nullptr, false);
13992 if ((NonTrivialKind & NTCUK_Destruct) &&
13994 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13995 .visit(QT, nullptr, false);
13996 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13997 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13998 .visit(QT, nullptr, false);
13999}
14000
14002 const VarDecl *Dcl) {
14003 if (!getLangOpts().CPlusPlus)
14004 return false;
14005
14006 // We only need to warn if the definition is in a header file, so wait to
14007 // diagnose until we've seen the definition.
14008 if (!Dcl->isThisDeclarationADefinition())
14009 return false;
14010
14011 // If an object is defined in a source file, its definition can't get
14012 // duplicated since it will never appear in more than one TU.
14014 return false;
14015
14016 // If the variable we're looking at is a static local, then we actually care
14017 // about the properties of the function containing it.
14018 const ValueDecl *Target = Dcl;
14019 // VarDecls and FunctionDecls have different functions for checking
14020 // inline-ness, and whether they were originally templated, so we have to
14021 // call the appropriate functions manually.
14022 bool TargetIsInline = Dcl->isInline();
14023 bool TargetWasTemplated =
14025
14026 // Update the Target and TargetIsInline property if necessary
14027 if (Dcl->isStaticLocal()) {
14028 const DeclContext *Ctx = Dcl->getDeclContext();
14029 if (!Ctx)
14030 return false;
14031
14032 const FunctionDecl *FunDcl =
14033 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
14034 if (!FunDcl)
14035 return false;
14036
14037 Target = FunDcl;
14038 // IsInlined() checks for the C++ inline property
14039 TargetIsInline = FunDcl->isInlined();
14040 TargetWasTemplated =
14042 }
14043
14044 // Non-inline functions/variables can only legally appear in one TU
14045 // unless they were part of a template. Unfortunately, making complex
14046 // template instantiations visible is infeasible in practice, since
14047 // everything the template depends on also has to be visible. To avoid
14048 // giving impractical-to-fix warnings, don't warn if we're inside
14049 // something that was templated, even on inline stuff.
14050 if (!TargetIsInline || TargetWasTemplated)
14051 return false;
14052
14053 // If the object isn't hidden, the dynamic linker will prevent duplication.
14054 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
14055
14056 // The target is "hidden" (from the dynamic linker) if:
14057 // 1. On posix, it has hidden visibility, or
14058 // 2. On windows, it has no import/export annotation, and neither does the
14059 // class which directly contains it.
14060 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
14061 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
14062 return false;
14063
14064 // If the variable isn't directly annotated, check to see if it's a member
14065 // of an annotated class.
14066 const CXXRecordDecl *Ctx =
14067 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
14068 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
14069 return false;
14070
14071 } else if (Lnk.getVisibility() != HiddenVisibility) {
14072 // Posix case
14073 return false;
14074 }
14075
14076 // If the obj doesn't have external linkage, it's supposed to be duplicated.
14078 return false;
14079
14080 return true;
14081}
14082
14083// Determine whether the object seems mutable for the purpose of diagnosing
14084// possible unique object duplication, i.e. non-const-qualified, and
14085// not an always-constant type like a function.
14086// Not perfect: doesn't account for mutable members, for example, or
14087// elements of container types.
14088// For nested pointers, any individual level being non-const is sufficient.
14089static bool looksMutable(QualType T, const ASTContext &Ctx) {
14090 T = T.getNonReferenceType();
14091 if (T->isFunctionType())
14092 return false;
14093 if (!T.isConstant(Ctx))
14094 return true;
14095 if (T->isPointerType())
14096 return looksMutable(T->getPointeeType(), Ctx);
14097 return false;
14098}
14099
14101 // If this object has external linkage and hidden visibility, it might be
14102 // duplicated when built into a shared library, which causes problems if it's
14103 // mutable (since the copies won't be in sync) or its initialization has side
14104 // effects (since it will run once per copy instead of once globally).
14105
14106 // Don't diagnose if we're inside a template, because it's not practical to
14107 // fix the warning in most cases.
14108 if (!VD->isTemplated() &&
14110
14111 QualType Type = VD->getType();
14112 if (looksMutable(Type, VD->getASTContext())) {
14113 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
14114 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14115 }
14116
14117 // To keep false positives low, only warn if we're certain that the
14118 // initializer has side effects. Don't warn on operator new, since a mutable
14119 // pointer will trigger the previous warning, and an immutable pointer
14120 // getting duplicated just results in a little extra memory usage.
14121 const Expr *Init = VD->getAnyInitializer();
14122 if (Init &&
14123 Init->HasSideEffects(VD->getASTContext(),
14124 /*IncludePossibleEffects=*/false) &&
14125 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
14126 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
14127 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14128 }
14129 }
14130}
14131
14133 llvm::scope_exit ResetDeclForInitializer([this]() {
14134 if (!this->ExprEvalContexts.empty())
14135 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
14136 });
14137
14138 // If there is no declaration, there was an error parsing it. Just ignore
14139 // the initializer.
14140 if (!RealDecl) {
14141 return;
14142 }
14143
14144 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
14145 if (!Method->isInvalidDecl()) {
14146 // Pure-specifiers are handled in ActOnPureSpecifier.
14147 Diag(Method->getLocation(), diag::err_member_function_initialization)
14148 << Method->getDeclName() << Init->getSourceRange();
14149 Method->setInvalidDecl();
14150 }
14151 return;
14152 }
14153
14154 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
14155 if (!VDecl) {
14156 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
14157 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
14158 RealDecl->setInvalidDecl();
14159 return;
14160 }
14161
14162 if (VDecl->isInvalidDecl()) {
14163 ExprResult Recovery =
14164 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
14165 if (Expr *E = Recovery.get())
14166 VDecl->setInit(E);
14167 return;
14168 }
14169
14170 // __amdgpu_feature_predicate_t cannot be initialised
14171 if (VDecl->getType().getDesugaredType(Context) ==
14172 Context.AMDGPUFeaturePredicateTy) {
14173 Diag(VDecl->getLocation(),
14174 diag::err_amdgcn_predicate_type_is_not_constructible)
14175 << VDecl;
14176 VDecl->setInvalidDecl();
14177 return;
14178 }
14179
14180 // WebAssembly tables can't be used to initialise a variable.
14181 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
14182 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
14183 VDecl->setInvalidDecl();
14184 return;
14185 }
14186
14187 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
14188 if (VDecl->getType()->isUndeducedType()) {
14189 if (Init->containsErrors()) {
14190 // Invalidate the decl as we don't know the type for recovery-expr yet.
14191 RealDecl->setInvalidDecl();
14192 VDecl->setInit(Init);
14193 return;
14194 }
14195
14197 assert(VDecl->isInvalidDecl() &&
14198 "decl should be invalidated when deduce fails");
14199 if (auto *RecoveryExpr =
14200 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init})
14201 .get())
14202 VDecl->setInit(RecoveryExpr);
14203 return;
14204 }
14205 }
14206
14207 this->CheckAttributesOnDeducedType(RealDecl);
14208
14209 // we don't initialize groupshared variables so warn and return
14210 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
14211 Diag(VDecl->getLocation(), diag::warn_hlsl_groupshared_init);
14212 return;
14213 }
14214
14215 // dllimport cannot be used on variable definitions.
14216 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
14217 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
14218 VDecl->setInvalidDecl();
14219 return;
14220 }
14221
14222 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
14223 // the identifier has external or internal linkage, the declaration shall
14224 // have no initializer for the identifier.
14225 // C++14 [dcl.init]p5 is the same restriction for C++.
14226 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14227 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
14228 VDecl->setInvalidDecl();
14229 return;
14230 }
14231
14232 if (!VDecl->getType()->isDependentType()) {
14233 // A definition must end up with a complete type, which means it must be
14234 // complete with the restriction that an array type might be completed by
14235 // the initializer; note that later code assumes this restriction.
14236 QualType BaseDeclType = VDecl->getType();
14237 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
14238 BaseDeclType = Array->getElementType();
14239 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
14240 diag::err_typecheck_decl_incomplete_type)) {
14241 RealDecl->setInvalidDecl();
14242 return;
14243 }
14244
14245 // The variable can not have an abstract class type.
14246 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
14247 diag::err_abstract_type_in_decl,
14249 VDecl->setInvalidDecl();
14250 }
14251
14252 // C++ [module.import/6]
14253 // ...
14254 // A header unit shall not contain a definition of a non-inline function or
14255 // variable whose name has external linkage.
14256 //
14257 // We choose to allow weak & selectany definitions, as they are common in
14258 // headers, and have semantics similar to inline definitions which are allowed
14259 // in header units.
14260 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14261 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14262 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14263 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
14265 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14266 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
14267 VDecl->setInvalidDecl();
14268 }
14269
14270 // If adding the initializer will turn this declaration into a definition,
14271 // and we already have a definition for this variable, diagnose or otherwise
14272 // handle the situation.
14273 if (VarDecl *Def = VDecl->getDefinition())
14274 if (Def != VDecl &&
14275 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14277 checkVarDeclRedefinition(Def, VDecl))
14278 return;
14279
14280 if (getLangOpts().CPlusPlus) {
14281 // C++ [class.static.data]p4
14282 // If a static data member is of const integral or const
14283 // enumeration type, its declaration in the class definition can
14284 // specify a constant-initializer which shall be an integral
14285 // constant expression (5.19). In that case, the member can appear
14286 // in integral constant expressions. The member shall still be
14287 // defined in a namespace scope if it is used in the program and the
14288 // namespace scope definition shall not contain an initializer.
14289 //
14290 // We already performed a redefinition check above, but for static
14291 // data members we also need to check whether there was an in-class
14292 // declaration with an initializer.
14293 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14294 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
14295 << VDecl->getDeclName();
14296 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14297 diag::note_previous_initializer)
14298 << 0;
14299 return;
14300 }
14301
14303 VDecl->setInvalidDecl();
14304 return;
14305 }
14306 }
14307
14308 // If the variable has an initializer and local storage, check whether
14309 // anything jumps over the initialization.
14310 if (VDecl->hasLocalStorage())
14312
14313 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14314 // a kernel function cannot be initialized."
14315 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14316 Diag(VDecl->getLocation(), diag::err_local_cant_init);
14317 VDecl->setInvalidDecl();
14318 return;
14319 }
14320
14321 // The LoaderUninitialized attribute acts as a definition (of undef).
14322 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14323 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
14324 VDecl->setInvalidDecl();
14325 return;
14326 }
14327
14328 if (getLangOpts().HLSL)
14329 if (!HLSL().handleInitialization(VDecl, Init))
14330 return;
14331
14332 // Get the decls type and save a reference for later, since
14333 // CheckInitializerTypes may change it.
14334 QualType DclT = VDecl->getType(), SavT = DclT;
14335
14336 // Expressions default to 'id' when we're in a debugger
14337 // and we are assigning it to a variable of Objective-C pointer type.
14338 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14339 Init->getType() == Context.UnknownAnyTy) {
14341 if (!Result.isUsable()) {
14342 VDecl->setInvalidDecl();
14343 return;
14344 }
14345 Init = Result.get();
14346 }
14347
14348 // Perform the initialization.
14349 bool InitializedFromParenListExpr = false;
14350 bool IsParenListInit = false;
14351 if (!VDecl->isInvalidDecl()) {
14354 VDecl->getLocation(), DirectInit, Init);
14355
14356 MultiExprArg Args = Init;
14357 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
14358 Args =
14359 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14360 InitializedFromParenListExpr = true;
14361 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
14362 Args = CXXDirectInit->getInitExprs();
14363 InitializedFromParenListExpr = true;
14364 }
14365
14366 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14367 /*TopLevelOfInitList=*/false,
14368 /*TreatUnavailableAsInvalid=*/false);
14369 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14370 if (!Result.isUsable()) {
14371 // If the provided initializer fails to initialize the var decl,
14372 // we attach a recovery expr for better recovery.
14373 auto RecoveryExpr =
14374 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14375 if (RecoveryExpr.get())
14376 VDecl->setInit(RecoveryExpr.get());
14377 // In general, for error recovery purposes, the initializer doesn't play
14378 // part in the valid bit of the declaration. There are a few exceptions:
14379 // 1) if the var decl has a deduced auto type, and the type cannot be
14380 // deduced by an invalid initializer;
14381 // 2) if the var decl is a decomposition decl with a non-deduced type,
14382 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14383 // Case 1) was already handled elsewhere.
14384 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14385 VDecl->setInvalidDecl();
14386 return;
14387 }
14388
14389 Init = Result.getAs<Expr>();
14390 IsParenListInit = !InitSeq.steps().empty() &&
14391 InitSeq.step_begin()->Kind ==
14393 QualType VDeclType = VDecl->getType();
14394 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14395 !VDeclType->isDependentType() &&
14396 Context.getAsIncompleteArrayType(VDeclType) &&
14397 Context.getAsIncompleteArrayType(Init->getType())) {
14398 // Bail out if it is not possible to deduce array size from the
14399 // initializer.
14400 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14401 << VDeclType;
14402 VDecl->setInvalidDecl();
14403 return;
14404 }
14405 }
14406
14407 // Check for self-references within variable initializers.
14408 // Variables declared within a function/method body (except for references)
14409 // are handled by a dataflow analysis.
14410 // This is undefined behavior in C++, but valid in C.
14411 if (getLangOpts().CPlusPlus)
14412 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14413 VDecl->getType()->isReferenceType())
14414 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14415
14416 // If the type changed, it means we had an incomplete type that was
14417 // completed by the initializer. For example:
14418 // int ary[] = { 1, 3, 5 };
14419 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14420 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14421 VDecl->setType(DclT);
14422
14423 if (!VDecl->isInvalidDecl()) {
14424 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14425
14426 if (VDecl->hasAttr<BlocksAttr>())
14427 ObjC().checkRetainCycles(VDecl, Init);
14428
14429 // It is safe to assign a weak reference into a strong variable.
14430 // Although this code can still have problems:
14431 // id x = self.weakProp;
14432 // id y = self.weakProp;
14433 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14434 // paths through the function. This should be revisited if
14435 // -Wrepeated-use-of-weak is made flow-sensitive.
14436 if (FunctionScopeInfo *FSI = getCurFunction())
14437 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14439 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14440 Init->getBeginLoc()))
14441 FSI->markSafeWeakUse(Init);
14442 }
14443
14444 // The initialization is usually a full-expression.
14445 //
14446 // FIXME: If this is a braced initialization of an aggregate, it is not
14447 // an expression, and each individual field initializer is a separate
14448 // full-expression. For instance, in:
14449 //
14450 // struct Temp { ~Temp(); };
14451 // struct S { S(Temp); };
14452 // struct T { S a, b; } t = { Temp(), Temp() }
14453 //
14454 // we should destroy the first Temp before constructing the second.
14455
14456 // Set context flag for OverflowBehaviorType initialization analysis
14458 true);
14461 /*DiscardedValue*/ false, VDecl->isConstexpr());
14462 if (!Result.isUsable()) {
14463 VDecl->setInvalidDecl();
14464 return;
14465 }
14466 Init = Result.get();
14467
14468 // Attach the initializer to the decl.
14469 VDecl->setInit(Init);
14470
14471 if (VDecl->isLocalVarDecl()) {
14472 // Don't check the initializer if the declaration is malformed.
14473 if (VDecl->isInvalidDecl()) {
14474 // do nothing
14475
14476 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14477 // This is true even in C++ for OpenCL.
14478 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14480
14481 // Otherwise, C++ does not restrict the initializer.
14482 } else if (getLangOpts().CPlusPlus) {
14483 // do nothing
14484
14485 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14486 // static storage duration shall be constant expressions or string literals.
14487 } else if (VDecl->getStorageClass() == SC_Static) {
14488 // Avoid evaluating the initializer twice for constexpr variables. It will
14489 // be evaluated later.
14490 if (!VDecl->isConstexpr())
14492
14493 // C89 is stricter than C99 for aggregate initializers.
14494 // C89 6.5.7p3: All the expressions [...] in an initializer list
14495 // for an object that has aggregate or union type shall be
14496 // constant expressions.
14497 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14499 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14500 }
14501
14502 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14503 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14504 if (VDecl->hasLocalStorage())
14505 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14506 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14507 VDecl->getLexicalDeclContext()->isRecord()) {
14508 // This is an in-class initialization for a static data member, e.g.,
14509 //
14510 // struct S {
14511 // static const int value = 17;
14512 // };
14513
14514 // C++ [class.mem]p4:
14515 // A member-declarator can contain a constant-initializer only
14516 // if it declares a static member (9.4) of const integral or
14517 // const enumeration type, see 9.4.2.
14518 //
14519 // C++11 [class.static.data]p3:
14520 // If a non-volatile non-inline const static data member is of integral
14521 // or enumeration type, its declaration in the class definition can
14522 // specify a brace-or-equal-initializer in which every initializer-clause
14523 // that is an assignment-expression is a constant expression. A static
14524 // data member of literal type can be declared in the class definition
14525 // with the constexpr specifier; if so, its declaration shall specify a
14526 // brace-or-equal-initializer in which every initializer-clause that is
14527 // an assignment-expression is a constant expression.
14528
14529 // Do nothing on dependent types.
14530 if (DclT->isDependentType()) {
14531
14532 // Allow any 'static constexpr' members, whether or not they are of literal
14533 // type. We separately check that every constexpr variable is of literal
14534 // type.
14535 } else if (VDecl->isConstexpr()) {
14536
14537 // Require constness.
14538 } else if (!DclT.isConstQualified()) {
14539 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14540 << Init->getSourceRange();
14541 VDecl->setInvalidDecl();
14542
14543 // We allow integer constant expressions in all cases.
14544 } else if (DclT->isIntegralOrEnumerationType()) {
14546 // In C++11, a non-constexpr const static data member with an
14547 // in-class initializer cannot be volatile.
14548 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14549
14550 // We allow foldable floating-point constants as an extension.
14551 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14552 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14553 // it anyway and provide a fixit to add the 'constexpr'.
14554 if (getLangOpts().CPlusPlus11) {
14555 Diag(VDecl->getLocation(),
14556 diag::ext_in_class_initializer_float_type_cxx11)
14557 << DclT << Init->getSourceRange();
14558 Diag(VDecl->getBeginLoc(),
14559 diag::note_in_class_initializer_float_type_cxx11)
14560 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14561 } else {
14562 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14563 << DclT << Init->getSourceRange();
14564
14565 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14566 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14567 << Init->getSourceRange();
14568 VDecl->setInvalidDecl();
14569 }
14570 }
14571
14572 // Suggest adding 'constexpr' in C++11 for literal types.
14573 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14574 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14575 << DclT << Init->getSourceRange()
14576 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14577 VDecl->setConstexpr(true);
14578
14579 } else {
14580 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14581 << DclT << Init->getSourceRange();
14582 VDecl->setInvalidDecl();
14583 }
14584 } else if (VDecl->isFileVarDecl()) {
14585 // In C, extern is typically used to avoid tentative definitions when
14586 // declaring variables in headers, but adding an initializer makes it a
14587 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14588 // In C++, extern is often used to give implicitly static const variables
14589 // external linkage, so don't warn in that case. If selectany is present,
14590 // this might be header code intended for C and C++ inclusion, so apply the
14591 // C++ rules.
14592 if (VDecl->getStorageClass() == SC_Extern &&
14593 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14594 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14595 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14597 Diag(VDecl->getLocation(), diag::warn_extern_init);
14598
14599 // In Microsoft C++ mode, a const variable defined in namespace scope has
14600 // external linkage by default if the variable is declared with
14601 // __declspec(dllexport).
14602 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14604 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14605 VDecl->setStorageClass(SC_Extern);
14606
14607 // C99 6.7.8p4. All file scoped initializers need to be constant.
14608 // Avoid duplicate diagnostics for constexpr variables.
14609 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14610 !VDecl->isConstexpr())
14612 }
14613
14614 QualType InitType = Init->getType();
14615 if (!InitType.isNull() &&
14619
14620 // We will represent direct-initialization similarly to copy-initialization:
14621 // int x(1); -as-> int x = 1;
14622 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14623 //
14624 // Clients that want to distinguish between the two forms, can check for
14625 // direct initializer using VarDecl::getInitStyle().
14626 // A major benefit is that clients that don't particularly care about which
14627 // exactly form was it (like the CodeGen) can handle both cases without
14628 // special case code.
14629
14630 // C++ 8.5p11:
14631 // The form of initialization (using parentheses or '=') matters
14632 // when the entity being initialized has class type.
14633 if (InitializedFromParenListExpr) {
14634 assert(DirectInit && "Call-style initializer must be direct init.");
14635 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14637 } else if (DirectInit) {
14638 // This must be list-initialization. No other way is direct-initialization.
14640 }
14641
14642 if (LangOpts.OpenMP &&
14643 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14644 VDecl->isFileVarDecl())
14645 DeclsToCheckForDeferredDiags.insert(VDecl);
14647
14648 if (LangOpts.OpenACC && !InitType.isNull())
14649 OpenACC().ActOnVariableInit(VDecl, InitType);
14650}
14651
14653 // Our main concern here is re-establishing invariants like "a
14654 // variable's type is either dependent or complete".
14655 if (!D || D->isInvalidDecl()) return;
14656
14657 VarDecl *VD = dyn_cast<VarDecl>(D);
14658 if (!VD) return;
14659
14660 // Bindings are not usable if we can't make sense of the initializer.
14661 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14662 for (auto *BD : DD->bindings())
14663 BD->setInvalidDecl();
14664
14665 // Auto types are meaningless if we can't make sense of the initializer.
14666 if (VD->getType()->isUndeducedType()) {
14667 D->setInvalidDecl();
14668 return;
14669 }
14670
14671 QualType Ty = VD->getType();
14672 if (Ty->isDependentType()) return;
14673
14674 // Require a complete type.
14676 Context.getBaseElementType(Ty),
14677 diag::err_typecheck_decl_incomplete_type)) {
14678 VD->setInvalidDecl();
14679 return;
14680 }
14681
14682 // Require a non-abstract type.
14683 if (RequireNonAbstractType(VD->getLocation(), Ty,
14684 diag::err_abstract_type_in_decl,
14686 VD->setInvalidDecl();
14687 return;
14688 }
14689
14690 // Don't bother complaining about constructors or destructors,
14691 // though.
14692}
14693
14695 // If there is no declaration, there was an error parsing it. Just ignore it.
14696 if (!RealDecl)
14697 return;
14698
14699 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14700 QualType Type = Var->getType();
14701
14702 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14703 Diag(Var->getLocation(),
14704 diag::err_amdgcn_predicate_type_is_not_constructible)
14705 << Var;
14706 Var->setInvalidDecl();
14707 return;
14708 }
14709 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14710 if (isa<DecompositionDecl>(RealDecl)) {
14711 // Point the caret to the token immediately after the closing bracket if
14712 // it can be found; otherwise fall back to the declaration's location.
14713 SourceLocation Loc = Var->getLocation();
14714 SourceLocation RSquareLoc =
14715 dyn_cast<DecompositionDecl>(RealDecl)->getRSquareLoc();
14716 if (std::optional<Token> Next = Lexer::findNextToken(
14717 RSquareLoc, PP.getSourceManager(), PP.getLangOpts()))
14718 Loc = Next->getLocation();
14719 Diag(Loc, diag::err_decomp_decl_requires_init) << Var;
14720 Var->setInvalidDecl();
14721 return;
14722 }
14723
14724 if (Type->isUndeducedType() &&
14725 DeduceVariableDeclarationType(Var, false, nullptr))
14726 return;
14727
14728 this->CheckAttributesOnDeducedType(RealDecl);
14729
14730 // C++11 [class.static.data]p3: A static data member can be declared with
14731 // the constexpr specifier; if so, its declaration shall specify
14732 // a brace-or-equal-initializer.
14733 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14734 // the definition of a variable [...] or the declaration of a static data
14735 // member.
14736 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14737 !Var->isThisDeclarationADemotedDefinition()) {
14738 if (Var->isStaticDataMember()) {
14739 // C++1z removes the relevant rule; the in-class declaration is always
14740 // a definition there.
14741 if (!getLangOpts().CPlusPlus17 &&
14742 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14743 Diag(Var->getLocation(),
14744 diag::err_constexpr_static_mem_var_requires_init)
14745 << Var;
14746 Var->setInvalidDecl();
14747 return;
14748 }
14749 } else {
14750 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14751 Var->setInvalidDecl();
14752 return;
14753 }
14754 }
14755
14756 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14757 // be initialized.
14758 if (!Var->isInvalidDecl() &&
14759 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14760 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14761 bool HasConstExprDefaultConstructor = false;
14762 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14763 for (auto *Ctor : RD->ctors()) {
14764 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14765 Ctor->getMethodQualifiers().getAddressSpace() ==
14767 HasConstExprDefaultConstructor = true;
14768 }
14769 }
14770 }
14771 if (!HasConstExprDefaultConstructor) {
14772 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14773 Var->setInvalidDecl();
14774 return;
14775 }
14776 }
14777
14778 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14779 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14780 Diag(Var->getLocation(), diag::err_specialization_const);
14781 Var->setInvalidDecl();
14782 return;
14783 }
14784
14785 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14786 if (Var->getStorageClass() == SC_Extern) {
14787 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14788 << Var;
14789 Var->setInvalidDecl();
14790 return;
14791 }
14792 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14793 diag::err_typecheck_decl_incomplete_type)) {
14794 Var->setInvalidDecl();
14795 return;
14796 }
14797 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14798 if (!RD->hasTrivialDefaultConstructor()) {
14799 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14800 Var->setInvalidDecl();
14801 return;
14802 }
14803 }
14804 // The declaration is uninitialized, no need for further checks.
14805 return;
14806 }
14807
14808 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14809 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14810 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14811 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14813 NTCUK_Init);
14814
14815 switch (DefKind) {
14817 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14818 break;
14819
14820 // We have an out-of-line definition of a static data member
14821 // that has an in-class initializer, so we type-check this like
14822 // a declaration.
14823 //
14824 [[fallthrough]];
14825
14827 // It's only a declaration.
14828
14829 // Block scope. C99 6.7p7: If an identifier for an object is
14830 // declared with no linkage (C99 6.2.2p6), the type for the
14831 // object shall be complete.
14832 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14833 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14834 RequireCompleteType(Var->getLocation(), Type,
14835 diag::err_typecheck_decl_incomplete_type))
14836 Var->setInvalidDecl();
14837
14838 // Make sure that the type is not abstract.
14839 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14840 RequireNonAbstractType(Var->getLocation(), Type,
14841 diag::err_abstract_type_in_decl,
14843 Var->setInvalidDecl();
14844 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14845 Var->getStorageClass() == SC_PrivateExtern) {
14846 Diag(Var->getLocation(), diag::warn_private_extern);
14847 Diag(Var->getLocation(), diag::note_private_extern);
14848 }
14849
14850 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14851 !Var->isInvalidDecl())
14852 ExternalDeclarations.push_back(Var);
14853
14854 return;
14855
14857 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14858 // object that has file scope without an initializer, and without a
14859 // storage-class specifier or with the storage-class specifier "static",
14860 // constitutes a tentative definition. Note: A tentative definition with
14861 // external linkage is valid (C99 6.2.2p5).
14862 if (!Var->isInvalidDecl()) {
14863 if (const IncompleteArrayType *ArrayT
14864 = Context.getAsIncompleteArrayType(Type)) {
14866 Var->getLocation(), ArrayT->getElementType(),
14867 diag::err_array_incomplete_or_sizeless_type))
14868 Var->setInvalidDecl();
14869 }
14870 if (Var->getStorageClass() == SC_Static) {
14871 // C99 6.9.2p3: If the declaration of an identifier for an object is
14872 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14873 // declared type shall not be an incomplete type.
14874 // NOTE: code such as the following
14875 // static struct s;
14876 // struct s { int a; };
14877 // is accepted by gcc. Hence here we issue a warning instead of
14878 // an error and we do not invalidate the static declaration.
14879 // NOTE: to avoid multiple warnings, only check the first declaration.
14880 if (Var->isFirstDecl())
14881 RequireCompleteType(Var->getLocation(), Type,
14882 diag::ext_typecheck_decl_incomplete_type,
14883 Type->isArrayType());
14884 }
14885 }
14886
14887 // Record the tentative definition; we're done.
14888 if (!Var->isInvalidDecl())
14889 TentativeDefinitions.push_back(Var);
14890 return;
14891 }
14892
14893 // Provide a specific diagnostic for uninitialized variable definitions
14894 // with incomplete array type, unless it is a global unbounded HLSL resource
14895 // array.
14896 if (Type->isIncompleteArrayType() &&
14897 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14899 if (Var->isConstexpr())
14900 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14901 << Var;
14902 else
14903 Diag(Var->getLocation(),
14904 diag::err_typecheck_incomplete_array_needs_initializer);
14905 Var->setInvalidDecl();
14906 return;
14907 }
14908
14909 // Provide a specific diagnostic for uninitialized variable
14910 // definitions with reference type.
14911 if (Type->isReferenceType()) {
14912 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14913 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14914 return;
14915 }
14916
14917 // Do not attempt to type-check the default initializer for a
14918 // variable with dependent type.
14919 if (Type->isDependentType())
14920 return;
14921
14922 if (Var->isInvalidDecl())
14923 return;
14924
14925 if (!Var->hasAttr<AliasAttr>()) {
14926 if (RequireCompleteType(Var->getLocation(),
14927 Context.getBaseElementType(Type),
14928 diag::err_typecheck_decl_incomplete_type)) {
14929 Var->setInvalidDecl();
14930 return;
14931 }
14932 } else {
14933 return;
14934 }
14935
14936 // The variable can not have an abstract class type.
14937 if (RequireNonAbstractType(Var->getLocation(), Type,
14938 diag::err_abstract_type_in_decl,
14940 Var->setInvalidDecl();
14941 return;
14942 }
14943
14944 // In C, if the definition is const-qualified and has no initializer, it
14945 // is left uninitialized unless it has static or thread storage duration.
14946 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14947 unsigned DiagID = diag::warn_default_init_const_unsafe;
14948 if (Var->getStorageDuration() == SD_Static ||
14949 Var->getStorageDuration() == SD_Thread)
14950 DiagID = diag::warn_default_init_const;
14951
14952 bool EmitCppCompat = !Diags.isIgnored(
14953 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14954 Var->getLocation());
14955
14956 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14957 }
14958
14959 // Check for jumps past the implicit initializer. C++0x
14960 // clarifies that this applies to a "variable with automatic
14961 // storage duration", not a "local variable".
14962 // C++11 [stmt.dcl]p3
14963 // A program that jumps from a point where a variable with automatic
14964 // storage duration is not in scope to a point where it is in scope is
14965 // ill-formed unless the variable has scalar type, class type with a
14966 // trivial default constructor and a trivial destructor, a cv-qualified
14967 // version of one of these types, or an array of one of the preceding
14968 // types and is declared without an initializer.
14969 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14970 if (const auto *CXXRecord =
14971 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14972 // Mark the function (if we're in one) for further checking even if the
14973 // looser rules of C++11 do not require such checks, so that we can
14974 // diagnose incompatibilities with C++98.
14975 if (!CXXRecord->isPOD())
14977 }
14978 }
14979 // In OpenCL, we can't initialize objects in the __local address space,
14980 // even implicitly, so don't synthesize an implicit initializer.
14981 if (getLangOpts().OpenCL &&
14982 Var->getType().getAddressSpace() == LangAS::opencl_local)
14983 return;
14984
14985 // Handle HLSL uninitialized decls
14986 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14987 return;
14988
14989 // HLSL input & push-constant variables are expected to be externally
14990 // initialized, even when marked `static`.
14991 if (getLangOpts().HLSL &&
14992 hlsl::isInitializedByPipeline(Var->getType().getAddressSpace()))
14993 return;
14994
14995 // C++03 [dcl.init]p9:
14996 // If no initializer is specified for an object, and the
14997 // object is of (possibly cv-qualified) non-POD class type (or
14998 // array thereof), the object shall be default-initialized; if
14999 // the object is of const-qualified type, the underlying class
15000 // type shall have a user-declared default
15001 // constructor. Otherwise, if no initializer is specified for
15002 // a non- static object, the object and its subobjects, if
15003 // any, have an indeterminate initial value); if the object
15004 // or any of its subobjects are of const-qualified type, the
15005 // program is ill-formed.
15006 // C++0x [dcl.init]p11:
15007 // If no initializer is specified for an object, the object is
15008 // default-initialized; [...].
15011 = InitializationKind::CreateDefault(Var->getLocation());
15012
15013 InitializationSequence InitSeq(*this, Entity, Kind, {});
15014 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
15015
15016 if (Init.get()) {
15017 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
15018 // This is important for template substitution.
15019 Var->setInitStyle(VarDecl::CallInit);
15020 } else if (Init.isInvalid()) {
15021 // If default-init fails, attach a recovery-expr initializer to track
15022 // that initialization was attempted and failed.
15023 auto RecoveryExpr =
15024 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
15025 if (RecoveryExpr.get())
15026 Var->setInit(RecoveryExpr.get());
15027 }
15028
15030 }
15031}
15032
15033void Sema::ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt) {
15034 // If there is no declaration, there was an error parsing it. Ignore it.
15035 if (!D)
15036 return;
15037
15038 VarDecl *VD = dyn_cast<VarDecl>(D);
15039 if (!VD) {
15040 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var)
15041 << InExpansionStmt;
15042 D->setInvalidDecl();
15043 return;
15044 }
15045
15046 VD->setCXXForRangeDecl(true);
15047
15048 // for-range-declaration cannot be given a storage class specifier.
15049 int Error = -1;
15050 switch (VD->getStorageClass()) {
15051 case SC_None:
15052 break;
15053 case SC_Extern:
15054 Error = 0;
15055 break;
15056 case SC_Static:
15057 Error = 1;
15058 break;
15059 case SC_PrivateExtern:
15060 Error = 2;
15061 break;
15062 case SC_Auto:
15063 Error = 3;
15064 break;
15065 case SC_Register:
15066 Error = 4;
15067 break;
15068 }
15069
15070 // for-range-declaration cannot be given a storage class specifier con't.
15071 switch (VD->getTSCSpec()) {
15072 case TSCS_thread_local:
15073 Error = 6;
15074 break;
15075 case TSCS___thread:
15076 case TSCS__Thread_local:
15077 case TSCS_unspecified:
15078 break;
15079 }
15080
15081 if (Error != -1) {
15082 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
15083 << InExpansionStmt << VD << Error;
15084 D->setInvalidDecl();
15085 }
15086}
15087
15089 IdentifierInfo *Ident,
15090 ParsedAttributes &Attrs) {
15091 // C++1y [stmt.iter]p1:
15092 // A range-based for statement of the form
15093 // for ( for-range-identifier : for-range-initializer ) statement
15094 // is equivalent to
15095 // for ( auto&& for-range-identifier : for-range-initializer ) statement
15096 DeclSpec DS(Attrs.getPool().getFactory());
15097
15098 const char *PrevSpec;
15099 unsigned DiagID;
15100 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
15102
15104 D.SetIdentifier(Ident, IdentLoc);
15105 D.takeAttributesAppending(Attrs);
15106
15107 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
15108 IdentLoc);
15109 Decl *Var = ActOnDeclarator(S, D);
15110 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
15112 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
15113 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
15114 : IdentLoc);
15115}
15116
15119 return;
15120 auto *Attr = LifetimeBoundAttr::CreateImplicit(Context, MD->getLocation());
15121 QualType MethodType = MD->getType();
15122 QualType AttributedType =
15123 Context.getAttributedType(Attr, MethodType, MethodType);
15124 TypeLocBuilder TLB;
15125 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
15126 TLB.pushFullCopy(TSI->getTypeLoc());
15127 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(AttributedType);
15128 TyLoc.setAttr(Attr);
15129 MD->setType(AttributedType);
15130 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, AttributedType));
15131}
15132
15134 if (var->isInvalidDecl()) return;
15135
15137
15138 if (getLangOpts().OpenCL) {
15139 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
15140 // initialiser
15141 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
15142 !var->hasInit()) {
15143 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
15144 << 1 /*Init*/;
15145 var->setInvalidDecl();
15146 return;
15147 }
15148 }
15149
15150 // In Objective-C, don't allow jumps past the implicit initialization of a
15151 // local retaining variable.
15152 if (getLangOpts().ObjC &&
15153 var->hasLocalStorage()) {
15154 switch (var->getType().getObjCLifetime()) {
15158 break;
15159
15163 break;
15164 }
15165 }
15166
15167 if (var->hasLocalStorage() &&
15168 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
15170
15171 // Warn about externally-visible variables being defined without a
15172 // prior declaration. We only want to do this for global
15173 // declarations, but we also specifically need to avoid doing it for
15174 // class members because the linkage of an anonymous class can
15175 // change if it's later given a typedef name.
15176 if (var->isThisDeclarationADefinition() &&
15177 var->getDeclContext()->getRedeclContext()->isFileContext() &&
15178 var->isExternallyVisible() && var->hasLinkage() &&
15179 !var->isInline() && !var->getDescribedVarTemplate() &&
15180 var->getStorageClass() != SC_Register &&
15182 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
15183 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
15184 var->getLocation())) {
15185 // Find a previous declaration that's not a definition.
15186 VarDecl *prev = var->getPreviousDecl();
15187 while (prev && prev->isThisDeclarationADefinition())
15188 prev = prev->getPreviousDecl();
15189
15190 if (!prev) {
15191 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
15192 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
15193 << /* variable */ 0;
15194 }
15195 }
15196
15197 // Cache the result of checking for constant initialization.
15198 std::optional<bool> CacheHasConstInit;
15199 const Expr *CacheCulprit = nullptr;
15200 auto checkConstInit = [&]() mutable {
15201 const Expr *Init = var->getInit();
15202 if (Init->isInstantiationDependent())
15203 return true;
15204
15205 if (!CacheHasConstInit)
15206 CacheHasConstInit = var->getInit()->isConstantInitializer(
15207 Context, var->getType()->isReferenceType(), &CacheCulprit);
15208 return *CacheHasConstInit;
15209 };
15210
15211 if (var->getTLSKind() == VarDecl::TLS_Static) {
15212 if (var->getType().isDestructedType()) {
15213 // GNU C++98 edits for __thread, [basic.start.term]p3:
15214 // The type of an object with thread storage duration shall not
15215 // have a non-trivial destructor.
15216 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
15218 Diag(var->getLocation(), diag::note_use_thread_local);
15219 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
15220 if (!checkConstInit()) {
15221 // GNU C++98 edits for __thread, [basic.start.init]p4:
15222 // An object of thread storage duration shall not require dynamic
15223 // initialization.
15224 // FIXME: Need strict checking here.
15225 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
15226 << CacheCulprit->getSourceRange();
15228 Diag(var->getLocation(), diag::note_use_thread_local);
15229 }
15230 }
15231 }
15232
15233
15234 if (!var->getType()->isStructureType() && var->hasInit() &&
15235 isa<InitListExpr>(var->getInit())) {
15236 const auto *ILE = cast<InitListExpr>(var->getInit());
15237 unsigned NumInits = ILE->getNumInits();
15238 if (NumInits > 2)
15239 for (unsigned I = 0; I < NumInits; ++I) {
15240 const auto *Init = ILE->getInit(I);
15241 if (!Init)
15242 break;
15243 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15244 if (!SL)
15245 break;
15246
15247 unsigned NumConcat = SL->getNumConcatenated();
15248 // Diagnose missing comma in string array initialization.
15249 // Do not warn when all the elements in the initializer are concatenated
15250 // together. Do not warn for macros too.
15251 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15252 bool OnlyOneMissingComma = true;
15253 for (unsigned J = I + 1; J < NumInits; ++J) {
15254 const auto *Init = ILE->getInit(J);
15255 if (!Init)
15256 break;
15257 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15258 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15259 OnlyOneMissingComma = false;
15260 break;
15261 }
15262 }
15263
15264 if (OnlyOneMissingComma) {
15266 for (unsigned i = 0; i < NumConcat - 1; ++i)
15267 Hints.push_back(FixItHint::CreateInsertion(
15268 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
15269
15270 Diag(SL->getStrTokenLoc(1),
15271 diag::warn_concatenated_literal_array_init)
15272 << Hints;
15273 Diag(SL->getBeginLoc(),
15274 diag::note_concatenated_string_literal_silence);
15275 }
15276 // In any case, stop now.
15277 break;
15278 }
15279 }
15280 }
15281
15282
15283 QualType type = var->getType();
15284
15285 if (var->hasAttr<BlocksAttr>())
15287
15288 Expr *Init = var->getInit();
15289 bool GlobalStorage = var->hasGlobalStorage();
15290 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15291 QualType baseType = Context.getBaseElementType(type);
15292 bool HasConstInit = true;
15293
15294 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15295 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
15296 << var;
15297
15298 // Check whether the initializer is sufficiently constant.
15299 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15300 !type->isDependentType() && Init && !Init->isValueDependent() &&
15301 (GlobalStorage || var->isConstexpr() ||
15302 var->mightBeUsableInConstantExpressions(Context))) {
15303 // If this variable might have a constant initializer or might be usable in
15304 // constant expressions, check whether or not it actually is now. We can't
15305 // do this lazily, because the result might depend on things that change
15306 // later, such as which constexpr functions happen to be defined.
15308 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15309 // Prior to C++11, in contexts where a constant initializer is required,
15310 // the set of valid constant initializers is described by syntactic rules
15311 // in [expr.const]p2-6.
15312 // FIXME: Stricter checking for these rules would be useful for constinit /
15313 // -Wglobal-constructors.
15314 HasConstInit = checkConstInit();
15315
15316 // Compute and cache the constant value, and remember that we have a
15317 // constant initializer.
15318 if (HasConstInit) {
15319 if (var->isStaticDataMember() && !var->isInline() &&
15320 var->getLexicalDeclContext()->isRecord() &&
15321 type->isIntegralOrEnumerationType()) {
15322 // In C++98, in-class initialization for a static data member must
15323 // be an integer constant expression.
15324 if (!Init->isIntegerConstantExpr(Context)) {
15325 Diag(Init->getExprLoc(),
15326 diag::ext_in_class_initializer_non_constant)
15327 << Init->getSourceRange();
15328 }
15329 }
15330 (void)var->checkForConstantInitialization(Notes);
15331 Notes.clear();
15332 } else if (CacheCulprit) {
15333 Notes.emplace_back(CacheCulprit->getExprLoc(),
15334 PDiag(diag::note_invalid_subexpr_in_const_expr));
15335 Notes.back().second << CacheCulprit->getSourceRange();
15336 }
15337 } else {
15338 // Evaluate the initializer to see if it's a constant initializer.
15339 HasConstInit = var->checkForConstantInitialization(Notes);
15340 }
15341
15342 if (HasConstInit) {
15343 // FIXME: Consider replacing the initializer with a ConstantExpr.
15344 } else if (var->isConstexpr()) {
15345 SourceLocation DiagLoc = var->getLocation();
15346 // If the note doesn't add any useful information other than a source
15347 // location, fold it into the primary diagnostic.
15348 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15349 diag::note_invalid_subexpr_in_const_expr) {
15350 DiagLoc = Notes[0].first;
15351 Notes.clear();
15352 }
15353 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
15354 << var << Init->getSourceRange();
15355 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15356 Diag(Notes[I].first, Notes[I].second);
15357 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15358 auto *Attr = var->getAttr<ConstInitAttr>();
15359 Diag(var->getLocation(), diag::err_require_constant_init_failed)
15360 << Init->getSourceRange();
15361 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
15362 << Attr->getRange() << Attr->isConstinit();
15363 for (auto &it : Notes)
15364 Diag(it.first, it.second);
15365 } else if (var->isStaticDataMember() && !var->isInline() &&
15366 var->getLexicalDeclContext()->isRecord()) {
15367 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
15368 << Init->getSourceRange();
15369 for (auto &it : Notes)
15370 Diag(it.first, it.second);
15371 var->setInvalidDecl();
15372 } else if (IsGlobal &&
15373 !getDiagnostics().isIgnored(diag::warn_global_constructor,
15374 var->getLocation())) {
15375 // Warn about globals which don't have a constant initializer. Don't
15376 // warn about globals with a non-trivial destructor because we already
15377 // warned about them.
15378 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15379 if (!(RD && !RD->hasTrivialDestructor())) {
15380 // checkConstInit() here permits trivial default initialization even in
15381 // C++11 onwards, where such an initializer is not a constant initializer
15382 // but nonetheless doesn't require a global constructor.
15383 if (!checkConstInit())
15384 Diag(var->getLocation(), diag::warn_global_constructor)
15385 << Init->getSourceRange();
15386 }
15387 }
15388 }
15389
15390 // Apply section attributes and pragmas to global variables.
15391 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15393 PragmaStack<StringLiteral *> *Stack = nullptr;
15394 int SectionFlags = ASTContext::PSF_Read;
15395 bool MSVCEnv =
15396 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15397 std::optional<QualType::NonConstantStorageReason> Reason;
15398 if (HasConstInit &&
15399 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
15400 Stack = &ConstSegStack;
15401 } else {
15402 SectionFlags |= ASTContext::PSF_Write;
15403 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15404 }
15405 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15406 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15407 SectionFlags |= ASTContext::PSF_Implicit;
15408 UnifySection(SA->getName(), SectionFlags, var);
15409 } else if (Stack->CurrentValue) {
15410 if (Stack != &ConstSegStack && MSVCEnv &&
15411 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15412 var->getType().isConstQualified()) {
15413 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15414 NonConstNonReferenceType) &&
15415 "This case should've already been handled elsewhere");
15416 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15417 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15419 : *Reason);
15420 }
15421 SectionFlags |= ASTContext::PSF_Implicit;
15422 auto SectionName = Stack->CurrentValue->getString();
15423 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15424 Stack->CurrentPragmaLocation,
15425 SectionAttr::Declspec_allocate));
15426 if (UnifySection(SectionName, SectionFlags, var))
15427 var->dropAttr<SectionAttr>();
15428 }
15429
15430 // Apply the init_seg attribute if this has an initializer. If the
15431 // initializer turns out to not be dynamic, we'll end up ignoring this
15432 // attribute.
15433 if (CurInitSeg && var->getInit())
15434 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15435 CurInitSegLoc));
15436 }
15437
15438 // All the following checks are C++ only.
15439 if (!getLangOpts().CPlusPlus) {
15440 // If this variable must be emitted, add it as an initializer for the
15441 // current module.
15442 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15443 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15444 return;
15445 }
15446
15448
15449 // Require the destructor.
15450 if (!type->isDependentType())
15451 if (auto *RD = baseType->getAsCXXRecordDecl())
15453
15454 // If this variable must be emitted, add it as an initializer for the current
15455 // module. For named modules, discardable inline variables may be deferred
15456 // until they are odr-used. Non-inline variables that must be emitted,
15457 // including those with side-effecting initialization, must still be emitted
15458 // even if they have internal linkage.
15459 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) {
15460 GVALinkage Linkage = Context.GetGVALinkageForVariable(var);
15461 if (ModuleScopes.back().Module->isHeaderLikeModule() ||
15463 (Linkage == GVA_Internal && !var->isInline()))
15464 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15465 }
15466
15467 // Build the bindings if this is a structured binding declaration.
15468 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15470}
15471
15473 assert(VD->isStaticLocal());
15474
15475 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15476
15477 // Find outermost function when VD is in lambda function.
15478 while (FD && !getDLLAttr(FD) &&
15479 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15480 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15481 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15482 }
15483
15484 if (!FD)
15485 return;
15486
15487 // Static locals inherit dll attributes from their function.
15488 if (Attr *A = getDLLAttr(FD)) {
15489 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15490 NewAttr->setInherited(true);
15491 VD->addAttr(NewAttr);
15492 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15493 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15494 NewAttr->setInherited(true);
15495 VD->addAttr(NewAttr);
15496
15497 // Export this function to enforce exporting this static variable even
15498 // if it is not used in this compilation unit.
15499 if (!FD->hasAttr<DLLExportAttr>())
15500 FD->addAttr(NewAttr);
15501
15502 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15503 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15504 NewAttr->setInherited(true);
15505 VD->addAttr(NewAttr);
15506 }
15507}
15508
15510 assert(VD->getTLSKind());
15511
15512 // Perform TLS alignment check here after attributes attached to the variable
15513 // which may affect the alignment have been processed. Only perform the check
15514 // if the target has a maximum TLS alignment (zero means no constraints).
15515 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15516 // Protect the check so that it's not performed on dependent types and
15517 // dependent alignments (we can't determine the alignment in that case).
15518 if (!VD->hasDependentAlignment()) {
15519 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15520 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15521 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15522 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15523 << (unsigned)MaxAlignChars.getQuantity();
15524 }
15525 }
15526 }
15527}
15528
15530 // Note that we are no longer parsing the initializer for this declaration.
15531 ParsingInitForAutoVars.erase(ThisDecl);
15532
15533 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15534 if (!VD)
15535 return;
15536
15537 // Emit any deferred warnings for the variable's initializer, even if the
15538 // variable is invalid
15539 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15540
15541 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15543 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15544 if (PragmaClangBSSSection.Valid)
15545 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15546 Context, PragmaClangBSSSection.SectionName,
15547 PragmaClangBSSSection.PragmaLocation));
15548 if (PragmaClangDataSection.Valid)
15549 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15550 Context, PragmaClangDataSection.SectionName,
15551 PragmaClangDataSection.PragmaLocation));
15552 if (PragmaClangRodataSection.Valid)
15553 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15554 Context, PragmaClangRodataSection.SectionName,
15555 PragmaClangRodataSection.PragmaLocation));
15556 if (PragmaClangRelroSection.Valid)
15557 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15558 Context, PragmaClangRelroSection.SectionName,
15559 PragmaClangRelroSection.PragmaLocation));
15560 }
15561
15562 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15563 for (auto *BD : DD->bindings()) {
15565 }
15566 }
15567
15568 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15570
15571 checkAttributesAfterMerging(*this, *VD);
15572
15573 if (VD->isStaticLocal())
15575
15576 if (VD->getTLSKind())
15578
15579 // Perform check for initializers of device-side global variables.
15580 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15581 // 7.5). We must also apply the same checks to all __shared__
15582 // variables whether they are local or not. CUDA also allows
15583 // constant initializers for __constant__ and __device__ variables.
15584 if (getLangOpts().CUDA)
15586
15587 // Grab the dllimport or dllexport attribute off of the VarDecl.
15588 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15589
15590 // Imported static data members cannot be defined out-of-line.
15591 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15592 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15594 // We allow definitions of dllimport class template static data members
15595 // with a warning.
15598 bool IsClassTemplateMember =
15600 Context->getDescribedClassTemplate();
15601
15602 Diag(VD->getLocation(),
15603 IsClassTemplateMember
15604 ? diag::warn_attribute_dllimport_static_field_definition
15605 : diag::err_attribute_dllimport_static_field_definition);
15606 Diag(IA->getLocation(), diag::note_attribute);
15607 if (!IsClassTemplateMember)
15608 VD->setInvalidDecl();
15609 }
15610 }
15611
15612 // dllimport/dllexport variables cannot be thread local, their TLS index
15613 // isn't exported with the variable.
15614 if (DLLAttr && VD->getTLSKind()) {
15615 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15616 if (F && getDLLAttr(F)) {
15617 assert(VD->isStaticLocal());
15618 // But if this is a static local in a dlimport/dllexport function, the
15619 // function will never be inlined, which means the var would never be
15620 // imported, so having it marked import/export is safe.
15621 } else {
15622 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15623 << DLLAttr;
15624 VD->setInvalidDecl();
15625 }
15626 }
15627
15628 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15629 if (!Attr->isInherited() && !Attr->isImplicit() &&
15631 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15632 << Attr;
15633 VD->dropAttr<UsedAttr>();
15634 }
15635 }
15636 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15637 if (!Attr->isInherited() && !Attr->isImplicit() &&
15639 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15640 << Attr;
15641 VD->dropAttr<RetainAttr>();
15642 }
15643 }
15644
15645 const DeclContext *DC = VD->getDeclContext();
15646 // If there's a #pragma GCC visibility in scope, and this isn't a class
15647 // member, set the visibility of this variable.
15650
15651 // FIXME: Warn on unused var template partial specializations.
15654
15655 // Now we have parsed the initializer and can update the table of magic
15656 // tag values.
15657 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15659 return;
15660
15661 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15662 const Expr *MagicValueExpr = VD->getInit();
15663 if (!MagicValueExpr) {
15664 continue;
15665 }
15666 std::optional<llvm::APSInt> MagicValueInt;
15667 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15668 Diag(I->getRange().getBegin(),
15669 diag::err_type_tag_for_datatype_not_ice)
15670 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15671 continue;
15672 }
15673 if (MagicValueInt->getActiveBits() > 64) {
15674 Diag(I->getRange().getBegin(),
15675 diag::err_type_tag_for_datatype_too_large)
15676 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15677 continue;
15678 }
15679 uint64_t MagicValue = MagicValueInt->getZExtValue();
15680 RegisterTypeTagForDatatype(I->getArgumentKind(),
15681 MagicValue,
15682 I->getMatchingCType(),
15683 I->getLayoutCompatible(),
15684 I->getMustBeNull());
15685 }
15686}
15687
15689 auto *VD = dyn_cast<VarDecl>(DD);
15690 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15691}
15692
15694 ArrayRef<Decl *> Group) {
15696
15697 if (DS.isTypeSpecOwned())
15698 Decls.push_back(DS.getRepAsDecl());
15699
15700 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15701 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15702 bool DiagnosedMultipleDecomps = false;
15703 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15704 bool DiagnosedNonDeducedAuto = false;
15705
15706 for (Decl *D : Group) {
15707 if (!D)
15708 continue;
15709 // Check if the Decl has been declared in '#pragma omp declare target'
15710 // directive and has static storage duration.
15711 if (auto *VD = dyn_cast<VarDecl>(D);
15712 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15713 VD->hasGlobalStorage())
15715 // For declarators, there are some additional syntactic-ish checks we need
15716 // to perform.
15717 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15718 if (!FirstDeclaratorInGroup)
15719 FirstDeclaratorInGroup = DD;
15720 if (!FirstDecompDeclaratorInGroup)
15721 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15722 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15723 !hasDeducedAuto(DD))
15724 FirstNonDeducedAutoInGroup = DD;
15725
15726 if (FirstDeclaratorInGroup != DD) {
15727 // A decomposition declaration cannot be combined with any other
15728 // declaration in the same group.
15729 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15730 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15731 diag::err_decomp_decl_not_alone)
15732 << FirstDeclaratorInGroup->getSourceRange()
15733 << DD->getSourceRange();
15734 DiagnosedMultipleDecomps = true;
15735 }
15736
15737 // A declarator that uses 'auto' in any way other than to declare a
15738 // variable with a deduced type cannot be combined with any other
15739 // declarator in the same group.
15740 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15741 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15742 diag::err_auto_non_deduced_not_alone)
15743 << FirstNonDeducedAutoInGroup->getType()
15745 << FirstDeclaratorInGroup->getSourceRange()
15746 << DD->getSourceRange();
15747 DiagnosedNonDeducedAuto = true;
15748 }
15749 }
15750 }
15751
15752 Decls.push_back(D);
15753 }
15754
15756 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15757 handleTagNumbering(Tag, S);
15758 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15760 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15761 }
15762 }
15763
15764 return BuildDeclaratorGroup(Decls);
15765}
15766
15769 // C++14 [dcl.spec.auto]p7: (DR1347)
15770 // If the type that replaces the placeholder type is not the same in each
15771 // deduction, the program is ill-formed.
15772 if (Group.size() > 1) {
15774 VarDecl *DeducedDecl = nullptr;
15775 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15776 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15777 if (!D || D->isInvalidDecl())
15778 break;
15779 DeducedType *DT = D->getType()->getContainedDeducedType();
15780 if (!DT || DT->getDeducedType().isNull())
15781 continue;
15782 if (Deduced.isNull()) {
15783 Deduced = DT->getDeducedType();
15784 DeducedDecl = D;
15785 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15786 auto *AT = dyn_cast<AutoType>(DT);
15787 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15788 diag::err_auto_different_deductions)
15789 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15790 << DeducedDecl->getDeclName() << DT->getDeducedType()
15791 << D->getDeclName();
15792 if (DeducedDecl->hasInit())
15793 Dia << DeducedDecl->getInit()->getSourceRange();
15794 if (D->getInit())
15795 Dia << D->getInit()->getSourceRange();
15796 D->setInvalidDecl();
15797 break;
15798 }
15799 }
15800 }
15801
15803
15804 return DeclGroupPtrTy::make(
15805 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15806}
15807
15811
15813 // Don't parse the comment if Doxygen diagnostics are ignored.
15814 if (Group.empty() || !Group[0])
15815 return;
15816
15817 if (!areDocumentationDiagsEnabled(Group[0]->getLocation()))
15818 return;
15819
15820 if (Group.size() >= 2) {
15821 // This is a decl group. Normally it will contain only declarations
15822 // produced from declarator list. But in case we have any definitions or
15823 // additional declaration references:
15824 // 'typedef struct S {} S;'
15825 // 'typedef struct S *S;'
15826 // 'struct S *pS;'
15827 // FinalizeDeclaratorGroup adds these as separate declarations.
15828 Decl *MaybeTagDecl = Group[0];
15829 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15830 Group = Group.slice(1);
15831 }
15832 }
15833
15834 // FIXME: We assume every Decl in the group is in the same file.
15835 // This is false when preprocessor constructs the group from decls in
15836 // different files (e. g. macros or #include).
15837 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15838}
15839
15841 // Check that there are no default arguments inside the type of this
15842 // parameter.
15843 if (getLangOpts().CPlusPlus)
15845
15846 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15847 if (D.getCXXScopeSpec().isSet()) {
15848 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15849 << D.getCXXScopeSpec().getRange();
15850 }
15851
15852 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15853 // simple identifier except [...irrelevant cases...].
15854 switch (D.getName().getKind()) {
15856 break;
15857
15865 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15867 break;
15868
15871 // GetNameForDeclarator would not produce a useful name in this case.
15872 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15873 break;
15874 }
15875}
15876
15878 // This only matters in C.
15879 if (getLangOpts().CPlusPlus)
15880 return;
15881
15882 // This only matters if the declaration has a type.
15883 const auto *VD = dyn_cast<ValueDecl>(D);
15884 if (!VD)
15885 return;
15886
15887 // Get the type, this only matters for tag types.
15888 QualType QT = VD->getType();
15889 const auto *TD = QT->getAsTagDecl();
15890 if (!TD)
15891 return;
15892
15893 // Check if the tag declaration is lexically declared somewhere different
15894 // from the lexical declaration of the given object, then it will be hidden
15895 // in C++ and we should warn on it.
15896 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15897 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15898 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15899 Diag(TD->getLocation(), diag::note_declared_at);
15900 }
15901}
15902
15904 SourceLocation ExplicitThisLoc) {
15905 if (!ExplicitThisLoc.isValid())
15906 return;
15907 assert(S.getLangOpts().CPlusPlus &&
15908 "explicit parameter in non-cplusplus mode");
15909 if (!S.getLangOpts().CPlusPlus23)
15910 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15911 << P->getSourceRange();
15912
15913 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15914 // parameter pack.
15915 if (P->isParameterPack()) {
15916 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15917 << P->getSourceRange();
15918 return;
15919 }
15920 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15921 if (LambdaScopeInfo *LSI = S.getCurLambda())
15922 LSI->ExplicitObjectParameter = P;
15923}
15924
15926 SourceLocation ExplicitThisLoc) {
15927 const DeclSpec &DS = D.getDeclSpec();
15928
15929 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15930 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15931 // except for the special case of a single unnamed parameter of type void
15932 // with no storage class specifier, no type qualifier, and no following
15933 // ellipsis terminator.
15934 // Clang applies the C2y rules for 'register void' in all C language modes,
15935 // same as GCC, because it's questionable what that could possibly mean.
15936
15937 // C++03 [dcl.stc]p2 also permits 'auto'.
15938 StorageClass SC = SC_None;
15940 SC = SC_Register;
15941 // In C++11, the 'register' storage class specifier is deprecated.
15942 // In C++17, it is not allowed, but we tolerate it as an extension.
15943 if (getLangOpts().CPlusPlus11) {
15945 ? diag::ext_register_storage_class
15946 : diag::warn_deprecated_register)
15948 } else if (!getLangOpts().CPlusPlus &&
15950 D.getNumTypeObjects() == 0) {
15952 diag::err_invalid_storage_class_in_func_decl)
15955 }
15956 } else if (getLangOpts().CPlusPlus &&
15958 SC = SC_Auto;
15961 diag::err_invalid_storage_class_in_func_decl);
15963 }
15964
15966 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15968 if (DS.isInlineSpecified())
15969 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15970 << getLangOpts().CPlusPlus17;
15971 if (DS.hasConstexprSpecifier())
15972 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15973 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15974
15976
15978
15980 QualType parmDeclType = TInfo->getType();
15981
15982 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15983 const IdentifierInfo *II = D.getIdentifier();
15984 if (II) {
15987 LookupName(R, S);
15988 if (!R.empty()) {
15989 NamedDecl *PrevDecl = *R.begin();
15990 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15991 // Maybe we will complain about the shadowed template parameter.
15993 // Just pretend that we didn't see the previous declaration.
15994 PrevDecl = nullptr;
15995 }
15996 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15997 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15998 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15999 // Recover by removing the name
16000 II = nullptr;
16001 D.SetIdentifier(nullptr, D.getIdentifierLoc());
16002 D.setInvalidType(true);
16003 }
16004 }
16005 }
16006
16007 // Incomplete resource arrays are not allowed as function parameters in HLSL
16008 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType()) {
16009 QualType EltTy = Context.getBaseElementType(parmDeclType);
16010 // `isCompleteType` forces completion of the element type so the resource
16011 // check is valid.
16012 if (!EltTy->isDependentType() &&
16013 isCompleteType(D.getIdentifierLoc(), EltTy) &&
16014 parmDeclType->isHLSLResourceRecordArray()) {
16016 diag::err_hlsl_incomplete_resource_array_in_function_param);
16017 D.setInvalidType(true);
16018 }
16019 }
16020
16021 // Temporarily put parameter variables in the translation unit, not
16022 // the enclosing context. This prevents them from accidentally
16023 // looking like class members in C++.
16024 ParmVarDecl *New =
16025 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
16026 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
16027
16028 if (D.isInvalidType())
16029 New->setInvalidDecl();
16030
16031 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
16032
16033 assert(S->isFunctionPrototypeScope());
16034 assert(S->getFunctionPrototypeDepth() >= 1);
16035 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
16037
16039
16040 // Add the parameter declaration into this scope.
16041 S->AddDecl(New);
16042 if (II)
16043 IdResolver.AddDecl(New);
16044
16046
16048 Diag(New->getLocation(), diag::err_module_private_local)
16051
16052 if (New->hasAttr<BlocksAttr>())
16053 Diag(New->getLocation(), diag::err_block_not_allowed_on)
16054 << diag::NotAllowedBlockVarReason::NonlocalVariable;
16055
16056 New->deduceParmAddressSpace(Context);
16057
16058 return New;
16059}
16060
16062 SourceLocation Loc,
16063 QualType T) {
16064 /* FIXME: setting StartLoc == Loc.
16065 Would it be worth to modify callers so as to provide proper source
16066 location for the unnamed parameters, embedding the parameter's type? */
16067 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
16068 T, Context.getTrivialTypeSourceInfo(T, Loc),
16069 SC_None, nullptr);
16070 Param->setImplicit();
16071 return Param;
16072}
16073
16075 // Don't diagnose unused-parameter errors in template instantiations; we
16076 // will already have done so in the template itself.
16078 return;
16079
16080 for (const ParmVarDecl *Parameter : Parameters) {
16081 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
16082 !Parameter->hasAttr<UnusedAttr>() &&
16083 !Parameter->getIdentifier()->isPlaceholder()) {
16084 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
16085 << Parameter->getDeclName();
16086 }
16087 }
16088}
16089
16091 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
16092 if (LangOpts.NumLargeByValueCopy == 0) // No check.
16093 return;
16094
16095 // Warn if the return value is pass-by-value and larger than the specified
16096 // threshold.
16097 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
16098 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
16099 if (Size > LangOpts.NumLargeByValueCopy)
16100 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
16101 }
16102
16103 // Warn if any parameter is pass-by-value and larger than the specified
16104 // threshold.
16105 for (const ParmVarDecl *Parameter : Parameters) {
16106 QualType T = Parameter->getType();
16107 if (T->isDependentType() || !T.isPODType(Context))
16108 continue;
16109 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
16110 if (Size > LangOpts.NumLargeByValueCopy)
16111 Diag(Parameter->getLocation(), diag::warn_parameter_size)
16112 << Parameter << Size;
16113 }
16114}
16115
16117 SourceLocation NameLoc,
16118 const IdentifierInfo *Name, QualType T,
16119 TypeSourceInfo *TSInfo, StorageClass SC) {
16120 // In ARC, infer a lifetime qualifier for appropriate parameter types.
16121 if (getLangOpts().ObjCAutoRefCount &&
16122 T.getObjCLifetime() == Qualifiers::OCL_None &&
16123 T->isObjCLifetimeType()) {
16124
16125 Qualifiers::ObjCLifetime lifetime;
16126
16127 // Special cases for arrays:
16128 // - if it's const, use __unsafe_unretained
16129 // - otherwise, it's an error
16130 if (T->isArrayType()) {
16131 if (!T.isConstQualified()) {
16135 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
16136 else
16137 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
16138 << TSInfo->getTypeLoc().getSourceRange();
16139 }
16141 } else {
16142 lifetime = T->getObjCARCImplicitLifetime();
16143 }
16144 T = Context.getLifetimeQualifiedType(T, lifetime);
16145 }
16146
16147 if (getLangOpts().OpenCL) {
16148 assert(!isa<DecayedType>(T));
16149 if (T->isArrayType() && !T.hasAddressSpace()) {
16150 QualType ET = Context.getAsArrayType(T)->getElementType();
16151 if (!ET.hasAddressSpace()) {
16152 // Add the private address space to the contents of the pointer when a
16153 // pointer parameter is declared as an array and not declared.
16155 T = Context.getAddrSpaceQualType(T, ImplAS);
16156 T = QualType(Context.getAsArrayType(T), 0);
16157 }
16158 }
16159 }
16160
16161 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
16162 Context.getAdjustedParameterType(T),
16163 TSInfo, SC, nullptr);
16164
16165 // Make a note if we created a new pack in the scope of a lambda, so that
16166 // we know that references to that pack must also be expanded within the
16167 // lambda scope.
16168 if (New->isParameterPack())
16169 if (auto *CSI = getEnclosingLambdaOrBlock())
16170 CSI->LocalPacks.push_back(New);
16171
16172 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16173 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
16174 checkNonTrivialCUnion(New->getType(), New->getLocation(),
16177
16178 // Parameter declarators cannot be interface types. All ObjC objects are
16179 // passed by reference.
16180 if (T->isObjCObjectType()) {
16181 SourceLocation TypeEndLoc =
16183 Diag(NameLoc,
16184 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
16185 << FixItHint::CreateInsertion(TypeEndLoc, "*");
16186 T = Context.getObjCObjectPointerType(T);
16187 New->setType(T);
16188 }
16189
16190 // __ptrauth is forbidden on parameters.
16191 if (T.getPointerAuth()) {
16192 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
16193 New->setInvalidDecl();
16194 }
16195
16196 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
16197 // duration shall not be qualified by an address-space qualifier."
16198 // Since all parameters have automatic store duration, they can not have
16199 // an address space.
16200 if (T.getAddressSpace() != LangAS::Default &&
16201 // OpenCL allows function arguments declared to be an array of a type
16202 // to be qualified with an address space.
16203 !(getLangOpts().OpenCL &&
16204 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
16205 // WebAssembly allows reference types as parameters. Funcref in particular
16206 // lives in a different address space.
16207 !(T->isFunctionPointerType() &&
16208 T.getAddressSpace() == LangAS::wasm_funcref) &&
16209 // HLSL allows function arguments to be qualified with an address space
16210 // if the groupshared annotation is used.
16211 !(getLangOpts().HLSL &&
16212 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
16213 Diag(NameLoc, diag::err_arg_with_address_space);
16214 New->setInvalidDecl();
16215 }
16216
16217 // PPC MMA non-pointer types are not allowed as function argument types.
16218 if (Context.getTargetInfo().getTriple().isPPC64() &&
16219 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
16220 New->setInvalidDecl();
16221 }
16222
16223 return New;
16224}
16225
16227 SourceLocation LocAfterDecls) {
16229
16230 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
16231 // in the declaration list shall have at least one declarator, those
16232 // declarators shall only declare identifiers from the identifier list, and
16233 // every identifier in the identifier list shall be declared.
16234 //
16235 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
16236 // identifiers it names shall be declared in the declaration list."
16237 //
16238 // This is why we only diagnose in C99 and later. Note, the other conditions
16239 // listed are checked elsewhere.
16240 if (!FTI.hasPrototype) {
16241 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
16242 --i;
16243 if (FTI.Params[i].Param == nullptr) {
16244 if (getLangOpts().C99) {
16245 SmallString<256> Code;
16246 llvm::raw_svector_ostream(Code)
16247 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16248 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
16249 << FTI.Params[i].Ident
16250 << FixItHint::CreateInsertion(LocAfterDecls, Code);
16251 }
16252
16253 // Implicitly declare the argument as type 'int' for lack of a better
16254 // type.
16255 AttributeFactory attrs;
16256 DeclSpec DS(attrs);
16257 const char* PrevSpec; // unused
16258 unsigned DiagID; // unused
16259 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
16260 DiagID, Context.getPrintingPolicy());
16261 // Use the identifier location for the type source range.
16262 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16263 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16266 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
16267 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
16268 }
16269 }
16270 }
16271}
16272
16273Decl *
16275 MultiTemplateParamsArg TemplateParameterLists,
16276 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16277 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16278 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16279 Scope *ParentScope = FnBodyScope->getParent();
16280
16281 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16282 // we define a non-templated function definition, we will create a declaration
16283 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16284 // The base function declaration will have the equivalent of an `omp declare
16285 // variant` annotation which specifies the mangled definition as a
16286 // specialization function under the OpenMP context defined as part of the
16287 // `omp begin declare variant`.
16289 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16291 ParentScope, D, TemplateParameterLists, Bases);
16292
16294 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
16295 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
16296
16297 if (!Bases.empty())
16299 Bases);
16300
16301 return Dcl;
16302}
16303
16305 Consumer.HandleInlineFunctionDefinition(D);
16306}
16307
16309 const FunctionDecl *&PossiblePrototype) {
16310 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16311 Prev = Prev->getPreviousDecl()) {
16312 // Ignore any declarations that occur in function or method
16313 // scope, because they aren't visible from the header.
16314 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16315 continue;
16316
16317 PossiblePrototype = Prev;
16318 return Prev->getType()->isFunctionProtoType();
16319 }
16320 return false;
16321}
16322
16323static bool
16325 const FunctionDecl *&PossiblePrototype) {
16326 // Don't warn about invalid declarations.
16327 if (FD->isInvalidDecl())
16328 return false;
16329
16330 // Or declarations that aren't global.
16331 if (!FD->isGlobal())
16332 return false;
16333
16334 // Don't warn about C++ member functions.
16335 if (isa<CXXMethodDecl>(FD))
16336 return false;
16337
16338 // Don't warn about 'main'.
16340 if (IdentifierInfo *II = FD->getIdentifier())
16341 if (II->isStr("main") || II->isStr("efi_main"))
16342 return false;
16343
16344 if (FD->isMSVCRTEntryPoint())
16345 return false;
16346
16347 // Don't warn about inline functions.
16348 if (FD->isInlined())
16349 return false;
16350
16351 // Don't warn about function templates.
16353 return false;
16354
16355 // Don't warn about function template specializations.
16357 return false;
16358
16359 // Don't warn for OpenCL kernels.
16360 if (FD->hasAttr<DeviceKernelAttr>())
16361 return false;
16362
16363 // Don't warn on explicitly deleted functions.
16364 if (FD->isDeleted())
16365 return false;
16366
16367 // Don't warn on implicitly local functions (such as having local-typed
16368 // parameters).
16369 if (!FD->isExternallyVisible())
16370 return false;
16371
16372 // If we were able to find a potential prototype, don't warn.
16373 if (FindPossiblePrototype(FD, PossiblePrototype))
16374 return false;
16375
16376 return true;
16377}
16378
16379void
16381 const FunctionDecl *EffectiveDefinition,
16382 SkipBodyInfo *SkipBody) {
16383 const FunctionDecl *Definition = EffectiveDefinition;
16384 if (!Definition &&
16385 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16386 return;
16387
16388 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16389 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16390 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16391 // A merged copy of the same function, instantiated as a member of
16392 // the same class, is OK.
16393 if (declaresSameEntity(OrigFD, OrigDef) &&
16394 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
16396 return;
16397 }
16398 }
16399 }
16400
16402 return;
16403
16404 // Don't emit an error when this is redefinition of a typo-corrected
16405 // definition.
16407 return;
16408
16409 bool DefinitionVisible = false;
16410 if (SkipBody &&
16412 DefinitionVisible) &&
16413 (Definition->getFormalLinkage() == Linkage::Internal ||
16414 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16415 !Definition->getTemplateParameterLists().empty())) {
16416 SkipBody->ShouldSkip = true;
16417 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16418 if (!DefinitionVisible) {
16419 if (auto *TD = Definition->getDescribedFunctionTemplate())
16422 }
16423 return;
16424 }
16425
16426 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16427 Definition->getStorageClass() == SC_Extern)
16428 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
16429 << FD << getLangOpts().CPlusPlus;
16430 else
16431 Diag(FD->getLocation(), diag::err_redefinition) << FD;
16432
16433 Diag(Definition->getLocation(), diag::note_previous_definition);
16434 FD->setInvalidDecl();
16435}
16436
16438 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16439
16441 LSI->CallOperator = CallOperator;
16442 LSI->Lambda = LambdaClass;
16443 LSI->ReturnType = CallOperator->getReturnType();
16444 // When this function is called in situation where the context of the call
16445 // operator is not entered, we set AfterParameterList to false, so that
16446 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16447 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16448 // where we would set the CurContext to the lambda operator before
16449 // substituting into it. In this case the flag needs to be true such that
16450 // tryCaptureVariable can correctly handle potential captures thereof.
16451 LSI->AfterParameterList = CurContext == CallOperator;
16452 LSI->BeforeCompoundStatement = false;
16453
16454 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16455 // used at the point of dealing with potential captures.
16456 //
16457 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16458 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16459 // associated. (Technically, we could recover that list from their
16460 // instantiation patterns, but for now, the GLTemplateParameterList seems
16461 // unnecessary in these cases.)
16462 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16463 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16464 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16465
16466 if (LCD == LCD_None)
16468 else if (LCD == LCD_ByCopy)
16470 else if (LCD == LCD_ByRef)
16472 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16473
16475 LSI->Mutable = !CallOperator->isConst();
16476 if (CallOperator->isExplicitObjectMemberFunction())
16477 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16478
16479 // Add the captures to the LSI so they can be noted as already
16480 // captured within tryCaptureVar.
16481 auto I = LambdaClass->field_begin();
16482 for (const auto &C : LambdaClass->captures()) {
16483 if (C.capturesVariable()) {
16484 ValueDecl *VD = C.getCapturedVar();
16485 if (VD->isInitCapture())
16486 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16487 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16488 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16489 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16490 /*EllipsisLoc*/C.isPackExpansion()
16491 ? C.getEllipsisLoc() : SourceLocation(),
16492 I->getType(), /*Invalid*/false);
16493
16494 } else if (C.capturesThis()) {
16495 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16496 C.getCaptureKind() == LCK_StarThis);
16497 } else {
16498 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16499 I->getType());
16500 }
16501 ++I;
16502 }
16503 return LSI;
16504}
16505
16507 SkipBodyInfo *SkipBody,
16508 FnBodyKind BodyKind) {
16509 if (!D) {
16510 // Parsing the function declaration failed in some way. Push on a fake scope
16511 // anyway so we can try to parse the function body.
16514 return D;
16515 }
16516
16517 FunctionDecl *FD = nullptr;
16518
16519 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16520 FD = FunTmpl->getTemplatedDecl();
16521 else
16522 FD = cast<FunctionDecl>(D);
16523
16524 // Do not push if it is a lambda because one is already pushed when building
16525 // the lambda in ActOnStartOfLambdaDefinition().
16526 if (!isLambdaCallOperator(FD))
16528 FD);
16529
16530 // Check for defining attributes before the check for redefinition.
16531 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16532 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16533 FD->dropAttr<AliasAttr>();
16534 FD->setInvalidDecl();
16535 }
16536 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16537 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16538 FD->dropAttr<IFuncAttr>();
16539 FD->setInvalidDecl();
16540 }
16541 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16542 if (Context.getTargetInfo().getTriple().isAArch64() &&
16543 !Context.getTargetInfo().hasFeature("fmv") &&
16544 !Attr->isDefaultVersion()) {
16545 // If function multi versioning disabled skip parsing function body
16546 // defined with non-default target_version attribute
16547 if (SkipBody)
16548 SkipBody->ShouldSkip = true;
16549 return nullptr;
16550 }
16551 }
16552
16553 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16554 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16555 Ctor->isDefaultConstructor() &&
16556 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16557 // If this is an MS ABI dllexport default constructor, instantiate any
16558 // default arguments.
16559 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
16561 }
16562 }
16563
16564 // See if this is a redefinition. If 'will have body' (or similar) is already
16565 // set, then these checks were already performed when it was set.
16566 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16568 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16569
16570 // If we're skipping the body, we're done. Don't enter the scope.
16571 if (SkipBody && SkipBody->ShouldSkip)
16572 return D;
16573 }
16574
16575 // Mark this function as "will have a body eventually". This lets users to
16576 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16577 // this function.
16578 FD->setWillHaveBody();
16579
16580 // If we are instantiating a generic lambda call operator, push
16581 // a LambdaScopeInfo onto the function stack. But use the information
16582 // that's already been calculated (ActOnLambdaExpr) to prime the current
16583 // LambdaScopeInfo.
16584 // When the template operator is being specialized, the LambdaScopeInfo,
16585 // has to be properly restored so that tryCaptureVariable doesn't try
16586 // and capture any new variables. In addition when calculating potential
16587 // captures during transformation of nested lambdas, it is necessary to
16588 // have the LSI properly restored.
16590 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16591 // specialized.
16593 Diag(FD->getLocation(), diag::err_lambda_explicit_temp_spec)
16594 << /*specialization*/ 0;
16596 Diag(RD->getLocation(), diag::note_defined_here) << RD;
16597
16598 FD->setInvalidDecl();
16600 } else {
16601 assert(inTemplateInstantiation() &&
16602 "There should be an active template instantiation on the stack "
16603 "when instantiating a generic lambda!");
16605 }
16606 } else {
16607 // Enter a new function scope
16609 }
16610
16611 // Builtin functions cannot be defined.
16612 if (unsigned BuiltinID = FD->getBuiltinID()) {
16613 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16614 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16615 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16616 FD->setInvalidDecl();
16617 }
16618 }
16619
16620 // The return type of a function definition must be complete (C99 6.9.1p3).
16621 // C++23 [dcl.fct.def.general]/p2
16622 // The type of [...] the return for a function definition
16623 // shall not be a (possibly cv-qualified) class type that is incomplete
16624 // or abstract within the function body unless the function is deleted.
16625 QualType ResultType = FD->getReturnType();
16626 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16627 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16628 (RequireCompleteType(FD->getLocation(), ResultType,
16629 diag::err_func_def_incomplete_result) ||
16631 diag::err_abstract_type_in_decl,
16633 FD->setInvalidDecl();
16634
16635 if (FnBodyScope)
16636 PushDeclContext(FnBodyScope, FD);
16637
16638 // Check the validity of our function parameters
16639 if (BodyKind != FnBodyKind::Delete)
16641 /*CheckParameterNames=*/true);
16642
16643 // Add non-parameter declarations already in the function to the current
16644 // scope.
16645 if (FnBodyScope) {
16646 for (Decl *NPD : FD->decls()) {
16647 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16648 if (!NonParmDecl)
16649 continue;
16650 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16651 "parameters should not be in newly created FD yet");
16652
16653 // If the decl has a name, make it accessible in the current scope.
16654 if (NonParmDecl->getDeclName())
16655 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16656
16657 // Similarly, dive into enums and fish their constants out, making them
16658 // accessible in this scope.
16659 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16660 for (auto *EI : ED->enumerators())
16661 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16662 }
16663 }
16664 }
16665
16666 // Introduce our parameters into the function scope
16667 for (auto *Param : FD->parameters()) {
16668 Param->setOwningFunction(FD);
16669
16670 // If this has an identifier, add it to the scope stack.
16671 if (Param->getIdentifier() && FnBodyScope) {
16672 CheckShadow(FnBodyScope, Param);
16673
16674 PushOnScopeChains(Param, FnBodyScope);
16675 }
16676 }
16677
16678 // C++ [module.import/6]
16679 // ...
16680 // A header unit shall not contain a definition of a non-inline function or
16681 // variable whose name has external linkage.
16682 //
16683 // Deleted and Defaulted functions are implicitly inline (but the
16684 // inline state is not set at this point, so check the BodyKind explicitly).
16685 // We choose to allow weak & selectany definitions, as they are common in
16686 // headers, and have semantics similar to inline definitions which are allowed
16687 // in header units.
16688 // FIXME: Consider an alternate location for the test where the inlined()
16689 // state is complete.
16690 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16691 !FD->isInvalidDecl() && !FD->isInlined() &&
16692 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16693 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16694 !FD->isTemplateInstantiation() &&
16695 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16696 assert(FD->isThisDeclarationADefinition());
16697 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16698 FD->setInvalidDecl();
16699 }
16700
16701 // Ensure that the function's exception specification is instantiated.
16702 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16704
16705 // dllimport cannot be applied to non-inline function definitions.
16706 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16707 !FD->isTemplateInstantiation()) {
16708 assert(!FD->hasAttr<DLLExportAttr>());
16709 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16710 FD->setInvalidDecl();
16711 return D;
16712 }
16713
16714 // Some function attributes (like OptimizeNoneAttr) need actions before
16715 // parsing body started.
16717
16718 // We want to attach documentation to original Decl (which might be
16719 // a function template).
16721 if (getCurLexicalContext()->isObjCContainer() &&
16722 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16723 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16724 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16725
16727
16728 if (!FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16729 FnBodyScope) {
16730 // An implicit call expression is synthesized for functions declared with
16731 // the sycl_kernel_entry_point attribute. The call may resolve to a
16732 // function template, a member function template, or a call operator
16733 // of a variable template depending on the results of unqualified lookup
16734 // for 'sycl_kernel_launch' from the beginning of the function body.
16735 // Performing that lookup requires the stack of parsing scopes active
16736 // when the definition is parsed and is thus done here; the result is
16737 // cached in FunctionScopeInfo and used to synthesize the (possibly
16738 // unresolved) call expression after the function body has been parsed.
16739 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16740 if (!SKEPAttr->isInvalidAttr()) {
16741 ExprResult LaunchIdExpr =
16742 SYCL().BuildSYCLKernelLaunchIdExpr(FD, SKEPAttr->getKernelName());
16743 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16744 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16745 // treated as an error in the definition of 'FD'; treating it as an error
16746 // of the declaration would affect overload resolution which would
16747 // potentially result in additional errors. If construction of
16748 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16749 // a null pointer value below; that is expected.
16750 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16751 }
16752 }
16753
16754 return D;
16755}
16756
16758 if (!FD || FD->isInvalidDecl())
16759 return;
16760 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16761 FD = TD->getTemplatedDecl();
16762 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16765 CurFPFeatures.applyChanges(FPO);
16766 FpPragmaStack.CurrentValue =
16767 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16768 }
16769}
16770
16772 ReturnStmt **Returns = Scope->Returns.data();
16773
16774 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16775 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16776 if (!NRVOCandidate->isNRVOVariable()) {
16777 Diag(Returns[I]->getRetValue()->getExprLoc(),
16778 diag::warn_not_eliding_copy_on_return);
16779 Returns[I]->setNRVOCandidate(nullptr);
16780 }
16781 }
16782 }
16783}
16784
16786 // We can't delay parsing the body of a constexpr function template (yet).
16788 return false;
16789
16790 // We can't delay parsing the body of a function template with a deduced
16791 // return type (yet).
16792 if (D.getDeclSpec().hasAutoTypeSpec()) {
16793 // If the placeholder introduces a non-deduced trailing return type,
16794 // we can still delay parsing it.
16795 if (D.getNumTypeObjects()) {
16796 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16797 if (Outer.Kind == DeclaratorChunk::Function &&
16798 Outer.Fun.hasTrailingReturnType()) {
16799 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16800 return Ty.isNull() || !Ty->isUndeducedType();
16801 }
16802 }
16803 return false;
16804 }
16805
16806 return true;
16807}
16808
16810 // We cannot skip the body of a function (or function template) which is
16811 // constexpr, since we may need to evaluate its body in order to parse the
16812 // rest of the file.
16813 // We cannot skip the body of a function with an undeduced return type,
16814 // because any callers of that function need to know the type.
16815 if (const FunctionDecl *FD = D->getAsFunction()) {
16816 if (FD->isConstexpr())
16817 return false;
16818 // We can't simply call Type::isUndeducedType here, because inside template
16819 // auto can be deduced to a dependent type, which is not considered
16820 // "undeduced".
16821 if (FD->getReturnType()->getContainedDeducedType())
16822 return false;
16823 }
16824 return Consumer.shouldSkipFunctionBody(D);
16825}
16826
16828 if (!Decl)
16829 return nullptr;
16830 if (FunctionDecl *FD = Decl->getAsFunction())
16831 FD->setHasSkippedBody();
16832 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16833 MD->setHasSkippedBody();
16834 return Decl;
16835}
16836
16837/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16838/// body.
16840public:
16841 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16843 if (!IsLambda)
16844 S.PopExpressionEvaluationContext();
16845 }
16846
16847private:
16848 Sema &S;
16849 bool IsLambda = false;
16850};
16851
16853 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16854
16855 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16856 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16857 if (!Inserted)
16858 return It->second;
16859
16860 bool R = false;
16861 const BlockDecl *CurBD = BD;
16862
16863 do {
16864 R = !CurBD->doesNotEscape();
16865 if (R)
16866 break;
16867 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16868 } while (CurBD);
16869
16870 return It->second = R;
16871 };
16872
16873 // If the location where 'self' is implicitly retained is inside a escaping
16874 // block, emit a diagnostic.
16875 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16877 if (IsOrNestedInEscapingBlock(P.second))
16878 S.Diag(P.first, diag::warn_implicitly_retains_self)
16879 << FixItHint::CreateInsertion(P.first, "self->");
16880}
16881
16882static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16883 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16884 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16885}
16886
16888 return methodHasName(FD, "get_return_object");
16889}
16890
16892 return FD->isStatic() &&
16893 methodHasName(FD, "get_return_object_on_allocation_failure");
16894}
16895
16898 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16899 return;
16900 // Allow some_promise_type::get_return_object().
16902 return;
16903 if (!FD->hasAttr<CoroWrapperAttr>())
16904 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16905}
16906
16907Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16908 bool RetainFunctionScopeInfo) {
16910 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16911
16912 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16913 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16914
16915 SourceLocation AnalysisLoc;
16916 if (Body)
16917 AnalysisLoc = Body->getEndLoc();
16918 else if (FD)
16919 AnalysisLoc = FD->getEndLoc();
16921 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16922 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16923
16924 // If we skip function body, we can't tell if a function is a coroutine.
16925 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16926 if (FSI->isCoroutine())
16928 else
16930 }
16931
16932 // Diagnose invalid SYCL kernel entry point function declarations
16933 // and build SYCLKernelCallStmts for valid ones.
16934 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16935 SYCLKernelEntryPointAttr *SKEPAttr =
16936 FD->getAttr<SYCLKernelEntryPointAttr>();
16937 if (FD->isDefaulted()) {
16938 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16939 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16940 SKEPAttr->setInvalidAttr();
16941 } else if (FD->isDeleted()) {
16942 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16943 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16944 SKEPAttr->setInvalidAttr();
16945 } else if (FSI->isCoroutine()) {
16946 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16947 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16948 SKEPAttr->setInvalidAttr();
16949 } else if (Body && isa<CXXTryStmt>(Body)) {
16950 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16951 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16952 SKEPAttr->setInvalidAttr();
16953 }
16954
16955 // Build an unresolved SYCL kernel call statement for a function template,
16956 // validate that a SYCL kernel call statement was instantiated for an
16957 // (implicit or explicit) instantiation of a function template, or otherwise
16958 // build a (resolved) SYCL kernel call statement for a non-templated
16959 // function or an explicit specialization.
16960 if (Body && !SKEPAttr->isInvalidAttr()) {
16961 StmtResult SR;
16962 if (FD->isTemplateInstantiation()) {
16963 // The function body should already be a SYCLKernelCallStmt in this
16964 // case, but might not be if there were previous errors.
16965 SR = Body;
16966 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16967 // If name lookup for a template named sycl_kernel_launch failed
16968 // earlier, don't try to build a SYCL kernel call statement as that
16969 // would cause additional errors to be issued; just proceed with the
16970 // original function body.
16971 SR = Body;
16972 } else if (FD->isTemplated()) {
16974 cast<CompoundStmt>(Body), getCurFunction()->SYCLKernelLaunchIdExpr);
16975 } else {
16977 FD, cast<CompoundStmt>(Body),
16978 getCurFunction()->SYCLKernelLaunchIdExpr);
16979 }
16980 // If construction of the replacement body fails, just continue with the
16981 // original function body. An early error return here is not valid; the
16982 // current declaration context and function scopes must be popped before
16983 // returning.
16984 if (SR.isUsable())
16985 Body = SR.get();
16986 }
16987 }
16988
16989 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16990 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16991 if (FD->isDeletedAsWritten())
16992 Diag(SEAttr->getLocation(),
16993 diag::err_sycl_external_invalid_deleted_function)
16994 << SEAttr;
16995 }
16996
16997 {
16998 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16999 // one is already popped when finishing the lambda in BuildLambdaExpr().
17000 // This is meant to pop the context added in ActOnStartOfFunctionDef().
17001 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
17002 if (FD) {
17003 // The function body and the DefaultedOrDeletedInfo, if present, use
17004 // the same storage; don't overwrite the latter if the former is null
17005 // (the body is initialised to null anyway, so even if the latter isn't
17006 // present, this would still be a no-op).
17007 if (Body)
17008 FD->setBody(Body);
17009 FD->setWillHaveBody(false);
17010
17011 if (getLangOpts().CPlusPlus14) {
17012 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
17013 FD->getReturnType()->isUndeducedType()) {
17014 // For a function with a deduced result type to return void,
17015 // the result type as written must be 'auto' or 'decltype(auto)',
17016 // possibly cv-qualified or constrained, but not ref-qualified.
17017 if (!FD->getReturnType()->getAs<AutoType>()) {
17018 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
17019 << FD->getReturnType();
17020 FD->setInvalidDecl();
17021 } else {
17022 // Falling off the end of the function is the same as 'return;'.
17023 Expr *Dummy = nullptr;
17025 FD, dcl->getLocation(), Dummy,
17026 FD->getReturnType()->getAs<AutoType>()))
17027 FD->setInvalidDecl();
17028 }
17029 }
17030 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
17031 // In C++11, we don't use 'auto' deduction rules for lambda call
17032 // operators because we don't support return type deduction.
17033 auto *LSI = getCurLambda();
17034 if (LSI->HasImplicitReturnType) {
17036
17037 // C++11 [expr.prim.lambda]p4:
17038 // [...] if there are no return statements in the compound-statement
17039 // [the deduced type is] the type void
17040 QualType RetType =
17041 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
17042
17043 // Update the return type to the deduced type.
17044 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
17045 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
17046 Proto->getExtProtoInfo()));
17047 }
17048 }
17049
17050 // If the function implicitly returns zero (like 'main') or is naked,
17051 // don't complain about missing return statements.
17052 // Clang implicitly returns 0 in C89 mode, but that's considered an
17053 // extension. The check is necessary to ensure the expected extension
17054 // warning is emitted in C89 mode.
17055 if ((FD->hasImplicitReturnZero() &&
17056 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
17057 FD->hasAttr<NakedAttr>())
17059
17060 // MSVC permits the use of pure specifier (=0) on function definition,
17061 // defined at class scope, warn about this non-standard construct.
17062 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
17063 !FD->isOutOfLine())
17064 Diag(FD->getLocation(), diag::ext_pure_function_definition);
17065
17066 if (!FD->isInvalidDecl()) {
17067 // Don't diagnose unused parameters of defaulted, deleted or naked
17068 // functions.
17069 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
17070 !FD->hasAttr<NakedAttr>())
17073 FD->getReturnType(), FD);
17074
17075 // If this is a structor, we need a vtable.
17076 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
17077 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
17078 else if (CXXDestructorDecl *Destructor =
17079 dyn_cast<CXXDestructorDecl>(FD))
17080 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
17081
17082 // Try to apply the named return value optimization. We have to check
17083 // if we can do this here because lambdas keep return statements around
17084 // to deduce an implicit return type.
17085 if (FD->getReturnType()->isRecordType() &&
17087 computeNRVO(Body, FSI);
17088 }
17089
17090 // GNU warning -Wmissing-prototypes:
17091 // Warn if a global function is defined without a previous
17092 // prototype declaration. This warning is issued even if the
17093 // definition itself provides a prototype. The aim is to detect
17094 // global functions that fail to be declared in header files.
17095 const FunctionDecl *PossiblePrototype = nullptr;
17096 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
17097 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
17098
17099 if (PossiblePrototype) {
17100 // We found a declaration that is not a prototype,
17101 // but that could be a zero-parameter prototype
17102 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
17103 TypeLoc TL = TI->getTypeLoc();
17105 Diag(PossiblePrototype->getLocation(),
17106 diag::note_declaration_not_a_prototype)
17107 << (FD->getNumParams() != 0)
17109 FTL.getRParenLoc(), "void")
17110 : FixItHint{});
17111 }
17112 } else {
17113 // Returns true if the token beginning at this Loc is `const`.
17114 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
17115 const LangOptions &LangOpts) {
17116 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
17117 if (LocInfo.first.isInvalid())
17118 return false;
17119
17120 bool Invalid = false;
17121 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
17122 if (Invalid)
17123 return false;
17124
17125 if (LocInfo.second > Buffer.size())
17126 return false;
17127
17128 const char *LexStart = Buffer.data() + LocInfo.second;
17129 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
17130
17131 return StartTok.consume_front("const") &&
17132 (StartTok.empty() || isWhitespace(StartTok[0]) ||
17133 StartTok.starts_with("/*") || StartTok.starts_with("//"));
17134 };
17135
17136 auto findBeginLoc = [&]() {
17137 // If the return type has `const` qualifier, we want to insert
17138 // `static` before `const` (and not before the typename).
17139 if ((FD->getReturnType()->isAnyPointerType() &&
17142 // But only do this if we can determine where the `const` is.
17143
17144 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
17145 getLangOpts()))
17146
17147 return FD->getBeginLoc();
17148 }
17149 return FD->getTypeSpecStartLoc();
17150 };
17152 diag::note_static_for_internal_linkage)
17153 << /* function */ 1
17154 << (FD->getStorageClass() == SC_None
17155 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
17156 : FixItHint{});
17157 }
17158 }
17159
17160 // We might not have found a prototype because we didn't wish to warn on
17161 // the lack of a missing prototype. Try again without the checks for
17162 // whether we want to warn on the missing prototype.
17163 if (!PossiblePrototype)
17164 (void)FindPossiblePrototype(FD, PossiblePrototype);
17165
17166 // If the function being defined does not have a prototype, then we may
17167 // need to diagnose it as changing behavior in C23 because we now know
17168 // whether the function accepts arguments or not. This only handles the
17169 // case where the definition has no prototype but does have parameters
17170 // and either there is no previous potential prototype, or the previous
17171 // potential prototype also has no actual prototype. This handles cases
17172 // like:
17173 // void f(); void f(a) int a; {}
17174 // void g(a) int a; {}
17175 // See MergeFunctionDecl() for other cases of the behavior change
17176 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
17177 // type without a prototype.
17178 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
17179 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
17180 !PossiblePrototype->isImplicit()))) {
17181 // The function definition has parameters, so this will change behavior
17182 // in C23. If there is a possible prototype, it comes before the
17183 // function definition.
17184 // FIXME: The declaration may have already been diagnosed as being
17185 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
17186 // there's no way to test for the "changes behavior" condition in
17187 // SemaType.cpp when forming the declaration's function type. So, we do
17188 // this awkward dance instead.
17189 //
17190 // If we have a possible prototype and it declares a function with a
17191 // prototype, we don't want to diagnose it; if we have a possible
17192 // prototype and it has no prototype, it may have already been
17193 // diagnosed in SemaType.cpp as deprecated depending on whether
17194 // -Wstrict-prototypes is enabled. If we already warned about it being
17195 // deprecated, add a note that it also changes behavior. If we didn't
17196 // warn about it being deprecated (because the diagnostic is not
17197 // enabled), warn now that it is deprecated and changes behavior.
17198
17199 // This K&R C function definition definitely changes behavior in C23,
17200 // so diagnose it.
17201 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
17202 << /*definition*/ 1 << /* not supported in C23 */ 0;
17203
17204 // If we have a possible prototype for the function which is a user-
17205 // visible declaration, we already tested that it has no prototype.
17206 // This will change behavior in C23. This gets a warning rather than a
17207 // note because it's the same behavior-changing problem as with the
17208 // definition.
17209 if (PossiblePrototype)
17210 Diag(PossiblePrototype->getLocation(),
17211 diag::warn_non_prototype_changes_behavior)
17212 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
17213 << /*definition*/ 1;
17214 }
17215
17216 // Warn on CPUDispatch with an actual body.
17217 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
17218 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
17219 if (!CmpndBody->body_empty())
17220 Diag(CmpndBody->body_front()->getBeginLoc(),
17221 diag::warn_dispatch_body_ignored);
17222
17223 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
17224 const CXXMethodDecl *KeyFunction;
17225 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
17226 MD->isVirtual() &&
17227 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
17228 MD == KeyFunction->getCanonicalDecl()) {
17229 // Update the key-function state if necessary for this ABI.
17230 if (FD->isInlined() &&
17231 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
17232 Context.setNonKeyFunction(MD);
17233
17234 // If the newly-chosen key function is already defined, then we
17235 // need to mark the vtable as used retroactively.
17236 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
17237 const FunctionDecl *Definition;
17238 if (KeyFunction && KeyFunction->isDefined(Definition))
17239 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
17240 } else {
17241 // We just defined they key function; mark the vtable as used.
17242 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
17243 }
17244 }
17245 }
17246
17247 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
17248 "Function parsing confused");
17249 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
17250 assert(MD == getCurMethodDecl() && "Method parsing confused");
17251 MD->setBody(Body);
17252 if (!MD->isInvalidDecl()) {
17254 MD->getReturnType(), MD);
17255
17256 if (Body)
17257 computeNRVO(Body, FSI);
17258 }
17259 if (FSI->ObjCShouldCallSuper) {
17260 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
17261 << MD->getSelector().getAsString();
17262 FSI->ObjCShouldCallSuper = false;
17263 }
17265 const ObjCMethodDecl *InitMethod = nullptr;
17266 bool isDesignated =
17267 MD->isDesignatedInitializerForTheInterface(&InitMethod);
17268 assert(isDesignated && InitMethod);
17269 (void)isDesignated;
17270
17271 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17272 auto IFace = MD->getClassInterface();
17273 if (!IFace)
17274 return false;
17275 auto SuperD = IFace->getSuperClass();
17276 if (!SuperD)
17277 return false;
17278 return SuperD->getIdentifier() ==
17279 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
17280 };
17281 // Don't issue this warning for unavailable inits or direct subclasses
17282 // of NSObject.
17283 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17284 Diag(MD->getLocation(),
17285 diag::warn_objc_designated_init_missing_super_call);
17286 Diag(InitMethod->getLocation(),
17287 diag::note_objc_designated_init_marked_here);
17288 }
17290 }
17291 if (FSI->ObjCWarnForNoInitDelegation) {
17292 // Don't issue this warning for unavailable inits.
17293 if (!MD->isUnavailable())
17294 Diag(MD->getLocation(),
17295 diag::warn_objc_secondary_init_missing_init_call);
17296 FSI->ObjCWarnForNoInitDelegation = false;
17297 }
17298
17300 } else {
17301 // Parsing the function declaration failed in some way. Pop the fake scope
17302 // we pushed on.
17303 PopFunctionScopeInfo(ActivePolicy, dcl);
17304 return nullptr;
17305 }
17306
17307 if (Body) {
17310 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17312 }
17313
17314 assert(!FSI->ObjCShouldCallSuper &&
17315 "This should only be set for ObjC methods, which should have been "
17316 "handled in the block above.");
17317
17318 // Verify and clean out per-function state.
17319 if (Body && (!FD || !FD->isDefaulted())) {
17320 // C++ constructors that have function-try-blocks can't have return
17321 // statements in the handlers of that block. (C++ [except.handle]p14)
17322 // Verify this.
17323 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
17325
17326 // Verify that gotos and switch cases don't jump into scopes illegally.
17327 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17329
17330 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
17331 if (!Destructor->getParent()->isDependentType())
17333
17335 Destructor->getParent());
17336 }
17337
17338 // If any errors have occurred, clear out any temporaries that may have
17339 // been leftover. This ensures that these temporaries won't be picked up
17340 // for deletion in some later function.
17343 getDiagnostics().getSuppressAllDiagnostics()) {
17345 }
17347 // Since the body is valid, issue any analysis-based warnings that are
17348 // enabled.
17349 ActivePolicy = &WP;
17350 }
17351
17352 if (!IsInstantiation && FD &&
17353 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17354 !FD->isInvalidDecl() &&
17356 FD->setInvalidDecl();
17357
17358 if (FD && FD->hasAttr<NakedAttr>()) {
17359 for (const Stmt *S : Body->children()) {
17360 // Allow local register variables without initializer as they don't
17361 // require prologue.
17362 bool RegisterVariables = false;
17363 if (auto *DS = dyn_cast<DeclStmt>(S)) {
17364 for (const auto *Decl : DS->decls()) {
17365 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
17366 RegisterVariables =
17367 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17368 if (!RegisterVariables)
17369 break;
17370 }
17371 }
17372 }
17373 if (RegisterVariables)
17374 continue;
17375 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
17376 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
17377 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
17378 FD->setInvalidDecl();
17379 break;
17380 }
17381 }
17382 }
17383
17384 assert(ExprCleanupObjects.size() ==
17385 ExprEvalContexts.back().NumCleanupObjects &&
17386 "Leftover temporaries in function");
17387 assert(!Cleanup.exprNeedsCleanups() &&
17388 "Unaccounted cleanups in function");
17389 assert(MaybeODRUseExprs.empty() &&
17390 "Leftover expressions for odr-use checking");
17391 }
17392 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17393 // the declaration context below. Otherwise, we're unable to transform
17394 // 'this' expressions when transforming immediate context functions.
17395
17396 if (FD)
17398
17399 if (!IsInstantiation)
17401
17402 if (!RetainFunctionScopeInfo)
17403 PopFunctionScopeInfo(ActivePolicy, dcl);
17404 // If any errors have occurred, clear out any temporaries that may have
17405 // been leftover. This ensures that these temporaries won't be picked up for
17406 // deletion in some later function.
17409 }
17410
17411 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17412 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17413 auto ES = getEmissionStatus(FD);
17417 }
17418
17419 if (FD && !FD->isDeleted())
17420 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
17421
17422 return dcl;
17423}
17424
17425/// When we finish delayed parsing of an attribute, we must attach it to the
17426/// relevant Decl.
17428 ParsedAttributes &Attrs) {
17429 // Always attach attributes to the underlying decl.
17430 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
17431 D = TD->getTemplatedDecl();
17432 ProcessDeclAttributeList(S, D, Attrs);
17433 ProcessAPINotes(D);
17434
17435 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
17436 if (Method->isStatic())
17438}
17439
17441 IdentifierInfo &II, Scope *S) {
17442 // It is not valid to implicitly define a function in C23.
17443 assert(LangOpts.implicitFunctionsAllowed() &&
17444 "Implicit function declarations aren't allowed in this language mode");
17445
17446 // Find the scope in which the identifier is injected and the corresponding
17447 // DeclContext.
17448 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17449 // In that case, we inject the declaration into the translation unit scope
17450 // instead.
17451 Scope *BlockScope = S;
17452 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17453 BlockScope = BlockScope->getParent();
17454
17455 // Loop until we find a DeclContext that is either a function/method or the
17456 // translation unit, which are the only two valid places to implicitly define
17457 // a function. This avoids accidentally defining the function within a tag
17458 // declaration, for example.
17459 Scope *ContextScope = BlockScope;
17460 while (!ContextScope->getEntity() ||
17461 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17462 !ContextScope->getEntity()->isTranslationUnit()))
17463 ContextScope = ContextScope->getParent();
17464 ContextRAII SavedContext(*this, ContextScope->getEntity());
17465
17466 // Before we produce a declaration for an implicitly defined
17467 // function, see whether there was a locally-scoped declaration of
17468 // this name as a function or variable. If so, use that
17469 // (non-visible) declaration, and complain about it.
17470 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
17471 if (ExternCPrev) {
17472 // We still need to inject the function into the enclosing block scope so
17473 // that later (non-call) uses can see it.
17474 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
17475
17476 // C89 footnote 38:
17477 // If in fact it is not defined as having type "function returning int",
17478 // the behavior is undefined.
17479 if (!isa<FunctionDecl>(ExternCPrev) ||
17480 !Context.typesAreCompatible(
17481 cast<FunctionDecl>(ExternCPrev)->getType(),
17482 Context.getFunctionNoProtoType(Context.IntTy))) {
17483 Diag(Loc, diag::ext_use_out_of_scope_declaration)
17484 << ExternCPrev << !getLangOpts().C99;
17485 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
17486 return ExternCPrev;
17487 }
17488 }
17489
17490 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17491 unsigned diag_id;
17492 if (II.getName().starts_with("__builtin_"))
17493 diag_id = diag::warn_builtin_unknown;
17494 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17495 else if (getLangOpts().C99)
17496 diag_id = diag::ext_implicit_function_decl_c99;
17497 else
17498 diag_id = diag::warn_implicit_function_decl;
17499
17500 TypoCorrection Corrected;
17501 // Because typo correction is expensive, only do it if the implicit
17502 // function declaration is going to be treated as an error.
17503 //
17504 // Perform the correction before issuing the main diagnostic, as some
17505 // consumers use typo-correction callbacks to enhance the main diagnostic.
17506 if (S && !ExternCPrev &&
17507 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17509 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17510 S, nullptr, CCC, CorrectTypoKind::NonError);
17511 }
17512
17513 Diag(Loc, diag_id) << &II;
17514 if (Corrected) {
17515 // If the correction is going to suggest an implicitly defined function,
17516 // skip the correction as not being a particularly good idea.
17517 bool Diagnose = true;
17518 if (const auto *D = Corrected.getCorrectionDecl())
17519 Diagnose = !D->isImplicit();
17520 if (Diagnose)
17521 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17522 /*ErrorRecovery*/ false);
17523 }
17524
17525 // If we found a prior declaration of this function, don't bother building
17526 // another one. We've already pushed that one into scope, so there's nothing
17527 // more to do.
17528 if (ExternCPrev)
17529 return ExternCPrev;
17530
17531 // Set a Declarator for the implicit definition: int foo();
17532 const char *Dummy;
17533 AttributeFactory attrFactory;
17534 DeclSpec DS(attrFactory);
17535 unsigned DiagID;
17536 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17537 Context.getPrintingPolicy());
17538 (void)Error; // Silence warning.
17539 assert(!Error && "Error setting up implicit decl!");
17540 SourceLocation NoLoc;
17542 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17543 /*IsAmbiguous=*/false,
17544 /*LParenLoc=*/NoLoc,
17545 /*Params=*/nullptr,
17546 /*NumParams=*/0,
17547 /*EllipsisLoc=*/NoLoc,
17548 /*RParenLoc=*/NoLoc,
17549 /*RefQualifierIsLvalueRef=*/true,
17550 /*RefQualifierLoc=*/NoLoc,
17551 /*MutableLoc=*/NoLoc, EST_None,
17552 /*ESpecRange=*/SourceRange(),
17553 /*Exceptions=*/nullptr,
17554 /*ExceptionRanges=*/nullptr,
17555 /*NumExceptions=*/0,
17556 /*NoexceptExpr=*/nullptr,
17557 /*ExceptionSpecTokens=*/nullptr,
17558 /*DeclsInPrototype=*/{}, Loc, Loc,
17559 D),
17560 std::move(DS.getAttributes()), SourceLocation());
17561 D.SetIdentifier(&II, Loc);
17562
17563 // Insert this function into the enclosing block scope.
17564 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17565 FD->setImplicit();
17566
17568
17569 return FD;
17570}
17571
17573 FunctionDecl *FD) {
17574 if (FD->isInvalidDecl())
17575 return;
17576
17577 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17578 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17579 return;
17580
17581 UnsignedOrNone AlignmentParam = std::nullopt;
17582 bool IsNothrow = false;
17583 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17584 return;
17585
17586 // C++2a [basic.stc.dynamic.allocation]p4:
17587 // An allocation function that has a non-throwing exception specification
17588 // indicates failure by returning a null pointer value. Any other allocation
17589 // function never returns a null pointer value and indicates failure only by
17590 // throwing an exception [...]
17591 //
17592 // However, -fcheck-new invalidates this possible assumption, so don't add
17593 // NonNull when that is enabled.
17594 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17595 !getLangOpts().CheckNew)
17596 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17597
17598 // C++2a [basic.stc.dynamic.allocation]p2:
17599 // An allocation function attempts to allocate the requested amount of
17600 // storage. [...] If the request succeeds, the value returned by a
17601 // replaceable allocation function is a [...] pointer value p0 different
17602 // from any previously returned value p1 [...]
17603 //
17604 // However, this particular information is being added in codegen,
17605 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17606
17607 // C++2a [basic.stc.dynamic.allocation]p2:
17608 // An allocation function attempts to allocate the requested amount of
17609 // storage. If it is successful, it returns the address of the start of a
17610 // block of storage whose length in bytes is at least as large as the
17611 // requested size.
17612 if (!FD->hasAttr<AllocSizeAttr>()) {
17613 FD->addAttr(AllocSizeAttr::CreateImplicit(
17614 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17615 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17616 }
17617
17618 // C++2a [basic.stc.dynamic.allocation]p3:
17619 // For an allocation function [...], the pointer returned on a successful
17620 // call shall represent the address of storage that is aligned as follows:
17621 // (3.1) If the allocation function takes an argument of type
17622 // std​::​align_­val_­t, the storage will have the alignment
17623 // specified by the value of this argument.
17624 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17625 FD->addAttr(AllocAlignAttr::CreateImplicit(
17626 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17627 }
17628
17629 // FIXME:
17630 // C++2a [basic.stc.dynamic.allocation]p3:
17631 // For an allocation function [...], the pointer returned on a successful
17632 // call shall represent the address of storage that is aligned as follows:
17633 // (3.2) Otherwise, if the allocation function is named operator new[],
17634 // the storage is aligned for any object that does not have
17635 // new-extended alignment ([basic.align]) and is no larger than the
17636 // requested size.
17637 // (3.3) Otherwise, the storage is aligned for any object that does not
17638 // have new-extended alignment and is of the requested size.
17639}
17640
17642 if (FD->isInvalidDecl())
17643 return;
17644
17645 // If this is a built-in function, map its builtin attributes to
17646 // actual attributes.
17647 if (unsigned BuiltinID = FD->getBuiltinID()) {
17648 // Handle printf-formatting attributes.
17649 unsigned FormatIdx;
17650 bool HasVAListArg;
17651 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17652 if (!FD->hasAttr<FormatAttr>()) {
17653 const char *fmt = "printf";
17654 unsigned int NumParams = FD->getNumParams();
17655 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17656 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17657 fmt = "NSString";
17658 FD->addAttr(FormatAttr::CreateImplicit(Context,
17659 &Context.Idents.get(fmt),
17660 FormatIdx+1,
17661 HasVAListArg ? 0 : FormatIdx+2,
17662 FD->getLocation()));
17663 }
17664 }
17665 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17666 HasVAListArg)) {
17667 if (!FD->hasAttr<FormatAttr>())
17668 FD->addAttr(FormatAttr::CreateImplicit(Context,
17669 &Context.Idents.get("scanf"),
17670 FormatIdx+1,
17671 HasVAListArg ? 0 : FormatIdx+2,
17672 FD->getLocation()));
17673 }
17674
17675 // Handle automatically recognized callbacks.
17676 SmallVector<int, 4> Encoding;
17677 if (!FD->hasAttr<CallbackAttr>() &&
17678 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17679 FD->addAttr(CallbackAttr::CreateImplicit(
17680 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17681
17682 // Mark const if we don't care about errno and/or floating point exceptions
17683 // that are the only thing preventing the function from being const. This
17684 // allows IRgen to use LLVM intrinsics for such functions.
17685 bool NoExceptions =
17687 bool ConstWithoutErrnoAndExceptions =
17688 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17689 bool ConstWithoutExceptions =
17690 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17691 if (!FD->hasAttr<ConstAttr>() &&
17692 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17693 (!ConstWithoutErrnoAndExceptions ||
17694 (!getLangOpts().MathErrno && NoExceptions)) &&
17695 (!ConstWithoutExceptions || NoExceptions))
17696 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17697
17698 // We make "fma" on GNU or Windows const because we know it does not set
17699 // errno in those environments even though it could set errno based on the
17700 // C standard.
17701 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17702 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17703 !FD->hasAttr<ConstAttr>()) {
17704 switch (BuiltinID) {
17705 case Builtin::BI__builtin_fma:
17706 case Builtin::BI__builtin_fmaf:
17707 case Builtin::BI__builtin_fmal:
17708 case Builtin::BIfma:
17709 case Builtin::BIfmaf:
17710 case Builtin::BIfmal:
17711 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17712 break;
17713 default:
17714 break;
17715 }
17716 }
17717
17718 SmallVector<int, 4> Indxs;
17720 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17721 !FD->hasAttr<NonNullAttr>()) {
17723 for (int I : Indxs) {
17724 ParmVarDecl *PVD = FD->getParamDecl(I);
17725 QualType T = PVD->getType();
17726 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17727 PVD->setType(T);
17728 }
17729 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17731 for (int I : Indxs)
17732 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17733 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17734 ParamIndxs.size()));
17735 }
17736 }
17737 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17738 !FD->hasAttr<ReturnsTwiceAttr>())
17739 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17740 FD->getLocation()));
17741 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17742 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17743 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17744 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17745 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17746 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17747 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17748 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17749 // Add the appropriate attribute, depending on the CUDA compilation mode
17750 // and which target the builtin belongs to. For example, during host
17751 // compilation, aux builtins are __device__, while the rest are __host__.
17752 if (getLangOpts().CUDAIsDevice !=
17753 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17754 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17755 else
17756 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17757 }
17758
17759 // Add known guaranteed alignment for allocation functions.
17760 switch (BuiltinID) {
17761 case Builtin::BImemalign:
17762 case Builtin::BIaligned_alloc:
17763 if (!FD->hasAttr<AllocAlignAttr>())
17764 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17765 FD->getLocation()));
17766 break;
17767 default:
17768 break;
17769 }
17770
17771 // Add allocsize attribute for allocation functions.
17772 switch (BuiltinID) {
17773 case Builtin::BIcalloc:
17774 FD->addAttr(AllocSizeAttr::CreateImplicit(
17775 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17776 break;
17777 case Builtin::BImemalign:
17778 case Builtin::BIaligned_alloc:
17779 case Builtin::BIrealloc:
17780 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17781 ParamIdx(), FD->getLocation()));
17782 break;
17783 case Builtin::BImalloc:
17784 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17785 ParamIdx(), FD->getLocation()));
17786 break;
17787 default:
17788 break;
17789 }
17790 }
17791
17796
17797 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17798 // throw, add an implicit nothrow attribute to any extern "C" function we come
17799 // across.
17800 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17801 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17802 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17803 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17804 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17805 }
17806
17807 IdentifierInfo *Name = FD->getIdentifier();
17808 if (!Name)
17809 return;
17812 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17814 // Okay: this could be a libc/libm/Objective-C function we know
17815 // about.
17816 } else
17817 return;
17818
17819 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17820 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17821 // target-specific builtins, perhaps?
17822 if (!FD->hasAttr<FormatAttr>())
17823 FD->addAttr(FormatAttr::CreateImplicit(Context,
17824 &Context.Idents.get("printf"), 2,
17825 Name->isStr("vasprintf") ? 0 : 3,
17826 FD->getLocation()));
17827 }
17828
17829 if (Name->isStr("__CFStringMakeConstantString")) {
17830 // We already have a __builtin___CFStringMakeConstantString,
17831 // but builds that use -fno-constant-cfstrings don't go through that.
17832 if (!FD->hasAttr<FormatArgAttr>())
17833 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17834 FD->getLocation()));
17835 }
17836}
17837
17839 TypeSourceInfo *TInfo) {
17840 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17841 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17842
17843 if (!TInfo) {
17844 assert(D.isInvalidType() && "no declarator info for valid type");
17845 TInfo = Context.getTrivialTypeSourceInfo(T);
17846 }
17847
17848 // Scope manipulation handled by caller.
17849 TypedefDecl *NewTD =
17851 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17852
17853 // Bail out immediately if we have an invalid declaration.
17854 if (D.isInvalidType()) {
17855 NewTD->setInvalidDecl();
17856 return NewTD;
17857 }
17858
17860 if (CurContext->isFunctionOrMethod())
17861 Diag(NewTD->getLocation(), diag::err_module_private_local)
17862 << 2 << NewTD
17866 else
17867 NewTD->setModulePrivate();
17868 }
17869
17870 // C++ [dcl.typedef]p8:
17871 // If the typedef declaration defines an unnamed class (or
17872 // enum), the first typedef-name declared by the declaration
17873 // to be that class type (or enum type) is used to denote the
17874 // class type (or enum type) for linkage purposes only.
17875 // We need to check whether the type was declared in the declaration.
17876 switch (D.getDeclSpec().getTypeSpecType()) {
17877 case TST_enum:
17878 case TST_struct:
17879 case TST_interface:
17880 case TST_union:
17881 case TST_class: {
17882 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17883 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17884 break;
17885 }
17886
17887 default:
17888 break;
17889 }
17890
17891 return NewTD;
17892}
17893
17895 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17896 QualType T = TI->getType();
17897
17898 if (T->isDependentType())
17899 return false;
17900
17901 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17902 // integral type; any cv-qualification is ignored.
17903 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17904 // non-atomic version of the type specified by the type specifiers in the
17905 // specifier qualifier list.
17906 // Because of how odd C's rule is, we'll let the user know that operations
17907 // involving the enumeration type will be non-atomic.
17908 if (T->isAtomicType())
17909 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17910
17911 Qualifiers Q = T.getQualifiers();
17912 std::optional<unsigned> QualSelect;
17913 if (Q.hasConst() && Q.hasVolatile())
17914 QualSelect = diag::CVQualList::Both;
17915 else if (Q.hasConst())
17916 QualSelect = diag::CVQualList::Const;
17917 else if (Q.hasVolatile())
17918 QualSelect = diag::CVQualList::Volatile;
17919
17920 if (QualSelect)
17921 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17922
17923 T = T.getAtomicUnqualifiedType();
17924
17925 // This doesn't use 'isIntegralType' despite the error message mentioning
17926 // integral type because isIntegralType would also allow enum types in C.
17927 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17928 if (BT->isInteger())
17929 return false;
17930
17931 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17932 << T << T->isBitIntType();
17933}
17934
17936 QualType EnumUnderlyingTy, bool IsFixed,
17937 const EnumDecl *Prev) {
17938 if (IsScoped != Prev->isScoped()) {
17939 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17940 << Prev->isScoped();
17941 Diag(Prev->getLocation(), diag::note_previous_declaration);
17942 return true;
17943 }
17944
17945 if (IsFixed && Prev->isFixed()) {
17946 if (!EnumUnderlyingTy->isDependentType() &&
17947 !Prev->getIntegerType()->isDependentType() &&
17948 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17949 Prev->getIntegerType())) {
17950 // TODO: Highlight the underlying type of the redeclaration.
17951 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17952 << EnumUnderlyingTy << Prev->getIntegerType();
17953 Diag(Prev->getLocation(), diag::note_previous_declaration)
17954 << Prev->getIntegerTypeRange();
17955 return true;
17956 }
17957 } else if (IsFixed != Prev->isFixed()) {
17958 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17959 << Prev->isFixed();
17960 Diag(Prev->getLocation(), diag::note_previous_declaration);
17961 return true;
17962 }
17963
17964 return false;
17965}
17966
17967/// Get diagnostic %select index for tag kind for
17968/// redeclaration diagnostic message.
17969/// WARNING: Indexes apply to particular diagnostics only!
17970///
17971/// \returns diagnostic %select index.
17973 switch (Tag) {
17975 return 0;
17977 return 1;
17978 case TagTypeKind::Class:
17979 return 2;
17980 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17981 }
17982}
17983
17984/// Determine if tag kind is a class-key compatible with
17985/// class for redeclaration (class, struct, or __interface).
17986///
17987/// \returns true iff the tag kind is compatible.
17989{
17990 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17992}
17993
17995 if (isa<TypedefDecl>(PrevDecl))
17996 return NonTagKind::Typedef;
17997 else if (isa<TypeAliasDecl>(PrevDecl))
17998 return NonTagKind::TypeAlias;
17999 else if (isa<ClassTemplateDecl>(PrevDecl))
18000 return NonTagKind::Template;
18001 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
18003 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
18005 switch (TTK) {
18008 case TagTypeKind::Class:
18009 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
18011 case TagTypeKind::Union:
18012 return NonTagKind::NonUnion;
18013 case TagTypeKind::Enum:
18014 return NonTagKind::NonEnum;
18015 }
18016 llvm_unreachable("invalid TTK");
18017}
18018
18020 TagTypeKind NewTag, bool isDefinition,
18021 SourceLocation NewTagLoc,
18022 const IdentifierInfo *Name) {
18023 // C++ [dcl.type.elab]p3:
18024 // The class-key or enum keyword present in the
18025 // elaborated-type-specifier shall agree in kind with the
18026 // declaration to which the name in the elaborated-type-specifier
18027 // refers. This rule also applies to the form of
18028 // elaborated-type-specifier that declares a class-name or
18029 // friend class since it can be construed as referring to the
18030 // definition of the class. Thus, in any
18031 // elaborated-type-specifier, the enum keyword shall be used to
18032 // refer to an enumeration (7.2), the union class-key shall be
18033 // used to refer to a union (clause 9), and either the class or
18034 // struct class-key shall be used to refer to a class (clause 9)
18035 // declared using the class or struct class-key.
18036 TagTypeKind OldTag = Previous->getTagKind();
18037 if (OldTag != NewTag &&
18039 return false;
18040
18041 // Tags are compatible, but we might still want to warn on mismatched tags.
18042 // Non-class tags can't be mismatched at this point.
18044 return true;
18045
18046 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
18047 // by our warning analysis. We don't want to warn about mismatches with (eg)
18048 // declarations in system headers that are designed to be specialized, but if
18049 // a user asks us to warn, we should warn if their code contains mismatched
18050 // declarations.
18051 auto IsIgnoredLoc = [&](SourceLocation Loc) {
18052 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
18053 Loc);
18054 };
18055 if (IsIgnoredLoc(NewTagLoc))
18056 return true;
18057
18058 auto IsIgnored = [&](const TagDecl *Tag) {
18059 return IsIgnoredLoc(Tag->getLocation());
18060 };
18061 while (IsIgnored(Previous)) {
18062 Previous = Previous->getPreviousDecl();
18063 if (!Previous)
18064 return true;
18065 OldTag = Previous->getTagKind();
18066 }
18067
18068 bool isTemplate = false;
18069 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
18070 isTemplate = Record->getDescribedClassTemplate();
18071
18073 if (OldTag != NewTag) {
18074 // In a template instantiation, do not offer fix-its for tag mismatches
18075 // since they usually mess up the template instead of fixing the problem.
18076 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
18078 << getRedeclDiagFromTagKind(OldTag);
18079 // FIXME: Note previous location?
18080 }
18081 return true;
18082 }
18083
18084 if (isDefinition) {
18085 // On definitions, check all previous tags and issue a fix-it for each
18086 // one that doesn't match the current tag.
18087 if (Previous->getDefinition()) {
18088 // Don't suggest fix-its for redefinitions.
18089 return true;
18090 }
18091
18092 bool previousMismatch = false;
18093 for (const TagDecl *I : Previous->redecls()) {
18094 if (I->getTagKind() != NewTag) {
18095 // Ignore previous declarations for which the warning was disabled.
18096 if (IsIgnored(I))
18097 continue;
18098
18099 if (!previousMismatch) {
18100 previousMismatch = true;
18101 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
18103 << getRedeclDiagFromTagKind(I->getTagKind());
18104 }
18105 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
18107 << FixItHint::CreateReplacement(I->getInnerLocStart(),
18109 }
18110 }
18111 return true;
18112 }
18113
18114 // Identify the prevailing tag kind: this is the kind of the definition (if
18115 // there is a non-ignored definition), or otherwise the kind of the prior
18116 // (non-ignored) declaration.
18117 const TagDecl *PrevDef = Previous->getDefinition();
18118 if (PrevDef && IsIgnored(PrevDef))
18119 PrevDef = nullptr;
18120 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
18121 if (Redecl->getTagKind() != NewTag) {
18122 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
18124 << getRedeclDiagFromTagKind(OldTag);
18125 Diag(Redecl->getLocation(), diag::note_previous_use);
18126
18127 // If there is a previous definition, suggest a fix-it.
18128 if (PrevDef) {
18129 Diag(NewTagLoc, diag::note_struct_class_suggestion)
18133 }
18134 }
18135
18136 return true;
18137}
18138
18139/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
18140/// from an outer enclosing namespace or file scope inside a friend declaration.
18141/// This should provide the commented out code in the following snippet:
18142/// namespace N {
18143/// struct X;
18144/// namespace M {
18145/// struct Y { friend struct /*N::*/ X; };
18146/// }
18147/// }
18149 SourceLocation NameLoc) {
18150 // While the decl is in a namespace, do repeated lookup of that name and see
18151 // if we get the same namespace back. If we do not, continue until
18152 // translation unit scope, at which point we have a fully qualified NNS.
18155 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
18156 // This tag should be declared in a namespace, which can only be enclosed by
18157 // other namespaces. Bail if there's an anonymous namespace in the chain.
18158 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
18159 if (!Namespace || Namespace->isAnonymousNamespace())
18160 return FixItHint();
18161 IdentifierInfo *II = Namespace->getIdentifier();
18162 Namespaces.push_back(II);
18163 NamedDecl *Lookup = SemaRef.LookupSingleName(
18164 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
18165 if (Lookup == Namespace)
18166 break;
18167 }
18168
18169 // Once we have all the namespaces, reverse them to go outermost first, and
18170 // build an NNS.
18171 SmallString<64> Insertion;
18172 llvm::raw_svector_ostream OS(Insertion);
18173 if (DC->isTranslationUnit())
18174 OS << "::";
18175 std::reverse(Namespaces.begin(), Namespaces.end());
18176 for (auto *II : Namespaces)
18177 OS << II->getName() << "::";
18178 return FixItHint::CreateInsertion(NameLoc, Insertion);
18179}
18180
18181/// Determine whether a tag originally declared in context \p OldDC can
18182/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
18183/// found a declaration in \p OldDC as a previous decl, perhaps through a
18184/// using-declaration).
18186 DeclContext *NewDC) {
18187 OldDC = OldDC->getRedeclContext();
18188 NewDC = NewDC->getRedeclContext();
18189
18190 if (OldDC->Equals(NewDC))
18191 return true;
18192
18193 // In MSVC mode, we allow a redeclaration if the contexts are related (either
18194 // encloses the other).
18195 if (S.getLangOpts().MSVCCompat &&
18196 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
18197 return true;
18198
18199 return false;
18200}
18201
18203Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
18204 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18205 const ParsedAttributesView &Attrs, AccessSpecifier AS,
18206 SourceLocation ModulePrivateLoc,
18207 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
18208 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
18209 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
18210 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
18211 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
18212 // If this is not a definition, it must have a name.
18213 IdentifierInfo *OrigName = Name;
18214 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
18215 "Nameless record must be a definition!");
18216 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
18217
18218 OwnedDecl = false;
18220 bool ScopedEnum = ScopedEnumKWLoc.isValid();
18221
18222 // FIXME: Check member specializations more carefully.
18223 bool isMemberSpecialization = false;
18224 bool IsInjectedClassName = false;
18225 bool Invalid = false;
18226
18227 // We only need to do this matching if we have template parameters
18228 // or a scope specifier, which also conveniently avoids this work
18229 // for non-C++ cases.
18230 if (TemplateParameterLists.size() > 0 ||
18231 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
18232 TemplateParameterList *TemplateParams =
18234 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
18235 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
18236
18237 // C++23 [dcl.type.elab] p2:
18238 // If an elaborated-type-specifier is the sole constituent of a
18239 // declaration, the declaration is ill-formed unless it is an explicit
18240 // specialization, an explicit instantiation or it has one of the
18241 // following forms: [...]
18242 // C++23 [dcl.enum] p1:
18243 // If the enum-head-name of an opaque-enum-declaration contains a
18244 // nested-name-specifier, the declaration shall be an explicit
18245 // specialization.
18246 //
18247 // FIXME: Class template partial specializations can be forward declared
18248 // per CWG2213, but the resolution failed to allow qualified forward
18249 // declarations. This is almost certainly unintentional, so we allow them.
18250 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18251 !isMemberSpecialization)
18252 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
18254
18255 if (TemplateParams) {
18256 if (Kind == TagTypeKind::Enum) {
18257 Diag(KWLoc, diag::err_enum_template);
18258 return true;
18259 }
18260
18261 if (TemplateParams->size() > 0) {
18262 // This is a declaration or definition of a class template (which may
18263 // be a member of another template).
18264
18265 if (Invalid)
18266 return true;
18267
18268 OwnedDecl = false;
18270 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
18271 AS, ModulePrivateLoc,
18272 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
18273 TemplateParameterLists.data(), isMemberSpecialization, SkipBody);
18274 return Result.get();
18275 } else {
18276 // The "template<>" header is extraneous.
18277 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18278 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18279 isMemberSpecialization = true;
18280 }
18281 }
18282
18283 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18284 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
18285 return true;
18286 }
18287
18288 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18289 // C++23 [dcl.type.elab]p4:
18290 // If an elaborated-type-specifier appears with the friend specifier as
18291 // an entire member-declaration, the member-declaration shall have one
18292 // of the following forms:
18293 // friend class-key nested-name-specifier(opt) identifier ;
18294 // friend class-key simple-template-id ;
18295 // friend class-key nested-name-specifier template(opt)
18296 // simple-template-id ;
18297 //
18298 // Since enum is not a class-key, so declarations like "friend enum E;"
18299 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18300 // invalid, most implementations accept so we issue a pedantic warning.
18301 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
18302 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18303 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18304 Diag(KWLoc, diag::note_enum_friend)
18305 << (ScopedEnum + ScopedEnumUsesClassTag);
18306 }
18307
18308 // Figure out the underlying type if this a enum declaration. We need to do
18309 // this early, because it's needed to detect if this is an incompatible
18310 // redeclaration.
18311 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18312 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18313
18314 if (Kind == TagTypeKind::Enum) {
18315 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18316 Invalid) {
18317 // No underlying type explicitly specified, or we failed to parse the
18318 // type, default to int.
18319 EnumUnderlying = Context.IntTy.getTypePtr();
18320 } else if (UnderlyingType.get()) {
18321 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18322 // integral type; any cv-qualification is ignored.
18323 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18324 // unqualified, non-atomic version of the type specified by the type
18325 // specifiers in the specifier qualifier list.
18326 TypeSourceInfo *TI = nullptr;
18327 GetTypeFromParser(UnderlyingType.get(), &TI);
18328 EnumUnderlying = TI;
18329
18331 // Recover by falling back to int.
18332 EnumUnderlying = Context.IntTy.getTypePtr();
18333
18336 EnumUnderlying = Context.IntTy.getTypePtr();
18337
18338 // If the underlying type is atomic, we need to adjust the type before
18339 // continuing. This only happens in the case we stored a TypeSourceInfo
18340 // into EnumUnderlying because the other cases are error recovery up to
18341 // this point. But because it's not possible to gin up a TypeSourceInfo
18342 // for a non-atomic type from an atomic one, we'll store into the Type
18343 // field instead. FIXME: it would be nice to have an easy way to get a
18344 // derived TypeSourceInfo which strips qualifiers including the weird
18345 // ones like _Atomic where it forms a different type.
18346 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
18347 TI && TI->getType()->isAtomicType())
18348 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18349
18350 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18351 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18352 // of 'int'. However, if this is an unfixed forward declaration, don't set
18353 // the underlying type unless the user enables -fms-compatibility. This
18354 // makes unfixed forward declared enums incomplete and is more conforming.
18355 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18356 EnumUnderlying = Context.IntTy.getTypePtr();
18357 }
18358 }
18359
18360 DeclContext *SearchDC = CurContext;
18361 DeclContext *DC = CurContext;
18362 bool isStdBadAlloc = false;
18363 bool isStdAlignValT = false;
18364
18366 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18368
18369 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18370 /// implemented asks for structural equivalence checking, the returned decl
18371 /// here is passed back to the parser, allowing the tag body to be parsed.
18372 auto createTagFromNewDecl = [&]() -> TagDecl * {
18373 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18374 // If there is an identifier, use the location of the identifier as the
18375 // location of the decl, otherwise use the location of the struct/union
18376 // keyword.
18377 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18378 TagDecl *New = nullptr;
18379
18380 if (Kind == TagTypeKind::Enum) {
18381 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
18382 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
18383 // If this is an undefined enum, bail.
18384 if (TUK != TagUseKind::Definition && !Invalid)
18385 return nullptr;
18386 if (EnumUnderlying) {
18388 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18390 else
18391 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18392 QualType EnumTy = ED->getIntegerType();
18393 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18394 ? Context.getPromotedIntegerType(EnumTy)
18395 : EnumTy);
18396 }
18397 } else { // struct/union
18398 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18399 nullptr);
18400 }
18401
18402 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18403 // Add alignment attributes if necessary; these attributes are checked
18404 // when the ASTContext lays out the structure.
18405 //
18406 // It is important for implementing the correct semantics that this
18407 // happen here (in ActOnTag). The #pragma pack stack is
18408 // maintained as a result of parser callbacks which can occur at
18409 // many points during the parsing of a struct declaration (because
18410 // the #pragma tokens are effectively skipped over during the
18411 // parsing of the struct).
18412 if (TUK == TagUseKind::Definition &&
18413 (!SkipBody || !SkipBody->ShouldSkip)) {
18414 if (LangOpts.HLSL)
18415 RD->addAttr(PackedAttr::CreateImplicit(Context));
18418 }
18419 }
18420 New->setLexicalDeclContext(CurContext);
18421 return New;
18422 };
18423
18424 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18425 if (Name && SS.isNotEmpty()) {
18426 // We have a nested-name tag ('struct foo::bar').
18427
18428 // Check for invalid 'foo::'.
18429 if (SS.isInvalid()) {
18430 Name = nullptr;
18431 goto CreateNewDecl;
18432 }
18433
18434 // If this is a friend or a reference to a class in a dependent
18435 // context, don't try to make a decl for it.
18436 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18437 DC = computeDeclContext(SS, false);
18438 if (!DC) {
18439 IsDependent = true;
18440 return true;
18441 }
18442 } else {
18443 DC = computeDeclContext(SS, true);
18444 if (!DC) {
18445 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
18446 << SS.getRange();
18447 return true;
18448 }
18449 }
18450
18451 if (RequireCompleteDeclContext(SS, DC))
18452 return true;
18453
18454 SearchDC = DC;
18455 // Look-up name inside 'foo::'.
18457
18458 if (Previous.isAmbiguous())
18459 return true;
18460
18461 if (Previous.empty()) {
18462 // Name lookup did not find anything. However, if the
18463 // nested-name-specifier refers to the current instantiation,
18464 // and that current instantiation has any dependent base
18465 // classes, we might find something at instantiation time: treat
18466 // this as a dependent elaborated-type-specifier.
18467 // But this only makes any sense for reference-like lookups.
18468 if (Previous.wasNotFoundInCurrentInstantiation() &&
18469 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18470 IsDependent = true;
18471 return true;
18472 }
18473
18474 // A tag 'foo::bar' must already exist.
18475 Diag(NameLoc, diag::err_not_tag_in_scope)
18476 << Kind << Name << DC << SS.getRange();
18477 Name = nullptr;
18478 Invalid = true;
18479 goto CreateNewDecl;
18480 }
18481 } else if (Name) {
18482 // C++14 [class.mem]p14:
18483 // If T is the name of a class, then each of the following shall have a
18484 // name different from T:
18485 // -- every member of class T that is itself a type
18486 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18487 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
18488 return true;
18489
18490 // If this is a named struct, check to see if there was a previous forward
18491 // declaration or definition.
18492 // FIXME: We're looking into outer scopes here, even when we
18493 // shouldn't be. Doing so can result in ambiguities that we
18494 // shouldn't be diagnosing.
18495 LookupName(Previous, S);
18496
18497 // When declaring or defining a tag, ignore ambiguities introduced
18498 // by types using'ed into this scope.
18499 if (Previous.isAmbiguous() &&
18501 LookupResult::Filter F = Previous.makeFilter();
18502 while (F.hasNext()) {
18503 NamedDecl *ND = F.next();
18504 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18505 SearchDC->getRedeclContext()))
18506 F.erase();
18507 }
18508 F.done();
18509 }
18510
18511 // C++11 [namespace.memdef]p3:
18512 // If the name in a friend declaration is neither qualified nor
18513 // a template-id and the declaration is a function or an
18514 // elaborated-type-specifier, the lookup to determine whether
18515 // the entity has been previously declared shall not consider
18516 // any scopes outside the innermost enclosing namespace.
18517 //
18518 // MSVC doesn't implement the above rule for types, so a friend tag
18519 // declaration may be a redeclaration of a type declared in an enclosing
18520 // scope. They do implement this rule for friend functions.
18521 //
18522 // Does it matter that this should be by scope instead of by
18523 // semantic context?
18524 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18525 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18526 LookupResult::Filter F = Previous.makeFilter();
18527 bool FriendSawTagOutsideEnclosingNamespace = false;
18528 while (F.hasNext()) {
18529 NamedDecl *ND = F.next();
18531 if (DC->isFileContext() &&
18532 !EnclosingNS->Encloses(ND->getDeclContext())) {
18533 if (getLangOpts().MSVCCompat)
18534 FriendSawTagOutsideEnclosingNamespace = true;
18535 else
18536 F.erase();
18537 }
18538 }
18539 F.done();
18540
18541 // Diagnose this MSVC extension in the easy case where lookup would have
18542 // unambiguously found something outside the enclosing namespace.
18543 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18544 NamedDecl *ND = Previous.getFoundDecl();
18545 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18546 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18547 }
18548 }
18549
18550 // Note: there used to be some attempt at recovery here.
18551 if (Previous.isAmbiguous())
18552 return true;
18553
18554 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18555 // FIXME: This makes sure that we ignore the contexts associated
18556 // with C structs, unions, and enums when looking for a matching
18557 // tag declaration or definition. See the similar lookup tweak
18558 // in Sema::LookupName; is there a better way to deal with this?
18560 SearchDC = SearchDC->getParent();
18561 } else if (getLangOpts().CPlusPlus) {
18562 // Inside ObjCContainer want to keep it as a lexical decl context but go
18563 // past it (most often to TranslationUnit) to find the semantic decl
18564 // context.
18565 while (isa<ObjCContainerDecl>(SearchDC))
18566 SearchDC = SearchDC->getParent();
18567 }
18568 } else if (getLangOpts().CPlusPlus) {
18569 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18570 // TagDecl the same way as we skip it for named TagDecl.
18571 while (isa<ObjCContainerDecl>(SearchDC))
18572 SearchDC = SearchDC->getParent();
18573 }
18574
18575 if (Previous.isSingleResult() &&
18576 Previous.getFoundDecl()->isTemplateParameter()) {
18577 // Maybe we will complain about the shadowed template parameter.
18578 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18579 // Just pretend that we didn't see the previous declaration.
18580 Previous.clear();
18581 }
18582
18583 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18585 if (Name->isStr("bad_alloc")) {
18586 // This is a declaration of or a reference to "std::bad_alloc".
18587 isStdBadAlloc = true;
18588
18589 // If std::bad_alloc has been implicitly declared (but made invisible to
18590 // name lookup), fill in this implicit declaration as the previous
18591 // declaration, so that the declarations get chained appropriately.
18592 if (Previous.empty() && StdBadAlloc)
18593 Previous.addDecl(getStdBadAlloc());
18594 } else if (Name->isStr("align_val_t")) {
18595 isStdAlignValT = true;
18596 if (Previous.empty() && StdAlignValT)
18597 Previous.addDecl(getStdAlignValT());
18598 }
18599 }
18600
18601 // If we didn't find a previous declaration, and this is a reference
18602 // (or friend reference), move to the correct scope. In C++, we
18603 // also need to do a redeclaration lookup there, just in case
18604 // there's a shadow friend decl.
18605 if (Name && Previous.empty() &&
18606 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18607 IsTemplateParamOrArg)) {
18608 if (Invalid) goto CreateNewDecl;
18609 assert(SS.isEmpty());
18610
18611 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18612 // C++ [basic.scope.pdecl]p5:
18613 // -- for an elaborated-type-specifier of the form
18614 //
18615 // class-key identifier
18616 //
18617 // if the elaborated-type-specifier is used in the
18618 // decl-specifier-seq or parameter-declaration-clause of a
18619 // function defined in namespace scope, the identifier is
18620 // declared as a class-name in the namespace that contains
18621 // the declaration; otherwise, except as a friend
18622 // declaration, the identifier is declared in the smallest
18623 // non-class, non-function-prototype scope that contains the
18624 // declaration.
18625 //
18626 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18627 // C structs and unions.
18628 //
18629 // It is an error in C++ to declare (rather than define) an enum
18630 // type, including via an elaborated type specifier. We'll
18631 // diagnose that later; for now, declare the enum in the same
18632 // scope as we would have picked for any other tag type.
18633 //
18634 // GNU C also supports this behavior as part of its incomplete
18635 // enum types extension, while GNU C++ does not.
18636 //
18637 // Find the context where we'll be declaring the tag.
18638 // FIXME: We would like to maintain the current DeclContext as the
18639 // lexical context,
18640 SearchDC = getTagInjectionContext(SearchDC);
18641
18642 // Find the scope where we'll be declaring the tag.
18644 } else {
18645 assert(TUK == TagUseKind::Friend);
18646 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18647
18648 // C++ [namespace.memdef]p3:
18649 // If a friend declaration in a non-local class first declares a
18650 // class or function, the friend class or function is a member of
18651 // the innermost enclosing namespace.
18652 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18653 : SearchDC->getEnclosingNamespaceContext();
18654 }
18655
18656 // In C++, we need to do a redeclaration lookup to properly
18657 // diagnose some problems.
18658 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18659 // hidden declaration so that we don't get ambiguity errors when using a
18660 // type declared by an elaborated-type-specifier. In C that is not correct
18661 // and we should instead merge compatible types found by lookup.
18662 if (getLangOpts().CPlusPlus) {
18663 // FIXME: This can perform qualified lookups into function contexts,
18664 // which are meaningless.
18665 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18666 LookupQualifiedName(Previous, SearchDC);
18667 } else {
18668 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18669 LookupName(Previous, S);
18670 }
18671 }
18672
18673 // If we have a known previous declaration to use, then use it.
18674 if (Previous.empty() && SkipBody && SkipBody->Previous)
18675 Previous.addDecl(SkipBody->Previous);
18676
18677 if (!Previous.empty()) {
18678 NamedDecl *PrevDecl = Previous.getFoundDecl();
18679 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18680
18681 // It's okay to have a tag decl in the same scope as a typedef
18682 // which hides a tag decl in the same scope. Finding this
18683 // with a redeclaration lookup can only actually happen in C++.
18684 //
18685 // This is also okay for elaborated-type-specifiers, which is
18686 // technically forbidden by the current standard but which is
18687 // okay according to the likely resolution of an open issue;
18688 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18689 if (getLangOpts().CPlusPlus) {
18690 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18691 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18692 if (Tag->getDeclName() == Name &&
18693 Tag->getDeclContext()->getRedeclContext()
18694 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18695 PrevDecl = Tag;
18696 Previous.clear();
18697 Previous.addDecl(Tag);
18698 Previous.resolveKind();
18699 }
18700 }
18701 }
18702 }
18703
18704 // If this is a redeclaration of a using shadow declaration, it must
18705 // declare a tag in the same context. In MSVC mode, we allow a
18706 // redefinition if either context is within the other.
18707 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18708 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18709 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18710 TUK != TagUseKind::Friend &&
18711 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18712 !(OldTag && isAcceptableTagRedeclContext(
18713 *this, OldTag->getDeclContext(), SearchDC))) {
18714 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18715 Diag(Shadow->getTargetDecl()->getLocation(),
18716 diag::note_using_decl_target);
18717 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18718 << 0;
18719 // Recover by ignoring the old declaration.
18720 Previous.clear();
18721 goto CreateNewDecl;
18722 }
18723 }
18724
18725 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18726 // If this is a use of a previous tag, or if the tag is already declared
18727 // in the same scope (so that the definition/declaration completes or
18728 // rementions the tag), reuse the decl.
18729 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18730 isTagRedeclarationInScope(DirectPrevDecl, SearchDC, S,
18731 SS.isNotEmpty() ||
18732 isMemberSpecialization)) {
18733
18734 if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18735 RD && RD->isInjectedClassName()) {
18736 // If lookup found the injected class name, the previous declaration
18737 // is the class being injected into.
18738 Previous.clear();
18739 PrevDecl = PrevTagDecl = cast<CXXRecordDecl>(RD->getDeclContext());
18740 Previous.addDecl(PrevDecl);
18741 Previous.resolveKind();
18742 IsInjectedClassName = true;
18743 }
18744
18745 // Make sure that this wasn't declared as an enum and now used as a
18746 // struct or something similar.
18747 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18748 TUK == TagUseKind::Definition, KWLoc,
18749 Name)) {
18750 bool SafeToContinue =
18751 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18752 Kind != TagTypeKind::Enum);
18753 if (SafeToContinue)
18754 Diag(KWLoc, diag::err_use_with_wrong_tag)
18755 << Name
18757 PrevTagDecl->getKindName());
18758 else
18759 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18760 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18761
18762 if (SafeToContinue)
18763 Kind = PrevTagDecl->getTagKind();
18764 else {
18765 // Recover by making this an anonymous redefinition.
18766 Name = nullptr;
18767 Previous.clear();
18768 Invalid = true;
18769 }
18770 }
18771
18772 if (Kind == TagTypeKind::Enum &&
18773 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18774 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18775 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18776 return PrevTagDecl;
18777
18778 QualType EnumUnderlyingTy;
18779 if (TypeSourceInfo *TI =
18780 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18781 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18782 else if (const Type *T =
18783 dyn_cast_if_present<const Type *>(EnumUnderlying))
18784 EnumUnderlyingTy = QualType(T, 0);
18785
18786 // All conflicts with previous declarations are recovered by
18787 // returning the previous declaration, unless this is a definition,
18788 // in which case we want the caller to bail out.
18789 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18790 ScopedEnum, EnumUnderlyingTy,
18791 IsFixed, PrevEnum))
18792 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18793 }
18794
18795 // C++11 [class.mem]p1:
18796 // A member shall not be declared twice in the member-specification,
18797 // except that a nested class or member class template can be declared
18798 // and then later defined.
18799 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18800 S->isDeclScope(PrevDecl)) {
18801 Diag(NameLoc, diag::ext_member_redeclared);
18802 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18803 }
18804
18805 // C++ [class.local]p3:
18806 // A class nested within a local class is a local class. A member of
18807 // a local class X shall be declared only in the definition of X or,
18808 // if the member is a nested class, in the nearest enclosing block
18809 // scope of X.
18810 if (TUK == TagUseKind::Definition && SS.isValid()) {
18811 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(PrevDecl)) {
18812 while (const auto *ParentClass =
18813 dyn_cast<CXXRecordDecl>(OutermostClass->getParent()))
18814 OutermostClass = ParentClass;
18815
18816 if (OutermostClass->isLocalClass() &&
18817 !S->isDeclScope(OutermostClass)) {
18818 Diag(NameLoc, diag::err_local_nested_class_invalid_scope)
18819 << Name << OutermostClass;
18820 Diag(OutermostClass->getLocation(), diag::note_defined_here)
18821 << OutermostClass;
18822 }
18823 }
18824 }
18825
18826 if (!Invalid) {
18827 // If this is a use, just return the declaration we found, unless
18828 // we have attributes.
18829 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18830 if (!Attrs.empty()) {
18831 // FIXME: Diagnose these attributes. For now, we create a new
18832 // declaration to hold them.
18833 } else if (TUK == TagUseKind::Reference &&
18834 (PrevTagDecl->getFriendObjectKind() ==
18836 PrevDecl->getOwningModule() != getCurrentModule()) &&
18837 SS.isEmpty()) {
18838 // This declaration is a reference to an existing entity, but
18839 // has different visibility from that entity: it either makes
18840 // a friend visible or it makes a type visible in a new module.
18841 // In either case, create a new declaration. We only do this if
18842 // the declaration would have meant the same thing if no prior
18843 // declaration were found, that is, if it was found in the same
18844 // scope where we would have injected a declaration.
18845 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18846 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18847 return PrevTagDecl;
18848 // This is in the injected scope, create a new declaration in
18849 // that scope.
18851 } else {
18852 return PrevTagDecl;
18853 }
18854 }
18855
18856 // Diagnose attempts to redefine a tag.
18857 if (TUK == TagUseKind::Definition) {
18858 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18859 // If the type is currently being defined, complain
18860 // about a nested redefinition.
18861 if (Def->isBeingDefined()) {
18862 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18863 Diag(PrevTagDecl->getLocation(),
18864 diag::note_previous_definition);
18865 Name = nullptr;
18866 Previous.clear();
18867 Invalid = true;
18868 } else {
18869 // If we're defining a specialization and the previous
18870 // definition is from an implicit instantiation, don't emit an
18871 // error here; we'll catch this in the general case below.
18872 bool IsExplicitSpecializationAfterInstantiation = false;
18873 if (isMemberSpecialization) {
18874 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18875 IsExplicitSpecializationAfterInstantiation =
18876 RD->getTemplateSpecializationKind() !=
18878 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18879 IsExplicitSpecializationAfterInstantiation =
18880 ED->getTemplateSpecializationKind() !=
18882 }
18883
18884 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18885 // do not keep more that one definition around (merge them).
18886 // However, ensure the decl passes the structural compatibility
18887 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18888 NamedDecl *Hidden = nullptr;
18889 bool HiddenDefVisible = false;
18890 if (SkipBody && (isRedefinitionAllowedFor(Def, NameLoc, &Hidden,
18891 HiddenDefVisible) ||
18892 getLangOpts().C23)) {
18893 // There is a definition of this tag, but it is not visible.
18894 // We explicitly make use of C++'s one definition rule here,
18895 // and assume that this definition is identical to the hidden
18896 // one we already have. Make the existing definition visible
18897 // and use it in place of this one.
18898 if (!getLangOpts().CPlusPlus) {
18899 // Postpone making the old definition visible until after we
18900 // complete parsing the new one and do the structural
18901 // comparison.
18902 SkipBody->CheckSameAsPrevious = true;
18903 SkipBody->New = createTagFromNewDecl();
18904 SkipBody->Previous = Def;
18905
18906 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18907 return Def;
18908 }
18909
18910 SkipBody->ShouldSkip = true;
18911 SkipBody->Previous = Def;
18912 if (!HiddenDefVisible && Hidden)
18914 // Carry on and handle it like a normal definition. We'll
18915 // skip starting the definition later.
18916
18917 } else if (!IsExplicitSpecializationAfterInstantiation) {
18918 // A redeclaration in function prototype scope in C isn't
18919 // visible elsewhere, so merely issue a warning.
18920 if (!getLangOpts().CPlusPlus &&
18922 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18923 << Name;
18924 else
18925 Diag(NameLoc, diag::err_redefinition) << Name;
18927 NameLoc.isValid() ? NameLoc : KWLoc);
18928 // If this is a redefinition, recover by making this
18929 // struct be anonymous, which will make any later
18930 // references get the previous definition.
18931 Name = nullptr;
18932 Previous.clear();
18933 Invalid = true;
18934 }
18935 }
18936 }
18937
18938 // Okay, this is definition of a previously declared or referenced
18939 // tag. We're going to create a new Decl for it.
18940 }
18941
18942 // Okay, we're going to make a redeclaration. If this is some kind
18943 // of reference, make sure we build the redeclaration in the same DC
18944 // as the original, and ignore the current access specifier.
18945 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference ||
18946 IsInjectedClassName) {
18947 SearchDC = PrevTagDecl->getDeclContext();
18948 AS = AS_none;
18949 }
18950 }
18951 // If we get here we have (another) forward declaration or we
18952 // have a definition. Just create a new decl.
18953
18954 } else {
18955 // If we get here, this is a definition of a new tag type in a nested
18956 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18957 // new decl/type. We set PrevDecl to NULL so that the entities
18958 // have distinct types.
18959 Previous.clear();
18960 }
18961 // If we get here, we're going to create a new Decl. If PrevDecl
18962 // is non-NULL, it's a definition of the tag declared by
18963 // PrevDecl. If it's NULL, we have a new definition.
18964
18965 // Otherwise, PrevDecl is not a tag, but was found with tag
18966 // lookup. This is only actually possible in C++, where a few
18967 // things like templates still live in the tag namespace.
18968 } else {
18969 // Use a better diagnostic if an elaborated-type-specifier
18970 // found the wrong kind of type on the first
18971 // (non-redeclaration) lookup.
18972 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18973 !Previous.isForRedeclaration()) {
18974 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18975 Diag(NameLoc, diag::err_tag_reference_non_tag)
18976 << PrevDecl << NTK << Kind;
18977 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18978 Invalid = true;
18979
18980 // Otherwise, only diagnose if the declaration is in scope.
18981 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18982 SS.isNotEmpty() || isMemberSpecialization)) {
18983 // do nothing
18984
18985 // Diagnose implicit declarations introduced by elaborated types.
18986 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18987 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18988 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18989 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18990 Invalid = true;
18991
18992 // Otherwise it's a declaration. Call out a particularly common
18993 // case here.
18994 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18995 unsigned Kind = 0;
18996 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18997 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18998 << Name << Kind << TND->getUnderlyingType();
18999 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
19000 Invalid = true;
19001
19002 // Otherwise, diagnose.
19003 } else {
19004 // The tag name clashes with something else in the target scope,
19005 // issue an error and recover by making this tag be anonymous.
19006 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
19007 notePreviousDefinition(PrevDecl, NameLoc);
19008 Name = nullptr;
19009 Invalid = true;
19010 }
19011
19012 // The existing declaration isn't relevant to us; we're in a
19013 // new scope, so clear out the previous declaration.
19014 Previous.clear();
19015 }
19016 }
19017
19018CreateNewDecl:
19019
19020 TagDecl *PrevDecl = nullptr;
19021 if (Previous.isSingleResult())
19022 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
19023
19024 // If there is an identifier, use the location of the identifier as the
19025 // location of the decl, otherwise use the location of the struct/union
19026 // keyword.
19027 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
19028
19029 // Otherwise, create a new declaration. If there is a previous
19030 // declaration of the same entity, the two will be linked via
19031 // PrevDecl.
19032 TagDecl *New;
19033
19034 if (Kind == TagTypeKind::Enum) {
19035 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19036 // enum X { A, B, C } D; D should chain to X.
19037 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
19038 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
19039 ScopedEnumUsesClassTag, IsFixed);
19040
19043 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
19044
19045 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
19047
19048 // If this is an undefined enum, warn.
19049 if (TUK != TagUseKind::Definition && !Invalid) {
19050 TagDecl *Def;
19051 if (IsFixed && ED->isFixed()) {
19052 // C++0x: 7.2p2: opaque-enum-declaration.
19053 // Conflicts are diagnosed above. Do nothing.
19054 } else if (PrevDecl &&
19055 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
19056 Diag(Loc, diag::ext_forward_ref_enum_def)
19057 << New;
19058 Diag(Def->getLocation(), diag::note_previous_definition);
19059 } else {
19060 unsigned DiagID = diag::ext_forward_ref_enum;
19061 if (getLangOpts().MSVCCompat)
19062 DiagID = diag::ext_ms_forward_ref_enum;
19063 else if (getLangOpts().CPlusPlus)
19064 DiagID = diag::err_forward_ref_enum;
19065 Diag(Loc, DiagID);
19066 }
19067 }
19068
19069 if (EnumUnderlying) {
19071 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
19073 else
19074 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
19075 QualType EnumTy = ED->getIntegerType();
19076 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
19077 ? Context.getPromotedIntegerType(EnumTy)
19078 : EnumTy);
19079 assert(ED->isComplete() && "enum with type should be complete");
19080 }
19081 } else {
19082 // struct/union/class
19083
19084 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19085 // struct X { int A; } D; D should chain to X.
19086 if (getLangOpts().CPlusPlus) {
19087 // FIXME: Look for a way to use RecordDecl for simple structs.
19088 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
19089 cast_or_null<CXXRecordDecl>(PrevDecl));
19090
19091 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
19093 } else
19094 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
19095 cast_or_null<RecordDecl>(PrevDecl));
19096 }
19097
19098 // Only C23 and later allow defining new types in 'offsetof()'.
19099 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
19101 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
19102 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
19103
19104 // C++11 [dcl.type]p3:
19105 // A type-specifier-seq shall not define a class or enumeration [...].
19106 if (!Invalid && getLangOpts().CPlusPlus &&
19107 (IsTypeSpecifier || IsTemplateParamOrArg) &&
19108 TUK == TagUseKind::Definition) {
19109 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
19110 << Context.getCanonicalTagType(New);
19111 Invalid = true;
19112 }
19113
19115 DC->getDeclKind() == Decl::Enum) {
19116 Diag(New->getLocation(), diag::err_type_defined_in_enum)
19117 << Context.getCanonicalTagType(New);
19118 Invalid = true;
19119 }
19120
19121 // Maybe add qualifier info.
19122 if (SS.isNotEmpty()) {
19123 if (SS.isSet()) {
19124 // If this is either a declaration or a definition, check the
19125 // nested-name-specifier against the current context.
19126 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
19127 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
19128 /*TemplateId=*/nullptr,
19129 isMemberSpecialization))
19130 Invalid = true;
19131
19132 New->setQualifierInfo(SS.getWithLocInContext(Context));
19133 if (TemplateParameterLists.size() > 0) {
19134 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
19135 }
19136 }
19137 else
19138 Invalid = true;
19139 }
19140
19141 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
19142 // Add alignment attributes if necessary; these attributes are checked when
19143 // the ASTContext lays out the structure.
19144 //
19145 // It is important for implementing the correct semantics that this
19146 // happen here (in ActOnTag). The #pragma pack stack is
19147 // maintained as a result of parser callbacks which can occur at
19148 // many points during the parsing of a struct declaration (because
19149 // the #pragma tokens are effectively skipped over during the
19150 // parsing of the struct).
19151 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
19152 if (LangOpts.HLSL)
19153 RD->addAttr(PackedAttr::CreateImplicit(Context));
19156 }
19157 }
19158
19159 if (ModulePrivateLoc.isValid()) {
19160 if (isMemberSpecialization)
19161 Diag(New->getLocation(), diag::err_module_private_specialization)
19162 << 2
19163 << FixItHint::CreateRemoval(ModulePrivateLoc);
19164 // __module_private__ does not apply to local classes. However, we only
19165 // diagnose this as an error when the declaration specifiers are
19166 // freestanding. Here, we just ignore the __module_private__.
19167 else if (!SearchDC->isFunctionOrMethod())
19168 New->setModulePrivate();
19169 }
19170
19171 // If this is a specialization of a member class (of a class template),
19172 // check the specialization.
19173 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
19174 Invalid = true;
19175
19176 // If we're declaring or defining a tag in function prototype scope in C,
19177 // note that this type can only be used within the function and add it to
19178 // the list of decls to inject into the function definition scope. However,
19179 // in C23 and later, while the type is only visible within the function, the
19180 // function can be called with a compatible type defined in the same TU, so
19181 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
19182 if ((Name || Kind == TagTypeKind::Enum) &&
19183 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
19184 if (getLangOpts().CPlusPlus) {
19185 // C++ [dcl.fct]p6:
19186 // Types shall not be defined in return or parameter types.
19187 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
19188 Diag(Loc, diag::err_type_defined_in_param_type)
19189 << Name;
19190 Invalid = true;
19191 }
19192 if (TUK == TagUseKind::Declaration)
19193 Invalid = true;
19194 } else if (!PrevDecl) {
19195 // In C23 mode, if the declaration is complete, we do not want to
19196 // diagnose.
19197 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
19198 Diag(Loc, diag::warn_decl_in_param_list)
19199 << Context.getCanonicalTagType(New);
19200 }
19201 }
19202
19203 if (Invalid)
19204 New->setInvalidDecl();
19205
19206 // Set the lexical context. If the tag has a C++ scope specifier, the
19207 // lexical context will be different from the semantic context.
19208 New->setLexicalDeclContext(CurContext);
19209
19210 // Mark this as a friend decl if applicable.
19211 // In Microsoft mode, a friend declaration also acts as a forward
19212 // declaration so we always pass true to setObjectOfFriendDecl to make
19213 // the tag name visible.
19214 if (TUK == TagUseKind::Friend)
19215 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
19216
19217 // Set the access specifier.
19218 if (!Invalid && SearchDC->isRecord())
19219 SetMemberAccessSpecifier(New, PrevDecl, AS);
19220
19221 // FIXME: An elaborated-type-specifier referring to an existing tag should
19222 // ideally not introduce a redeclaration. ActOnTag currently creates one, so
19223 // avoid diagnosing it as a redeclaration across module boundaries.
19224 //
19225 // See https://github.com/llvm/llvm-project/pull/194546 for full background.
19226 if (PrevDecl && TUK != TagUseKind::Reference)
19228
19229 if (TUK == TagUseKind::Definition) {
19230 if (!SkipBody || !SkipBody->ShouldSkip) {
19231 New->startDefinition();
19232 } else {
19233 New->setCompleteDefinition();
19234 New->demoteThisDefinitionToDeclaration();
19235 }
19236 }
19237
19238 ProcessDeclAttributeList(S, New, Attrs);
19240
19241 // If this has an identifier, add it to the scope stack.
19242 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
19243 // We might be replacing an existing declaration in the lookup tables;
19244 // if so, borrow its access specifier.
19245 if (PrevDecl)
19246 New->setAccess(PrevDecl->getAccess());
19247
19248 DeclContext *DC = New->getDeclContext()->getRedeclContext();
19250 if (Name) // can be null along some error paths
19251 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19252 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
19253 } else if (Name) {
19254 S = getNonFieldDeclScope(S);
19255 PushOnScopeChains(New, S, true);
19256 } else {
19257 CurContext->addDecl(New);
19258 }
19259
19260 // If this is the C FILE type, notify the AST context.
19261 if (IdentifierInfo *II = New->getIdentifier())
19262 if (!New->isInvalidDecl() &&
19263 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19264 II->isStr("FILE"))
19265 Context.setFILEDecl(New);
19266
19267 if (PrevDecl)
19268 mergeDeclAttributes(New, PrevDecl);
19269
19270 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
19273 }
19274
19275 // If there's a #pragma GCC visibility in scope, set the visibility of this
19276 // record.
19278
19279 // If this is not a definition, process API notes for it now.
19280 if (TUK != TagUseKind::Definition)
19282
19283 if (isMemberSpecialization && !New->isInvalidDecl())
19285
19286 OwnedDecl = true;
19287 // In C++, don't return an invalid declaration. We can't recover well from
19288 // the cases where we make the type anonymous.
19289 if (Invalid && getLangOpts().CPlusPlus) {
19290 if (New->isBeingDefined())
19291 if (auto RD = dyn_cast<RecordDecl>(New))
19292 RD->completeDefinition();
19293 return true;
19294 } else if (SkipBody && SkipBody->ShouldSkip) {
19295 return SkipBody->Previous;
19296 } else {
19297 return New;
19298 }
19299}
19300
19303 TagDecl *Tag = cast<TagDecl>(TagD);
19304
19305 // Enter the tag context.
19306 PushDeclContext(S, Tag);
19307
19309
19310 // If there's a #pragma GCC visibility in scope, set the visibility of this
19311 // record.
19313}
19314
19316 SkipBodyInfo &SkipBody) {
19317 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
19318 return false;
19319
19320 // Make the previous decl visible.
19322 CleanupMergedEnum(S, SkipBody.New);
19323 return true;
19324}
19325
19327 SourceLocation FinalLoc,
19328 bool IsFinalSpelledSealed,
19329 bool IsAbstract,
19330 SourceLocation LBraceLoc) {
19333
19334 FieldCollector->StartClass();
19335
19336 if (!Record->getIdentifier())
19337 return;
19338
19339 if (IsAbstract)
19340 Record->markAbstract();
19341
19342 if (FinalLoc.isValid()) {
19343 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
19344 IsFinalSpelledSealed
19345 ? FinalAttr::Keyword_sealed
19346 : FinalAttr::Keyword_final));
19347 }
19348
19349 // C++ [class]p2:
19350 // [...] The class-name is also inserted into the scope of the
19351 // class itself; this is known as the injected-class-name. For
19352 // purposes of access checking, the injected-class-name is treated
19353 // as if it were a public member name.
19354 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19355 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
19356 Record->getLocation(), Record->getIdentifier());
19357 InjectedClassName->setImplicit();
19358 InjectedClassName->setAccess(AS_public);
19359 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19360 InjectedClassName->setDescribedClassTemplate(Template);
19361
19362 PushOnScopeChains(InjectedClassName, S);
19363 assert(InjectedClassName->isInjectedClassName() &&
19364 "Broken injected-class-name");
19365}
19366
19368 SourceRange BraceRange) {
19370 TagDecl *Tag = cast<TagDecl>(TagD);
19371 Tag->setBraceRange(BraceRange);
19372
19373 // Make sure we "complete" the definition even it is invalid.
19374 if (Tag->isBeingDefined()) {
19375 assert(Tag->isInvalidDecl() && "We should already have completed it");
19376 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19377 RD->completeDefinition();
19378 }
19379
19380 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
19381 FieldCollector->FinishClass();
19382 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19383 auto *Def = RD->getDefinition();
19384 assert(Def && "The record is expected to have a completed definition");
19385 unsigned NumInitMethods = 0;
19386 for (auto *Method : Def->methods()) {
19387 if (!Method->getIdentifier())
19388 continue;
19389 if (Method->getName() == "__init")
19390 NumInitMethods++;
19391 }
19392 if (NumInitMethods > 1 || !Def->hasInitMethod())
19393 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
19394 }
19395
19396 // If we're defining a dynamic class in a module interface unit, we always
19397 // need to produce the vtable for it, even if the vtable is not used in the
19398 // current TU.
19399 //
19400 // The case where the current class is not dynamic is handled in
19401 // MarkVTableUsed.
19402 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19403 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
19404 }
19405
19406 // Exit this scope of this tag's definition.
19408
19409 if (getCurLexicalContext()->isObjCContainer() &&
19410 Tag->getDeclContext()->isFileContext())
19411 Tag->setTopLevelDeclInObjCContainer();
19412
19413 // Notify the consumer that we've defined a tag.
19414 if (!Tag->isInvalidDecl())
19415 Consumer.HandleTagDeclDefinition(Tag);
19416
19417 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19418 // from XLs and instead matches the XL #pragma pack(1) behavior.
19419 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19420 AlignPackStack.hasValue()) {
19421 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19422 // Only diagnose #pragma align(packed).
19423 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19424 return;
19425 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
19426 if (!RD)
19427 return;
19428 // Only warn if there is at least 1 bitfield member.
19429 if (llvm::any_of(RD->fields(),
19430 [](const FieldDecl *FD) { return FD->isBitField(); }))
19431 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
19432 }
19433}
19434
19437 TagDecl *Tag = cast<TagDecl>(TagD);
19438 Tag->setInvalidDecl();
19439
19440 // Make sure we "complete" the definition even it is invalid.
19441 if (Tag->isBeingDefined()) {
19442 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19443 RD->completeDefinition();
19444 }
19445
19446 // We're undoing ActOnTagStartDefinition here, not
19447 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19448 // the FieldCollector.
19449
19451}
19452
19453// Note that FieldName may be null for anonymous bitfields.
19455 const IdentifierInfo *FieldName,
19456 QualType FieldTy, bool IsMsStruct,
19457 Expr *BitWidth) {
19458 assert(BitWidth);
19459 if (BitWidth->containsErrors())
19460 return ExprError();
19461
19462 // C99 6.7.2.1p4 - verify the field type.
19463 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19464 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19465 // Handle incomplete and sizeless types with a specific error.
19466 if (RequireCompleteSizedType(FieldLoc, FieldTy,
19467 diag::err_field_incomplete_or_sizeless))
19468 return ExprError();
19469 if (FieldName)
19470 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
19471 << FieldName << FieldTy << BitWidth->getSourceRange();
19472 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
19473 << FieldTy << BitWidth->getSourceRange();
19475 return ExprError();
19476
19477 // If the bit-width is type- or value-dependent, don't try to check
19478 // it now.
19479 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19480 return BitWidth;
19481
19482 llvm::APSInt Value;
19483 ExprResult ICE =
19485 if (ICE.isInvalid())
19486 return ICE;
19487 BitWidth = ICE.get();
19488
19489 // Zero-width bitfield is ok for anonymous field.
19490 if (Value == 0 && FieldName)
19491 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
19492 << FieldName << BitWidth->getSourceRange();
19493
19494 if (Value.isSigned() && Value.isNegative()) {
19495 if (FieldName)
19496 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
19497 << FieldName << toString(Value, 10);
19498 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
19499 << toString(Value, 10);
19500 }
19501
19502 // The size of the bit-field must not exceed our maximum permitted object
19503 // size.
19504 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19505 return Diag(FieldLoc, diag::err_bitfield_too_wide)
19506 << !FieldName << FieldName << toString(Value, 10);
19507 }
19508
19509 if (!FieldTy->isDependentType()) {
19510 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
19511 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
19512 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
19513
19514 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19515 // ABI.
19516 bool CStdConstraintViolation =
19517 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19518 bool MSBitfieldViolation = Value.ugt(TypeStorageSize) && IsMsStruct;
19519 if (CStdConstraintViolation || MSBitfieldViolation) {
19520 unsigned DiagWidth =
19521 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19522 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
19523 << (bool)FieldName << FieldName << toString(Value, 10)
19524 << !CStdConstraintViolation << DiagWidth;
19525 }
19526
19527 // Warn on types where the user might conceivably expect to get all
19528 // specified bits as value bits: that's all integral types other than
19529 // 'bool'.
19530 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19531 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
19532 << FieldName << Value << (unsigned)TypeWidth;
19533 }
19534 }
19535
19536 if (isa<ConstantExpr>(BitWidth))
19537 return BitWidth;
19538 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
19539}
19540
19542 Declarator &D, Expr *BitfieldWidth) {
19543 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
19544 D, BitfieldWidth,
19545 /*InitStyle=*/ICIS_NoInit, AS_public);
19546 return Res;
19547}
19548
19550 SourceLocation DeclStart,
19551 Declarator &D, Expr *BitWidth,
19552 InClassInitStyle InitStyle,
19553 AccessSpecifier AS) {
19554 if (D.isDecompositionDeclarator()) {
19556 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19557 << Decomp.getSourceRange();
19558 return nullptr;
19559 }
19560
19561 const IdentifierInfo *II = D.getIdentifier();
19562 SourceLocation Loc = DeclStart;
19563 if (II) Loc = D.getIdentifierLoc();
19564
19566 QualType T = TInfo->getType();
19567 if (getLangOpts().CPlusPlus) {
19569
19572 D.setInvalidType();
19573 T = Context.IntTy;
19574 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19575 }
19576 }
19577
19579
19581 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19582 << getLangOpts().CPlusPlus17;
19585 diag::err_invalid_thread)
19587
19588 // Check to see if this name was declared as a member previously
19589 NamedDecl *PrevDecl = nullptr;
19590 LookupResult Previous(*this, II, Loc, LookupMemberName,
19592 LookupName(Previous, S);
19593 switch (Previous.getResultKind()) {
19596 PrevDecl = Previous.getAsSingle<NamedDecl>();
19597 break;
19598
19600 PrevDecl = Previous.getRepresentativeDecl();
19601 break;
19602
19606 break;
19607 }
19608 Previous.suppressDiagnostics();
19609
19610 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19611 // Maybe we will complain about the shadowed template parameter.
19613 // Just pretend that we didn't see the previous declaration.
19614 PrevDecl = nullptr;
19615 }
19616
19617 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19618 PrevDecl = nullptr;
19619
19620 bool Mutable
19621 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19622 SourceLocation TSSL = D.getBeginLoc();
19623 FieldDecl *NewFD
19624 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19625 TSSL, AS, PrevDecl, &D);
19626
19627 if (NewFD->isInvalidDecl())
19628 Record->setInvalidDecl();
19629
19631 NewFD->setModulePrivate();
19632
19633 if (NewFD->isInvalidDecl() && PrevDecl) {
19634 // Don't introduce NewFD into scope; there's already something
19635 // with the same name in the same scope.
19636 } else if (II) {
19637 PushOnScopeChains(NewFD, S);
19638 } else
19639 Record->addDecl(NewFD);
19640
19641 return NewFD;
19642}
19643
19645 TypeSourceInfo *TInfo,
19647 bool Mutable, Expr *BitWidth,
19648 InClassInitStyle InitStyle,
19649 SourceLocation TSSL,
19650 AccessSpecifier AS, NamedDecl *PrevDecl,
19651 Declarator *D) {
19652 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19653 bool InvalidDecl = false;
19654 if (D) InvalidDecl = D->isInvalidType();
19655
19656 // If we receive a broken type, recover by assuming 'int' and
19657 // marking this declaration as invalid.
19658 if (T.isNull() || T->containsErrors()) {
19659 InvalidDecl = true;
19660 T = Context.IntTy;
19661 }
19662
19663 QualType EltTy = Context.getBaseElementType(T);
19664 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19665 bool isIncomplete =
19666 LangOpts.HLSL // HLSL allows sizeless builtin types
19667 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19668 : RequireCompleteSizedType(Loc, EltTy,
19669 diag::err_field_incomplete_or_sizeless);
19670 if (isIncomplete) {
19671 // Fields of incomplete type force their record to be invalid.
19672 Record->setInvalidDecl();
19673 InvalidDecl = true;
19674 } else {
19675 NamedDecl *Def;
19676 EltTy->isIncompleteType(&Def);
19677 if (Def && Def->isInvalidDecl()) {
19678 Record->setInvalidDecl();
19679 InvalidDecl = true;
19680 }
19681 }
19682 }
19683
19684 // TR 18037 does not allow fields to be declared with address space
19685 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19686 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19687 Diag(Loc, diag::err_field_with_address_space);
19688 Record->setInvalidDecl();
19689 InvalidDecl = true;
19690 }
19691
19692 if (LangOpts.OpenCL) {
19693 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19694 // used as structure or union field: image, sampler, event or block types.
19695 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19696 T->isBlockPointerType()) {
19697 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19698 Record->setInvalidDecl();
19699 InvalidDecl = true;
19700 }
19701 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19702 // is enabled.
19703 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19704 "__cl_clang_bitfields", LangOpts)) {
19705 Diag(Loc, diag::err_opencl_bitfields);
19706 InvalidDecl = true;
19707 }
19708 }
19709
19710 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19711 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19712 T.hasQualifiers()) {
19713 InvalidDecl = true;
19714 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19715 }
19716
19717 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19718 // than a variably modified type.
19719 if (!InvalidDecl && T->isVariablyModifiedType()) {
19721 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19722 InvalidDecl = true;
19723 }
19724
19725 // Fields can not have abstract class types
19726 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19727 diag::err_abstract_type_in_decl,
19729 InvalidDecl = true;
19730
19731 if (InvalidDecl)
19732 BitWidth = nullptr;
19733 // If this is declared as a bit-field, check the bit-field.
19734 if (BitWidth) {
19735 BitWidth =
19736 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19737 if (!BitWidth) {
19738 InvalidDecl = true;
19739 BitWidth = nullptr;
19740 }
19741 }
19742
19743 // Check that 'mutable' is consistent with the type of the declaration.
19744 if (!InvalidDecl && Mutable) {
19745 unsigned DiagID = 0;
19746 if (T->isReferenceType())
19747 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19748 : diag::err_mutable_reference;
19749 else if (T.isConstQualified())
19750 DiagID = diag::err_mutable_const;
19751
19752 if (DiagID) {
19753 SourceLocation ErrLoc = Loc;
19754 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19755 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19756 Diag(ErrLoc, DiagID);
19757 if (DiagID != diag::ext_mutable_reference) {
19758 Mutable = false;
19759 InvalidDecl = true;
19760 }
19761 }
19762 }
19763
19764 // C++11 [class.union]p8 (DR1460):
19765 // At most one variant member of a union may have a
19766 // brace-or-equal-initializer.
19767 if (InitStyle != ICIS_NoInit)
19769
19770 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19771 BitWidth, Mutable, InitStyle);
19772 if (InvalidDecl)
19773 NewFD->setInvalidDecl();
19774
19775 if (!InvalidDecl)
19777
19778 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19779 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19780 Diag(Loc, diag::err_duplicate_member) << II;
19781 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19782 NewFD->setInvalidDecl();
19783 }
19784
19785 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19786 if (Record->isUnion()) {
19787 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19788 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19789
19790 // C++ [class.union]p1: An object of a class with a non-trivial
19791 // constructor, a non-trivial copy constructor, a non-trivial
19792 // destructor, or a non-trivial copy assignment operator
19793 // cannot be a member of a union, nor can an array of such
19794 // objects.
19795 if (CheckNontrivialField(NewFD))
19796 NewFD->setInvalidDecl();
19797 }
19798
19799 // C++ [class.union]p1: If a union contains a member of reference type,
19800 // the program is ill-formed, except when compiling with MSVC extensions
19801 // enabled.
19802 if (EltTy->isReferenceType()) {
19803 const bool HaveMSExt =
19804 getLangOpts().MicrosoftExt &&
19806
19807 Diag(NewFD->getLocation(),
19808 HaveMSExt ? diag::ext_union_member_of_reference_type
19809 : diag::err_union_member_of_reference_type)
19810 << NewFD->getDeclName() << EltTy;
19811 if (!HaveMSExt)
19812 NewFD->setInvalidDecl();
19813 }
19814 }
19815 }
19816
19817 // FIXME: We need to pass in the attributes given an AST
19818 // representation, not a parser representation.
19819 if (D) {
19820 // FIXME: The current scope is almost... but not entirely... correct here.
19821 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19822
19823 if (NewFD->hasAttrs())
19825 }
19826
19827 // In auto-retain/release, infer strong retension for fields of
19828 // retainable type.
19829 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19830 NewFD->setInvalidDecl();
19831
19832 if (T.isObjCGCWeak())
19833 Diag(Loc, diag::warn_attribute_weak_on_field);
19834
19835 // PPC MMA non-pointer types are not allowed as field types.
19836 if (Context.getTargetInfo().getTriple().isPPC64() &&
19837 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19838 NewFD->setInvalidDecl();
19839
19840 if (Context.getTargetInfo().hasAMDGPUTypes()) {
19841 if (!AMDGPU().checkAMDGPUTypeSupport(T, NewFD->getLocation()))
19842 NewFD->setInvalidDecl();
19843 }
19844
19845 NewFD->setAccess(AS);
19846 return NewFD;
19847}
19848
19850 assert(FD);
19851 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19852
19853 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19854 return false;
19855
19856 QualType EltTy = Context.getBaseElementType(FD->getType());
19857 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19858 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19859 // We check for copy constructors before constructors
19860 // because otherwise we'll never get complaints about
19861 // copy constructors.
19862
19864 // We're required to check for any non-trivial constructors. Since the
19865 // implicit default constructor is suppressed if there are any
19866 // user-declared constructors, we just need to check that there is a
19867 // trivial default constructor and a trivial copy constructor. (We don't
19868 // worry about move constructors here, since this is a C++98 check.)
19869 if (RDecl->hasNonTrivialCopyConstructor())
19871 else if (!RDecl->hasTrivialDefaultConstructor())
19873 else if (RDecl->hasNonTrivialCopyAssignment())
19875 else if (RDecl->hasNonTrivialDestructor())
19877
19878 if (member != CXXSpecialMemberKind::Invalid) {
19879 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19880 RDecl->hasObjectMember()) {
19881 // Objective-C++ ARC: it is an error to have a non-trivial field of
19882 // a union. However, system headers in Objective-C programs
19883 // occasionally have Objective-C lifetime objects within unions,
19884 // and rather than cause the program to fail, we make those
19885 // members unavailable.
19886 SourceLocation Loc = FD->getLocation();
19887 if (getSourceManager().isInSystemHeader(Loc)) {
19888 if (!FD->hasAttr<UnavailableAttr>())
19889 FD->addAttr(UnavailableAttr::CreateImplicit(
19890 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19891 return false;
19892 }
19893 }
19894
19895 Diag(FD->getLocation(),
19897 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19898 : diag::err_illegal_union_or_anon_struct_member)
19899 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19900 DiagnoseNontrivial(RDecl, member);
19901 return !getLangOpts().CPlusPlus11;
19902 }
19903 }
19904
19905 return false;
19906}
19907
19909 SmallVectorImpl<Decl *> &AllIvarDecls) {
19910 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19911 return;
19912
19913 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19914 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19915
19916 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19917 return;
19918 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19919 if (!ID) {
19920 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19921 if (!CD->IsClassExtension())
19922 return;
19923 }
19924 // No need to add this to end of @implementation.
19925 else
19926 return;
19927 }
19928 // All conditions are met. Add a new bitfield to the tail end of ivars.
19929 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19930 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19931 Expr *BitWidth =
19932 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19933
19934 Ivar = ObjCIvarDecl::Create(
19935 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19936 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19937 ObjCIvarDecl::Private, BitWidth, true);
19938 AllIvarDecls.push_back(Ivar);
19939}
19940
19941/// [class.dtor]p4:
19942/// At the end of the definition of a class, overload resolution is
19943/// performed among the prospective destructors declared in that class with
19944/// an empty argument list to select the destructor for the class, also
19945/// known as the selected destructor.
19946///
19947/// We do the overload resolution here, then mark the selected constructor in the AST.
19948/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19950 if (!Record->hasUserDeclaredDestructor()) {
19951 return;
19952 }
19953
19954 SourceLocation Loc = Record->getLocation();
19956
19957 for (auto *Decl : Record->decls()) {
19958 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19959 if (DD->isInvalidDecl())
19960 continue;
19961 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19962 OCS);
19963 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19964 }
19965 }
19966
19967 if (OCS.empty()) {
19968 return;
19969 }
19971 unsigned Msg = 0;
19972 OverloadCandidateDisplayKind DisplayKind;
19973
19974 switch (OCS.BestViableFunction(S, Loc, Best)) {
19975 case OR_Success:
19976 case OR_Deleted:
19977 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19978 break;
19979
19980 case OR_Ambiguous:
19981 Msg = diag::err_ambiguous_destructor;
19982 DisplayKind = OCD_AmbiguousCandidates;
19983 break;
19984
19986 Msg = diag::err_no_viable_destructor;
19987 DisplayKind = OCD_AllCandidates;
19988 break;
19989 }
19990
19991 if (Msg) {
19992 // OpenCL have got their own thing going with destructors. It's slightly broken,
19993 // but we allow it.
19994 if (!S.LangOpts.OpenCL) {
19995 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19996 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19997 Record->setInvalidDecl();
19998 }
19999 // It's a bit hacky: At this point we've raised an error but we want the
20000 // rest of the compiler to continue somehow working. However almost
20001 // everything we'll try to do with the class will depend on there being a
20002 // destructor. So let's pretend the first one is selected and hope for the
20003 // best.
20004 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
20005 }
20006}
20007
20008/// [class.mem.special]p5
20009/// Two special member functions are of the same kind if:
20010/// - they are both default constructors,
20011/// - they are both copy or move constructors with the same first parameter
20012/// type, or
20013/// - they are both copy or move assignment operators with the same first
20014/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
20016 CXXMethodDecl *M1,
20017 CXXMethodDecl *M2,
20019 // We don't want to compare templates to non-templates: See
20020 // https://github.com/llvm/llvm-project/issues/59206
20022 return bool(M1->getDescribedFunctionTemplate()) ==
20024 // FIXME: better resolve CWG
20025 // https://cplusplus.github.io/CWG/issues/2787.html
20026 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
20027 M2->getNonObjectParameter(0)->getType()))
20028 return false;
20029 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
20031 return false;
20032
20033 return true;
20034}
20035
20036/// [class.mem.special]p6:
20037/// An eligible special member function is a special member function for which:
20038/// - the function is not deleted,
20039/// - the associated constraints, if any, are satisfied, and
20040/// - no special member function of the same kind whose associated constraints
20041/// [CWG2595], if any, are satisfied is more constrained.
20045 SmallVector<bool, 4> SatisfactionStatus;
20046
20047 for (CXXMethodDecl *Method : Methods) {
20048 if (!Method->getTrailingRequiresClause())
20049 SatisfactionStatus.push_back(true);
20050 else {
20051 ConstraintSatisfaction Satisfaction;
20052 if (S.CheckFunctionConstraints(Method, Satisfaction))
20053 SatisfactionStatus.push_back(false);
20054 else
20055 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
20056 }
20057 }
20058
20059 for (size_t i = 0; i < Methods.size(); i++) {
20060 if (!SatisfactionStatus[i])
20061 continue;
20062 CXXMethodDecl *Method = Methods[i];
20063 CXXMethodDecl *OrigMethod = Method;
20064 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
20065 OrigMethod = cast<CXXMethodDecl>(MF);
20066
20068 bool AnotherMethodIsMoreConstrained = false;
20069 for (size_t j = 0; j < Methods.size(); j++) {
20070 if (i == j || !SatisfactionStatus[j])
20071 continue;
20072 CXXMethodDecl *OtherMethod = Methods[j];
20073 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
20074 OtherMethod = cast<CXXMethodDecl>(MF);
20075
20076 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
20077 CSM))
20078 continue;
20079
20081 if (!Other)
20082 continue;
20083 if (!Orig) {
20084 AnotherMethodIsMoreConstrained = true;
20085 break;
20086 }
20087 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
20088 AnotherMethodIsMoreConstrained)) {
20089 // There was an error with the constraints comparison. Exit the loop
20090 // and don't consider this function eligible.
20091 AnotherMethodIsMoreConstrained = true;
20092 }
20093 if (AnotherMethodIsMoreConstrained)
20094 break;
20095 }
20096 // FIXME: Do not consider deleted methods as eligible after implementing
20097 // DR1734 and DR1496.
20098 if (!AnotherMethodIsMoreConstrained) {
20099 Method->setIneligibleOrNotSelected(false);
20100 Record->addedEligibleSpecialMemberFunction(Method,
20101 1 << llvm::to_underlying(CSM));
20102 }
20103 }
20104}
20105
20108 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
20109 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
20110 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
20111 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
20112 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
20113
20114 for (auto *Decl : Record->decls()) {
20115 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
20116 if (!MD) {
20117 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
20118 if (FTD)
20119 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
20120 }
20121 if (!MD)
20122 continue;
20123 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
20124 if (CD->isInvalidDecl())
20125 continue;
20126 if (CD->isDefaultConstructor())
20127 DefaultConstructors.push_back(MD);
20128 else if (CD->isCopyConstructor())
20129 CopyConstructors.push_back(MD);
20130 else if (CD->isMoveConstructor())
20131 MoveConstructors.push_back(MD);
20132 } else if (MD->isCopyAssignmentOperator()) {
20133 CopyAssignmentOperators.push_back(MD);
20134 } else if (MD->isMoveAssignmentOperator()) {
20135 MoveAssignmentOperators.push_back(MD);
20136 }
20137 }
20138
20139 SetEligibleMethods(S, Record, DefaultConstructors,
20141 SetEligibleMethods(S, Record, CopyConstructors,
20143 SetEligibleMethods(S, Record, MoveConstructors,
20145 SetEligibleMethods(S, Record, CopyAssignmentOperators,
20147 SetEligibleMethods(S, Record, MoveAssignmentOperators,
20149}
20150
20151bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
20152 // Check to see if a FieldDecl is a pointer to a function.
20153 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
20154 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
20155 if (!FD) {
20156 // Check whether this is a forward declaration that was inserted by
20157 // Clang. This happens when a non-forward declared / defined type is
20158 // used, e.g.:
20159 //
20160 // struct foo {
20161 // struct bar *(*f)();
20162 // struct bar *(*g)();
20163 // };
20164 //
20165 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
20166 // incomplete definition.
20167 if (const auto *TD = dyn_cast<TagDecl>(D))
20168 return !TD->isCompleteDefinition();
20169 return false;
20170 }
20171 QualType FieldType = FD->getType().getDesugaredType(Context);
20172 if (isa<PointerType>(FieldType)) {
20173 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
20174 return PointeeType.getDesugaredType(Context)->isFunctionType();
20175 }
20176 // If a member is a struct entirely of function pointers, that counts too.
20177 if (const auto *Record = FieldType->getAsRecordDecl();
20178 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
20179 return true;
20180 return false;
20181 };
20182
20183 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
20184}
20185
20186void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
20187 ArrayRef<Decl *> Fields, SourceLocation LBrac,
20188 SourceLocation RBrac,
20189 const ParsedAttributesView &Attrs) {
20190 assert(EnclosingDecl && "missing record or interface decl");
20191
20192 // If this is an Objective-C @implementation or category and we have
20193 // new fields here we should reset the layout of the interface since
20194 // it will now change.
20195 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
20196 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
20197 switch (DC->getKind()) {
20198 default: break;
20199 case Decl::ObjCCategory:
20200 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
20201 break;
20202 case Decl::ObjCImplementation:
20203 Context.
20204 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
20205 break;
20206 }
20207 }
20208
20209 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
20210 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
20211
20212 // Start counting up the number of named members; make sure to include
20213 // members of anonymous structs and unions in the total.
20214 unsigned NumNamedMembers = 0;
20215 if (Record) {
20216 for (const auto *I : Record->decls()) {
20217 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
20218 if (IFD->getDeclName())
20219 ++NumNamedMembers;
20220 }
20221 }
20222
20223 // Verify that all the fields are okay.
20225 const FieldDecl *PreviousField = nullptr;
20226 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
20227 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
20228 FieldDecl *FD = cast<FieldDecl>(*i);
20229
20230 // Get the type for the field.
20231 const Type *FDTy = FD->getType().getTypePtr();
20232
20233 if (!FD->isAnonymousStructOrUnion()) {
20234 // Remember all fields written by the user.
20235 RecFields.push_back(FD);
20236 }
20237
20238 // If the field is already invalid for some reason, don't emit more
20239 // diagnostics about it.
20240 if (FD->isInvalidDecl()) {
20241 EnclosingDecl->setInvalidDecl();
20242 continue;
20243 }
20244
20245 // C99 6.7.2.1p2:
20246 // A structure or union shall not contain a member with
20247 // incomplete or function type (hence, a structure shall not
20248 // contain an instance of itself, but may contain a pointer to
20249 // an instance of itself), except that the last member of a
20250 // structure with more than one named member may have incomplete
20251 // array type; such a structure (and any union containing,
20252 // possibly recursively, a member that is such a structure)
20253 // shall not be a member of a structure or an element of an
20254 // array.
20255 bool IsLastField = (i + 1 == Fields.end());
20256 if (FDTy->isFunctionType()) {
20257 // Field declared as a function.
20258 Diag(FD->getLocation(), diag::err_field_declared_as_function)
20259 << FD->getDeclName();
20260 FD->setInvalidDecl();
20261 EnclosingDecl->setInvalidDecl();
20262 continue;
20263 } else if (FDTy->isIncompleteArrayType() &&
20264 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
20265 if (Record) {
20266 // Flexible array member.
20267 // Microsoft and g++ is more permissive regarding flexible array.
20268 // It will accept flexible array in union and also
20269 // as the sole element of a struct/class.
20270 unsigned DiagID = 0;
20271 if (!Record->isUnion() && !IsLastField) {
20272 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
20273 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20274 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
20275 FD->setInvalidDecl();
20276 EnclosingDecl->setInvalidDecl();
20277 continue;
20278 } else if (Record->isUnion())
20279 DiagID = getLangOpts().MicrosoftExt
20280 ? diag::ext_flexible_array_union_ms
20281 : diag::ext_flexible_array_union_gnu;
20282 else if (NumNamedMembers < 1)
20283 DiagID = getLangOpts().MicrosoftExt
20284 ? diag::ext_flexible_array_empty_aggregate_ms
20285 : diag::ext_flexible_array_empty_aggregate_gnu;
20286
20287 if (DiagID)
20288 Diag(FD->getLocation(), DiagID)
20289 << FD->getDeclName() << Record->getTagKind();
20290 // While the layout of types that contain virtual bases is not specified
20291 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20292 // virtual bases after the derived members. This would make a flexible
20293 // array member declared at the end of an object not adjacent to the end
20294 // of the type.
20295 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20296 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
20297 << FD->getDeclName() << Record->getTagKind();
20298 if (!getLangOpts().C99)
20299 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
20300 << FD->getDeclName() << Record->getTagKind();
20301
20302 // If the element type has a non-trivial destructor, we would not
20303 // implicitly destroy the elements, so disallow it for now.
20304 //
20305 // FIXME: GCC allows this. We should probably either implicitly delete
20306 // the destructor of the containing class, or just allow this.
20307 QualType BaseElem = Context.getBaseElementType(FD->getType());
20308 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20309 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
20310 << FD->getDeclName() << FD->getType();
20311 FD->setInvalidDecl();
20312 EnclosingDecl->setInvalidDecl();
20313 continue;
20314 }
20315 // Okay, we have a legal flexible array member at the end of the struct.
20316 Record->setHasFlexibleArrayMember(true);
20317 } else {
20318 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20319 // unless they are followed by another ivar. That check is done
20320 // elsewhere, after synthesized ivars are known.
20321 }
20322 } else if (!FDTy->isDependentType() &&
20323 (LangOpts.HLSL // HLSL allows sizeless builtin types
20325 diag::err_incomplete_type)
20327 FD->getLocation(), FD->getType(),
20328 diag::err_field_incomplete_or_sizeless))) {
20329 // Incomplete type
20330 FD->setInvalidDecl();
20331 EnclosingDecl->setInvalidDecl();
20332 continue;
20333 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20334 if (Record && RD->hasFlexibleArrayMember()) {
20335 // A type which contains a flexible array member is considered to be a
20336 // flexible array member.
20337 Record->setHasFlexibleArrayMember(true);
20338 if (!Record->isUnion()) {
20339 // If this is a struct/class and this is not the last element, reject
20340 // it. Note that GCC supports variable sized arrays in the middle of
20341 // structures.
20342 if (!IsLastField)
20343 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
20344 << FD->getDeclName() << FD->getType();
20345 else {
20346 // We support flexible arrays at the end of structs in
20347 // other structs as an extension.
20348 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
20349 << FD->getDeclName();
20350 }
20351 }
20352 }
20353 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
20355 diag::err_abstract_type_in_decl,
20357 // Ivars can not have abstract class types
20358 FD->setInvalidDecl();
20359 }
20360 if (Record && RD->hasObjectMember())
20361 Record->setHasObjectMember(true);
20362 if (Record && RD->hasVolatileMember())
20363 Record->setHasVolatileMember(true);
20364 } else if (FDTy->isObjCObjectType()) {
20365 /// A field cannot be an Objective-c object
20366 Diag(FD->getLocation(), diag::err_statically_allocated_object)
20368 QualType T = Context.getObjCObjectPointerType(FD->getType());
20369 FD->setType(T);
20370 } else if (Record && Record->isUnion() &&
20372 getSourceManager().isInSystemHeader(FD->getLocation()) &&
20373 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20375 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
20376 // For backward compatibility, fields of C unions declared in system
20377 // headers that have non-trivial ObjC ownership qualifications are marked
20378 // as unavailable unless the qualifier is explicit and __strong. This can
20379 // break ABI compatibility between programs compiled with ARC and MRR, but
20380 // is a better option than rejecting programs using those unions under
20381 // ARC.
20382 FD->addAttr(UnavailableAttr::CreateImplicit(
20383 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
20384 FD->getLocation()));
20385 } else if (getLangOpts().ObjC &&
20386 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20387 !Record->hasObjectMember()) {
20388 if (FD->getType()->isObjCObjectPointerType() ||
20389 FD->getType().isObjCGCStrong())
20390 Record->setHasObjectMember(true);
20391 else if (Context.getAsArrayType(FD->getType())) {
20392 QualType BaseType = Context.getBaseElementType(FD->getType());
20393 if (const auto *RD = BaseType->getAsRecordDecl();
20394 RD && RD->hasObjectMember())
20395 Record->setHasObjectMember(true);
20396 else if (BaseType->isObjCObjectPointerType() ||
20397 BaseType.isObjCGCStrong())
20398 Record->setHasObjectMember(true);
20399 }
20400 }
20401
20402 if (Record && !getLangOpts().CPlusPlus &&
20403 !shouldIgnoreForRecordTriviality(FD)) {
20404 QualType FT = FD->getType();
20406 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20408 Record->isUnion())
20409 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20410 }
20413 Record->setNonTrivialToPrimitiveCopy(true);
20414 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20415 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20416 }
20417 if (FD->hasAttr<ExplicitInitAttr>())
20418 Record->setHasUninitializedExplicitInitFields(true);
20419 if (FT.isDestructedType()) {
20420 Record->setNonTrivialToPrimitiveDestroy(true);
20421 Record->setParamDestroyedInCallee(true);
20422 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20423 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20424 }
20425
20426 if (const auto *RD = FT->getAsRecordDecl()) {
20427 if (RD->getArgPassingRestrictions() ==
20429 Record->setArgPassingRestrictions(
20431 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20432 Record->setArgPassingRestrictions(
20434 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20435 Q && Q.isAddressDiscriminated()) {
20436 Record->setArgPassingRestrictions(
20438 Record->setNonTrivialToPrimitiveCopy(true);
20439 }
20440 }
20441
20442 if (Record && FD->getType().isVolatileQualified())
20443 Record->setHasVolatileMember(true);
20444 bool ReportMSBitfieldStoragePacking =
20445 Record && PreviousField &&
20446 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
20447 Record->getLocation());
20448 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20449 return FD->isBitField() && !FD->getType()->isDependentType();
20450 };
20451
20452 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20453 IsNonDependentBitField(PreviousField)) {
20454 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
20455 CharUnits PreviousFieldStorageSize =
20456 Context.getTypeSizeInChars(PreviousField->getType());
20457 if (FDStorageSize != PreviousFieldStorageSize) {
20458 Diag(FD->getLocation(),
20459 diag::warn_ms_bitfield_mismatched_storage_packing)
20460 << FD << FD->getType() << FDStorageSize.getQuantity()
20461 << PreviousFieldStorageSize.getQuantity();
20462 Diag(PreviousField->getLocation(),
20463 diag::note_ms_bitfield_mismatched_storage_size_previous)
20464 << PreviousField << PreviousField->getType();
20465 }
20466 }
20467 // Keep track of the number of named members.
20468 if (FD->getIdentifier())
20469 ++NumNamedMembers;
20470 }
20471
20472 // Okay, we successfully defined 'Record'.
20473 if (Record) {
20474 bool Completed = false;
20475 if (S) {
20476 Scope *Parent = S->getParent();
20477 if (Parent && Parent->isTypeAliasScope() &&
20478 Parent->isTemplateParamScope())
20479 Record->setInvalidDecl();
20480 }
20481
20482 if (CXXRecord) {
20483 if (!CXXRecord->isInvalidDecl()) {
20484 // Set access bits correctly on the directly-declared conversions.
20486 I = CXXRecord->conversion_begin(),
20487 E = CXXRecord->conversion_end(); I != E; ++I)
20488 I.setAccess((*I)->getAccess());
20489 }
20490
20491 // Add any implicitly-declared members to this class.
20493
20494 if (!CXXRecord->isDependentType()) {
20495 if (!CXXRecord->isInvalidDecl()) {
20496 // If we have virtual base classes, we may end up finding multiple
20497 // final overriders for a given virtual function. Check for this
20498 // problem now.
20499 if (CXXRecord->getNumVBases()) {
20500 CXXFinalOverriderMap FinalOverriders;
20501 CXXRecord->getFinalOverriders(FinalOverriders);
20502
20503 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20504 MEnd = FinalOverriders.end();
20505 M != MEnd; ++M) {
20506 for (OverridingMethods::iterator SO = M->second.begin(),
20507 SOEnd = M->second.end();
20508 SO != SOEnd; ++SO) {
20509 assert(SO->second.size() > 0 &&
20510 "Virtual function without overriding functions?");
20511 if (SO->second.size() == 1)
20512 continue;
20513
20514 // C++ [class.virtual]p2:
20515 // In a derived class, if a virtual member function of a base
20516 // class subobject has more than one final overrider the
20517 // program is ill-formed.
20518 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
20519 << (const NamedDecl *)M->first << Record;
20520 Diag(M->first->getLocation(),
20521 diag::note_overridden_virtual_function);
20523 OM = SO->second.begin(),
20524 OMEnd = SO->second.end();
20525 OM != OMEnd; ++OM)
20526 Diag(OM->Method->getLocation(), diag::note_final_overrider)
20527 << (const NamedDecl *)M->first << OM->Method->getParent();
20528
20529 Record->setInvalidDecl();
20530 }
20531 }
20532 CXXRecord->completeDefinition(&FinalOverriders);
20533 Completed = true;
20534 }
20535 }
20536 ComputeSelectedDestructor(*this, CXXRecord);
20538 }
20539 }
20540
20541 if (!Completed)
20542 Record->completeDefinition();
20543
20544 // Handle attributes before checking the layout.
20546
20547 // Maybe randomize the record's decls. We automatically randomize a record
20548 // of function pointers, unless it has the "no_randomize_layout" attribute.
20549 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20550 !Record->isRandomized() && !Record->isUnion() &&
20551 (Record->hasAttr<RandomizeLayoutAttr>() ||
20552 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20553 EntirelyFunctionPointers(Record)))) {
20554 SmallVector<Decl *, 32> NewDeclOrdering;
20556 NewDeclOrdering))
20557 Record->reorderDecls(NewDeclOrdering);
20558 }
20559
20560 // We may have deferred checking for a deleted destructor. Check now.
20561 if (CXXRecord) {
20562 auto *Dtor = CXXRecord->getDestructor();
20563 if (Dtor && Dtor->isImplicit() &&
20565 CXXRecord->setImplicitDestructorIsDeleted();
20566 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20567 }
20568 }
20569
20570 if (Record->hasAttrs()) {
20572
20573 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20575 IA->getRange(), IA->getBestCase(),
20576 IA->getInheritanceModel());
20577 }
20578
20579 // Check if the structure/union declaration is a type that can have zero
20580 // size in C. For C this is a language extension, for C++ it may cause
20581 // compatibility problems.
20582 bool CheckForZeroSize;
20583 if (!getLangOpts().CPlusPlus) {
20584 CheckForZeroSize = true;
20585 } else {
20586 // For C++ filter out types that cannot be referenced in C code.
20588 CheckForZeroSize =
20589 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20590 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20591 CXXRecord->isCLike();
20592 }
20593 if (CheckForZeroSize) {
20594 bool ZeroSize = true;
20595 bool IsEmpty = true;
20596 unsigned NonBitFields = 0;
20597 for (RecordDecl::field_iterator I = Record->field_begin(),
20598 E = Record->field_end();
20599 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20600 IsEmpty = false;
20601 if (I->isUnnamedBitField()) {
20602 if (!I->isZeroLengthBitField())
20603 ZeroSize = false;
20604 } else {
20605 ++NonBitFields;
20606 QualType FieldType = I->getType();
20607 if (FieldType->isIncompleteType() ||
20608 !Context.getTypeSizeInChars(FieldType).isZero())
20609 ZeroSize = false;
20610 }
20611 }
20612
20613 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20614 // allowed in C++, but warn if its declaration is inside
20615 // extern "C" block.
20616 if (ZeroSize) {
20617 Diag(RecLoc, getLangOpts().CPlusPlus ?
20618 diag::warn_zero_size_struct_union_in_extern_c :
20619 diag::warn_zero_size_struct_union_compat)
20620 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20621 }
20622
20623 // Structs without named members are extension in C (C99 6.7.2.1p7),
20624 // but are accepted by GCC. In C2y, this became implementation-defined
20625 // (C2y 6.7.3.2p10).
20626 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20627 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20628 : diag::ext_no_named_members_in_struct_union)
20629 << Record->isUnion();
20630 }
20631 }
20632 } else {
20633 ObjCIvarDecl **ClsFields =
20634 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20635 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20636 ID->setEndOfDefinitionLoc(RBrac);
20637 // Add ivar's to class's DeclContext.
20638 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20639 ClsFields[i]->setLexicalDeclContext(ID);
20640 ID->addDecl(ClsFields[i]);
20641 }
20642 // Must enforce the rule that ivars in the base classes may not be
20643 // duplicates.
20644 if (ID->getSuperClass())
20645 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20646 } else if (ObjCImplementationDecl *IMPDecl =
20647 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20648 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20649 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20650 // Ivar declared in @implementation never belongs to the implementation.
20651 // Only it is in implementation's lexical context.
20652 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20653 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20654 RBrac);
20655 IMPDecl->setIvarLBraceLoc(LBrac);
20656 IMPDecl->setIvarRBraceLoc(RBrac);
20657 } else if (ObjCCategoryDecl *CDecl =
20658 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20659 // case of ivars in class extension; all other cases have been
20660 // reported as errors elsewhere.
20661 // FIXME. Class extension does not have a LocEnd field.
20662 // CDecl->setLocEnd(RBrac);
20663 // Add ivar's to class extension's DeclContext.
20664 // Diagnose redeclaration of private ivars.
20665 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20666 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20667 if (IDecl) {
20668 if (const ObjCIvarDecl *ClsIvar =
20669 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20670 Diag(ClsFields[i]->getLocation(),
20671 diag::err_duplicate_ivar_declaration);
20672 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20673 continue;
20674 }
20675 for (const auto *Ext : IDecl->known_extensions()) {
20676 if (const ObjCIvarDecl *ClsExtIvar
20677 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20678 Diag(ClsFields[i]->getLocation(),
20679 diag::err_duplicate_ivar_declaration);
20680 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20681 continue;
20682 }
20683 }
20684 }
20685 ClsFields[i]->setLexicalDeclContext(CDecl);
20686 CDecl->addDecl(ClsFields[i]);
20687 }
20688 CDecl->setIvarLBraceLoc(LBrac);
20689 CDecl->setIvarRBraceLoc(RBrac);
20690 }
20691 }
20692
20693 if (Record)
20695
20698}
20699
20700// Given an integral type, return the next larger integral type
20701// (or a NULL type of no such type exists).
20703 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20704 // enum checking below.
20705 assert((T->isIntegralType(Context) ||
20706 T->isEnumeralType()) && "Integral type required!");
20707 const unsigned NumTypes = 4;
20708 QualType SignedIntegralTypes[NumTypes] = {
20709 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20710 };
20711 QualType UnsignedIntegralTypes[NumTypes] = {
20712 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20713 Context.UnsignedLongLongTy
20714 };
20715
20716 // Compare value widths, not storage sizes: a _BitInt(33) is stored in 64
20717 // bits but a 64-bit standard type can still represent its incremented
20718 // value. C23 6.7.3.3p12 does not allow the widened type to be a
20719 // bit-precise type either.
20720 unsigned BitWidth = Context.getIntWidth(T);
20721 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20722 : UnsignedIntegralTypes;
20723 for (unsigned I = 0; I != NumTypes; ++I)
20724 if (Context.getTypeSize(Types[I]) > BitWidth)
20725 return Types[I];
20726
20727 return QualType();
20728}
20729
20731 EnumConstantDecl *LastEnumConst,
20732 SourceLocation IdLoc,
20733 IdentifierInfo *Id,
20734 Expr *Val) {
20735 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20736 llvm::APSInt EnumVal(IntWidth);
20737 QualType EltTy;
20738
20740 Val = nullptr;
20741
20742 if (Val)
20743 Val = DefaultLvalueConversion(Val).get();
20744
20745 if (Val) {
20746 if (Enum->isDependentType() || Val->isTypeDependent() ||
20747 Val->containsErrors())
20748 EltTy = Context.DependentTy;
20749 else {
20750 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20751 // underlying type, but do allow it in all other contexts.
20752 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20753 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20754 // constant-expression in the enumerator-definition shall be a converted
20755 // constant expression of the underlying type.
20756 EltTy = Enum->getIntegerType();
20758 Val, EltTy, EnumVal, CCEKind::Enumerator);
20759 if (Converted.isInvalid())
20760 Val = nullptr;
20761 else
20762 Val = Converted.get();
20763 } else if (!Val->isValueDependent() &&
20764 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20766 .get())) {
20767 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20768 } else {
20769 if (Enum->isComplete()) {
20770 EltTy = Enum->getIntegerType();
20771
20772 // In Obj-C and Microsoft mode, require the enumeration value to be
20773 // representable in the underlying type of the enumeration. In C++11,
20774 // we perform a non-narrowing conversion as part of converted constant
20775 // expression checking.
20776 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20777 if (Context.getTargetInfo()
20778 .getTriple()
20779 .isWindowsMSVCEnvironment()) {
20780 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20781 } else {
20782 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20783 }
20784 }
20785
20786 // Cast to the underlying type.
20787 Val = ImpCastExprToType(Val, EltTy,
20788 EltTy->isBooleanType() ? CK_IntegralToBoolean
20789 : CK_IntegralCast)
20790 .get();
20791 } else if (getLangOpts().CPlusPlus) {
20792 // C++11 [dcl.enum]p5:
20793 // If the underlying type is not fixed, the type of each enumerator
20794 // is the type of its initializing value:
20795 // - If an initializer is specified for an enumerator, the
20796 // initializing value has the same type as the expression.
20797 EltTy = Val->getType();
20798 } else {
20799 // C99 6.7.2.2p2:
20800 // The expression that defines the value of an enumeration constant
20801 // shall be an integer constant expression that has a value
20802 // representable as an int.
20803
20804 // Complain if the value is not representable in an int.
20805 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20806 Diag(IdLoc, getLangOpts().C23
20807 ? diag::warn_c17_compat_enum_value_not_int
20808 : diag::ext_c23_enum_value_not_int)
20809 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20810 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20811 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20812 // Force the type of the expression to 'int'.
20813 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20814 }
20815 EltTy = Val->getType();
20816 }
20817 }
20818 }
20819 }
20820
20821 if (!Val) {
20822 if (Enum->isDependentType())
20823 EltTy = Context.DependentTy;
20824 else if (!LastEnumConst) {
20825 // C++0x [dcl.enum]p5:
20826 // If the underlying type is not fixed, the type of each enumerator
20827 // is the type of its initializing value:
20828 // - If no initializer is specified for the first enumerator, the
20829 // initializing value has an unspecified integral type.
20830 //
20831 // GCC uses 'int' for its unspecified integral type, as does
20832 // C99 6.7.2.2p3.
20833 if (Enum->isFixed()) {
20834 EltTy = Enum->getIntegerType();
20835 }
20836 else {
20837 EltTy = Context.IntTy;
20838 }
20839 } else {
20840 // Assign the last value + 1.
20841 EnumVal = LastEnumConst->getInitVal();
20842 ++EnumVal;
20843 EltTy = LastEnumConst->getType();
20844
20845 // Check for overflow on increment.
20846 if (EnumVal < LastEnumConst->getInitVal()) {
20847 // C++0x [dcl.enum]p5:
20848 // If the underlying type is not fixed, the type of each enumerator
20849 // is the type of its initializing value:
20850 //
20851 // - Otherwise the type of the initializing value is the same as
20852 // the type of the initializing value of the preceding enumerator
20853 // unless the incremented value is not representable in that type,
20854 // in which case the type is an unspecified integral type
20855 // sufficient to contain the incremented value. If no such type
20856 // exists, the program is ill-formed.
20858 if (T.isNull() || Enum->isFixed()) {
20859 // There is no integral type larger enough to represent this
20860 // value. Complain, then allow the value to wrap around.
20861 EnumVal = LastEnumConst->getInitVal();
20862 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20863 ++EnumVal;
20864 if (Enum->isFixed())
20865 // When the underlying type is fixed, this is ill-formed.
20866 Diag(IdLoc, diag::err_enumerator_wrapped)
20867 << toString(EnumVal, 10)
20868 << EltTy;
20869 else
20870 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20871 << toString(EnumVal, 10);
20872 } else {
20873 EltTy = T;
20874 }
20875
20876 // Retrieve the last enumerator's value, extent that type to the
20877 // type that is supposed to be large enough to represent the incremented
20878 // value, then increment.
20879 EnumVal = LastEnumConst->getInitVal();
20880 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20881 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20882 ++EnumVal;
20883
20884 // If we're not in C++, diagnose the overflow of enumerator values,
20885 // which in C99 means that the enumerator value is not representable in
20886 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20887 // are representable in some larger integral type and we allow it in
20888 // older language modes as an extension.
20889 // Exclude fixed enumerators since they are diagnosed with an error for
20890 // this case.
20891 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20892 Diag(IdLoc, getLangOpts().C23
20893 ? diag::warn_c17_compat_enum_value_not_int
20894 : diag::ext_c23_enum_value_not_int)
20895 << 1 << toString(EnumVal, 10) << 1;
20896 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20897 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20898 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20899 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20900 : diag::ext_c23_enum_value_not_int)
20901 << 1 << toString(EnumVal, 10) << 1;
20902 }
20903 }
20904 }
20905
20906 if (!EltTy->isDependentType()) {
20907 // Make the enumerator value match the signedness and size of the
20908 // enumerator's type.
20909 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20910 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20911 }
20912
20913 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20914 Val, EnumVal);
20915}
20916
20918 SourceLocation IILoc) {
20919 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20921 return SkipBodyInfo();
20922
20923 // We have an anonymous enum definition. Look up the first enumerator to
20924 // determine if we should merge the definition with an existing one and
20925 // skip the body.
20926 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20928 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20929 if (!PrevECD)
20930 return SkipBodyInfo();
20931
20932 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20933 NamedDecl *Hidden;
20934 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20936 Skip.Previous = Hidden;
20937 return Skip;
20938 }
20939
20940 return SkipBodyInfo();
20941}
20942
20943Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20944 SourceLocation IdLoc, IdentifierInfo *Id,
20945 const ParsedAttributesView &Attrs,
20946 SourceLocation EqualLoc, Expr *Val,
20947 SkipBodyInfo *SkipBody) {
20948 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20949 EnumConstantDecl *LastEnumConst =
20950 cast_or_null<EnumConstantDecl>(lastEnumConst);
20951
20952 // The scope passed in may not be a decl scope. Zip up the scope tree until
20953 // we find one that is.
20954 S = getNonFieldDeclScope(S);
20955
20956 // Verify that there isn't already something declared with this name in this
20957 // scope.
20958 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20960 LookupName(R, S);
20961 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20962
20963 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20964 // Maybe we will complain about the shadowed template parameter.
20965 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20966 // Just pretend that we didn't see the previous declaration.
20967 PrevDecl = nullptr;
20968 }
20969
20970 // C++ [class.mem]p15:
20971 // If T is the name of a class, then each of the following shall have a name
20972 // different from T:
20973 // - every enumerator of every member of class T that is an unscoped
20974 // enumerated type
20975 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20977 DeclarationNameInfo(Id, IdLoc)))
20978 return nullptr;
20979
20981 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20982 if (!New)
20983 return nullptr;
20984
20985 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20986 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20987 // Check for other kinds of shadowing not already handled.
20988 CheckShadow(New, PrevDecl, R);
20989 }
20990
20991 // When in C++, we may get a TagDecl with the same name; in this case the
20992 // enum constant will 'hide' the tag.
20993 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20994 "Received TagDecl when not in C++!");
20995 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20996 if (isa<EnumConstantDecl>(PrevDecl))
20997 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20998 else
20999 Diag(IdLoc, diag::err_redefinition) << Id;
21000 notePreviousDefinition(PrevDecl, IdLoc);
21001 return nullptr;
21002 }
21003 }
21004
21005 // Process attributes.
21006 ProcessDeclAttributeList(S, New, Attrs);
21009
21010 // Register this decl in the current scope stack.
21011 New->setAccess(TheEnumDecl->getAccess());
21013
21015
21016 return New;
21017}
21018
21019// Returns true when the enum initial expression does not trigger the
21020// duplicate enum warning. A few common cases are exempted as follows:
21021// Element2 = Element1
21022// Element2 = Element1 + 1
21023// Element2 = Element1 - 1
21024// Where Element2 and Element1 are from the same enum.
21026 Expr *InitExpr = ECD->getInitExpr();
21027 if (!InitExpr)
21028 return true;
21029 InitExpr = InitExpr->IgnoreImpCasts();
21030
21031 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
21032 if (!BO->isAdditiveOp())
21033 return true;
21034 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
21035 if (!IL)
21036 return true;
21037 if (IL->getValue() != 1)
21038 return true;
21039
21040 InitExpr = BO->getLHS();
21041 }
21042
21043 // This checks if the elements are from the same enum.
21044 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
21045 if (!DRE)
21046 return true;
21047
21048 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
21049 if (!EnumConstant)
21050 return true;
21051
21053 Enum)
21054 return true;
21055
21056 return false;
21057}
21058
21059// Emits a warning when an element is implicitly set a value that
21060// a previous element has already been set to.
21062 EnumDecl *Enum, QualType EnumType) {
21063 // Avoid anonymous enums
21064 if (!Enum->getIdentifier())
21065 return;
21066
21067 // Only check for small enums.
21068 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
21069 return;
21070
21071 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
21072 return;
21073
21074 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
21075 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
21076
21077 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
21078
21079 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
21080 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
21081
21082 // Use int64_t as a key to avoid needing special handling for map keys.
21083 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
21084 llvm::APSInt Val = D->getInitVal();
21085 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
21086 };
21087
21088 DuplicatesVector DupVector;
21089 ValueToVectorMap EnumMap;
21090
21091 // Populate the EnumMap with all values represented by enum constants without
21092 // an initializer.
21093 for (auto *Element : Elements) {
21094 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
21095
21096 // Null EnumConstantDecl means a previous diagnostic has been emitted for
21097 // this constant. Skip this enum since it may be ill-formed.
21098 if (!ECD) {
21099 return;
21100 }
21101
21102 // Constants with initializers are handled in the next loop.
21103 if (ECD->getInitExpr())
21104 continue;
21105
21106 // Duplicate values are handled in the next loop.
21107 EnumMap.insert({EnumConstantToKey(ECD), ECD});
21108 }
21109
21110 if (EnumMap.size() == 0)
21111 return;
21112
21113 // Create vectors for any values that has duplicates.
21114 for (auto *Element : Elements) {
21115 // The last loop returned if any constant was null.
21117 if (!ValidDuplicateEnum(ECD, Enum))
21118 continue;
21119
21120 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
21121 if (Iter == EnumMap.end())
21122 continue;
21123
21124 DeclOrVector& Entry = Iter->second;
21125 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
21126 // Ensure constants are different.
21127 if (D == ECD)
21128 continue;
21129
21130 // Create new vector and push values onto it.
21131 auto Vec = std::make_unique<ECDVector>();
21132 Vec->push_back(D);
21133 Vec->push_back(ECD);
21134
21135 // Update entry to point to the duplicates vector.
21136 Entry = Vec.get();
21137
21138 // Store the vector somewhere we can consult later for quick emission of
21139 // diagnostics.
21140 DupVector.emplace_back(std::move(Vec));
21141 continue;
21142 }
21143
21144 ECDVector *Vec = cast<ECDVector *>(Entry);
21145 // Make sure constants are not added more than once.
21146 if (*Vec->begin() == ECD)
21147 continue;
21148
21149 Vec->push_back(ECD);
21150 }
21151
21152 // Emit diagnostics.
21153 for (const auto &Vec : DupVector) {
21154 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
21155
21156 // Emit warning for one enum constant.
21157 auto *FirstECD = Vec->front();
21158 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
21159 << FirstECD << toString(FirstECD->getInitVal(), 10)
21160 << FirstECD->getSourceRange();
21161
21162 // Emit one note for each of the remaining enum constants with
21163 // the same value.
21164 for (auto *ECD : llvm::drop_begin(*Vec))
21165 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
21166 << ECD << toString(ECD->getInitVal(), 10)
21167 << ECD->getSourceRange();
21168 }
21169}
21170
21171bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
21172 bool AllowMask) const {
21173 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
21174 assert(ED->isCompleteDefinition() && "expected enum definition");
21175
21176 auto R = FlagBitsCache.try_emplace(ED);
21177 llvm::APInt &FlagBits = R.first->second;
21178
21179 if (R.second) {
21180 for (auto *E : ED->enumerators()) {
21181 const auto &EVal = E->getInitVal();
21182 // Only single-bit enumerators introduce new flag values.
21183 if (EVal.isPowerOf2())
21184 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
21185 }
21186 }
21187
21188 // A value is in a flag enum if either its bits are a subset of the enum's
21189 // flag bits (the first condition) or we are allowing masks and the same is
21190 // true of its complement (the second condition). When masks are allowed, we
21191 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
21192 //
21193 // While it's true that any value could be used as a mask, the assumption is
21194 // that a mask will have all of the insignificant bits set. Anything else is
21195 // likely a logic error.
21196 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
21197 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
21198}
21199
21200// Emits a warning when a suspicious comparison operator is used along side
21201// binary operators in enum initializers.
21203 const EnumDecl *Enum) {
21204 bool HasBitwiseOp = false;
21205 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
21206
21207 // Iterate over all the enum values, gather suspisious comparison ops and
21208 // whether any enum initialisers contain a binary operator.
21209 for (const auto *ECD : Enum->enumerators()) {
21210 const Expr *InitExpr = ECD->getInitExpr();
21211 if (!InitExpr)
21212 continue;
21213
21214 const Expr *E = InitExpr->IgnoreParenImpCasts();
21215
21216 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
21217 BinaryOperatorKind Op = BinOp->getOpcode();
21218
21219 // Check for bitwise ops (<<, >>, &, |)
21220 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
21221 HasBitwiseOp = true;
21222 } else if (Op == BO_LT || Op == BO_GT) {
21223 // Check for the typo pattern (Comparison < or >)
21224 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
21225 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
21226 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
21227 if (IntLiteral->getValue() == 1)
21228 SuspiciousCompares.push_back(BinOp);
21229 }
21230 }
21231 }
21232 }
21233
21234 // If we found a bitwise op and some sus compares, iterate over the compares
21235 // and warn.
21236 if (HasBitwiseOp) {
21237 for (const auto *BinOp : SuspiciousCompares) {
21238 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
21241 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
21242
21243 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
21244 << BinOp->getOpcodeStr() << SuggestedOp;
21245
21246 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
21247 << SuggestedOp
21248 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
21249 }
21250 }
21251}
21252
21254 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
21255 const ParsedAttributesView &Attrs) {
21256 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
21257 CanQualType EnumType = Context.getCanonicalTagType(Enum);
21258
21259 ProcessDeclAttributeList(S, Enum, Attrs);
21261
21262 if (Enum->isDependentType()) {
21263 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
21264 EnumConstantDecl *ECD =
21265 cast_or_null<EnumConstantDecl>(Elements[i]);
21266 if (!ECD) continue;
21267
21268 ECD->setType(EnumType);
21269 }
21270
21271 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
21272 return;
21273 }
21274
21275 // Verify that all the values are okay, compute the size of the values, and
21276 // reverse the list.
21277 unsigned NumNegativeBits = 0;
21278 unsigned NumPositiveBits = 0;
21279 bool MembersRepresentableByInt =
21280 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
21281
21282 // Figure out the type that should be used for this enum.
21283 QualType BestType;
21284 unsigned BestWidth;
21285
21286 // C++0x N3000 [conv.prom]p3:
21287 // An rvalue of an unscoped enumeration type whose underlying
21288 // type is not fixed can be converted to an rvalue of the first
21289 // of the following types that can represent all the values of
21290 // the enumeration: int, unsigned int, long int, unsigned long
21291 // int, long long int, or unsigned long long int.
21292 // C99 6.4.4.3p2:
21293 // An identifier declared as an enumeration constant has type int.
21294 // The C99 rule is modified by C23.
21295 QualType BestPromotionType;
21296
21297 bool Packed = Enum->hasAttr<PackedAttr>();
21298 // -fshort-enums is the equivalent to specifying the packed attribute on all
21299 // enum definitions.
21300 if (LangOpts.ShortEnums)
21301 Packed = true;
21302
21303 // If the enum already has a type because it is fixed or dictated by the
21304 // target, promote that type instead of analyzing the enumerators.
21305 if (Enum->isComplete()) {
21306 BestType = Enum->getIntegerType();
21307 if (Context.isPromotableIntegerType(BestType))
21308 BestPromotionType = Context.getPromotedIntegerType(BestType);
21309 else
21310 BestPromotionType = BestType;
21311
21312 BestWidth = Context.getIntWidth(BestType);
21313 } else {
21314 bool EnumTooLarge = Context.computeBestEnumTypes(
21315 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21316 BestWidth = Context.getIntWidth(BestType);
21317 if (EnumTooLarge)
21318 Diag(Enum->getLocation(), diag::ext_enum_too_large);
21319 }
21320
21321 // Loop over all of the enumerator constants, changing their types to match
21322 // the type of the enum if needed.
21323 for (auto *D : Elements) {
21324 auto *ECD = cast_or_null<EnumConstantDecl>(D);
21325 if (!ECD) continue; // Already issued a diagnostic.
21326
21327 // C99 says the enumerators have int type, but we allow, as an
21328 // extension, the enumerators to be larger than int size. If each
21329 // enumerator value fits in an int, type it as an int, otherwise type it the
21330 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21331 // that X has type 'int', not 'unsigned'.
21332
21333 // Determine whether the value fits into an int.
21334 llvm::APSInt InitVal = ECD->getInitVal();
21335
21336 // If it fits into an integer type, force it. Otherwise force it to match
21337 // the enum decl type.
21338 QualType NewTy;
21339 unsigned NewWidth;
21340 bool NewSign;
21341 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21342 MembersRepresentableByInt) {
21343 // C23 6.7.3.3.3p15:
21344 // The enumeration member type for an enumerated type without fixed
21345 // underlying type upon completion is:
21346 // - int if all the values of the enumeration are representable as an
21347 // int; or,
21348 // - the enumerated type
21349 NewTy = Context.IntTy;
21350 NewWidth = Context.getTargetInfo().getIntWidth();
21351 NewSign = true;
21352 } else if (ECD->getType() == BestType) {
21353 // Already the right type!
21354 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21355 // C++ [dcl.enum]p4: Following the closing brace of an
21356 // enum-specifier, each enumerator has the type of its
21357 // enumeration.
21358 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21359 // with fixed underlying type is the enumerated type.
21360 ECD->setType(EnumType);
21361 continue;
21362 } else {
21363 NewTy = BestType;
21364 NewWidth = BestWidth;
21365 NewSign = BestType->isSignedIntegerOrEnumerationType();
21366 }
21367
21368 // Adjust the APSInt value.
21369 InitVal = InitVal.extOrTrunc(NewWidth);
21370 InitVal.setIsSigned(NewSign);
21371 ECD->setInitVal(Context, InitVal);
21372
21373 // Adjust the Expr initializer and type.
21374 if (ECD->getInitExpr() &&
21375 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
21376 ECD->setInitExpr(ImplicitCastExpr::Create(
21377 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
21378 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
21379 if (getLangOpts().CPlusPlus ||
21380 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21381 // C++ [dcl.enum]p4: Following the closing brace of an
21382 // enum-specifier, each enumerator has the type of its
21383 // enumeration.
21384 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21385 // with fixed underlying type is the enumerated type.
21386 ECD->setType(EnumType);
21387 else
21388 ECD->setType(NewTy);
21389 }
21390
21391 Enum->completeDefinition(BestType, BestPromotionType,
21392 NumPositiveBits, NumNegativeBits);
21393
21394 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
21396
21397 if (Enum->isClosedFlag()) {
21398 for (Decl *D : Elements) {
21399 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
21400 if (!ECD) continue; // Already issued a diagnostic.
21401
21402 llvm::APSInt InitVal = ECD->getInitVal();
21403 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21404 !IsValueInFlagEnum(Enum, InitVal, true))
21405 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
21406 << ECD << Enum;
21407 }
21408 }
21409
21410 // Now that the enum type is defined, ensure it's not been underaligned.
21411 if (Enum->hasAttrs())
21413}
21414
21416 SourceLocation EndLoc) {
21417
21419 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
21420 CurContext->addDecl(New);
21421 return New;
21422}
21423
21425 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
21426 CurContext->addDecl(New);
21427 PushDeclContext(S, New);
21429 PushCompoundScope(false);
21430 return New;
21431}
21432
21434 if (Statement)
21435 D->setStmt(Statement);
21439}
21440
21442 IdentifierInfo* AliasName,
21443 SourceLocation PragmaLoc,
21444 SourceLocation NameLoc,
21445 SourceLocation AliasNameLoc) {
21446 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
21448 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21450 AsmLabelAttr *Attr =
21451 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
21452
21453 // If a declaration that:
21454 // 1) declares a function or a variable
21455 // 2) has external linkage
21456 // already exists, add a label attribute to it.
21457 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21458 if (isDeclExternC(PrevDecl))
21459 PrevDecl->addAttr(Attr);
21460 else
21461 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
21462 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
21463 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21464 } else
21465 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
21466}
21467
21469 SourceLocation PragmaLoc,
21470 SourceLocation NameLoc) {
21471 NamedDecl *PrevDecl =
21473
21474 if (PrevDecl) {
21475 auto *Attr = WeakAttr::CreateImplicit(Context, PragmaLoc);
21476 if (checkWeakAttrCompatibility(*this, *PrevDecl, *Attr))
21477 PrevDecl->addAttr(Attr);
21478 } else {
21479 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
21480 }
21481}
21482
21484 IdentifierInfo* AliasName,
21485 SourceLocation PragmaLoc,
21486 SourceLocation NameLoc,
21487 SourceLocation AliasNameLoc) {
21488 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
21490 WeakInfo W = WeakInfo(Name, NameLoc);
21491
21492 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21493 if (!PrevDecl->hasAttr<AliasAttr>())
21494 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
21496 } else {
21497 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
21498 }
21499}
21500
21502 bool Final) {
21503 assert(FD && "Expected non-null FunctionDecl");
21504
21505 // Templates are emitted when they're instantiated.
21506 if (FD->isDependentContext())
21508
21509 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21510 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21511 FD->hasAttr<SYCLExternalAttr>()))
21513
21514 // Check whether this function is an externally visible definition.
21515 auto IsEmittedForExternalSymbol = [this, FD]() {
21516 // We have to check the GVA linkage of the function's *definition* -- if we
21517 // only have a declaration, we don't know whether or not the function will
21518 // be emitted, because (say) the definition could include "inline".
21519 const FunctionDecl *Def = FD->getDefinition();
21520
21521 // We can't compute linkage when we skip function bodies.
21522 return Def && !Def->hasSkippedBody() &&
21524 getASTContext().GetGVALinkageForFunction(Def));
21525 };
21526
21527 if (LangOpts.OpenMPIsTargetDevice) {
21528 // In OpenMP device mode we will not emit host only functions, or functions
21529 // we don't need due to their linkage.
21530 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21531 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21532 // DevTy may be changed later by
21533 // #pragma omp declare target to(*) device_type(*).
21534 // Therefore DevTy having no value does not imply host. The emission status
21535 // will be checked again at the end of compilation unit with Final = true.
21536 if (DevTy)
21537 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21539 // If we have an explicit value for the device type, or we are in a target
21540 // declare context, we need to emit all extern and used symbols.
21541 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21542 if (IsEmittedForExternalSymbol())
21544 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21545 // we'll omit it.
21546 if (Final)
21548 } else if (LangOpts.OpenMP > 45) {
21549 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21550 // function. In 5.0, no_host was introduced which might cause a function to
21551 // be omitted.
21552 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21553 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21554 if (DevTy)
21555 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21557 }
21558
21559 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21561
21562 if (LangOpts.CUDA) {
21563 // When compiling for device, host functions are never emitted. Similarly,
21564 // when compiling for host, device and global functions are never emitted.
21565 // (Technically, we do emit a host-side stub for global functions, but this
21566 // doesn't count for our purposes here.)
21568 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21570 if (!LangOpts.CUDAIsDevice &&
21573
21574 if (IsEmittedForExternalSymbol())
21576 }
21577
21578 // Otherwise, the function is known-emitted if it's in our set of
21579 // known-emitted functions.
21581}
21582
21584 // Host-side references to a __global__ function refer to the stub, so the
21585 // function itself is never emitted and therefore should not be marked.
21586 // If we have host fn calls kernel fn calls host+device, the HD function
21587 // does not get instantiated on the host. We model this by omitting at the
21588 // call to the kernel from the callgraph. This ensures that, when compiling
21589 // for host, only HD functions actually called from the host get marked as
21590 // known-emitted.
21591 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21593}
21594
21596 SourceLocation NewDefinitionLoc,
21597 NamedDecl **Suggested, bool &Visible) {
21598 Visible = hasVisibleDefinition(D, Suggested);
21599 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21600 // for declaratins which is attached to named modules.
21601 // We only did this if the current module is named module as we have better
21602 // diagnostics for declarations in global module and named modules.
21603 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21604 D->isInNamedModule())
21605 return false;
21606 // The redefinition of D in the **current** TU is allowed if D is invisible or
21607 // D is defined in the global module of other module units or D is defined in
21608 // the same header in a different module.
21609 return D->isInAnotherModuleUnit() || !Visible ||
21610 isFromSameSingleIncludeHeader(D, NewDefinitionLoc);
21611}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition Decl.cpp:2209
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines helper utilities for supporting the HLSL runtime environment.
static const Decl * getCanonicalDecl(const Decl *D)
Result
Implement __builtin_bit_cast and related operations.
#define CC_VLS_CASE(ABI_VLEN)
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:82
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.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:186
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
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:180
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool isMainVar(DeclarationName Name, VarDecl *VD)
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition SemaDecl.cpp:235
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND)
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition SemaDecl.cpp:847
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
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...
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
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...
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
static NestedNameSpecifier synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition SemaDecl.cpp:611
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND)
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
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...
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From, Sema &S)
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
static bool checkWeakAttrCompatibility(Sema &S, const NamedDecl &ND, const WeakAttr &Attr)
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...
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
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 ...
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...
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...
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
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 ...
OpenCLParamType
@ InvalidAddrSpacePtrKernelParam
@ ValidKernelParam
@ InvalidKernelParam
@ RecordKernelParam
@ PtrKernelParam
@ PtrPtrKernelParam
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const ValueDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
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:
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition SemaDecl.cpp:630
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...
static bool shouldConsiderLinkage(const VarDecl *VD)
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
static void checkInheritableAttr(Sema &S, NamedDecl &ND)
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
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:
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition SemaDecl.cpp:862
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
@ SDK_StructuredBinding
@ SDK_Field
@ SDK_Global
@ SDK_Local
@ SDK_Typedef
@ SDK_StaticMember
@ SDK_Using
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
static void CheckForComparisonInEnumInitializer(SemaBase &Sema, const EnumDecl *Enum)
static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
static void checkWeakAttr(Sema &S, NamedDecl &ND)
static void checkModularFormatAttr(Sema &S, NamedDecl &ND)
static void checkSelectAnyAttr(Sema &S, NamedDecl &ND)
static bool isImplicitInstantiation(NamedDecl *D)
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
static bool looksMutable(QualType T, const ASTContext &Ctx)
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From, F &&propagator)
static const NamedDecl * getDefinition(const Decl *D)
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...
static bool hasDeducedAuto(DeclaratorDecl *DD)
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
static QualType getCoreType(QualType Ty)
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, AvailabilityMergeKind AMK)
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
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...
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
static bool isSYCLAddressSpace(LangAS AS)
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
static void checkAliasAttr(Sema &S, NamedDecl &ND)
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...
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
static bool isAttributeTargetADefinition(Decl *D)
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
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...
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
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 for SYCL constructs.
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)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
@ GE_None
No error.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_type
Missing a type.
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
SourceManager & getSourceManager()
Definition ASTContext.h:917
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
IdentifierTable & Idents
Definition ASTContext.h:856
const LangOptions & getLangOpts() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const VariableArrayType * getAsVariableArrayType(QualType T) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:975
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
@ GE_Missing_type
Missing a type.
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3605
Wrapper for source info for arrays.
Definition TypeLoc.h:1808
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1810
Expr * getSizeExpr() const
Definition TypeLoc.h:1830
TypeLoc getElementLoc() const
Definition TypeLoc.h:1838
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1818
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
bool isInherited() const
Definition Attr.h:101
bool isImplicit() const
Returns true if the attribute has been implicitly created instead of explicitly written by the user.
Definition Attr.h:105
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition Attr.h:106
SourceLocation getLocation() const
Definition Attr.h:99
bool isStandardAttributeSyntax() const
The attribute is spelled [[]] in either C or C++ mode, including standard attributes spelled with a k...
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition ParsedAttr.h:635
AttributeFactory & getFactory() const
Definition ParsedAttr.h:731
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4555
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4543
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4086
Expr * getLHS() const
Definition Expr.h:4136
StringRef getOpcodeStr() const
Definition Expr.h:4152
Expr * getRHS() const
Definition Expr.h:4138
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4227
A binding in a decomposition declaration.
Definition DeclCXX.h:4215
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4814
bool doesNotEscape() const
Definition Decl.h:4965
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:237
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:384
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
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:3058
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(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3018
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2977
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3283
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, const AssociatedConstraint &TrailingRequiresClause={}, const CXXDeductionGuideDecl *SourceDG=nullptr, SourceDeductionGuideKind SK=SourceDeductionGuideKind::None)
Definition DeclCXX.cpp:2383
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3158
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:2150
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:2719
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition DeclCXX.cpp:2805
bool isVirtual() const
Definition DeclCXX.h:2205
CXXSpecialMemberKind getSpecialMemberKind() const
Definition DeclCXX.h:2229
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2504
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2328
bool isConst() const
Definition DeclCXX.h:2202
bool isStatic() const
Definition DeclCXX.cpp:2417
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2263
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
base_class_iterator bases_end()
Definition DeclCXX.h:618
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1382
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1578
base_class_range bases()
Definition DeclCXX.h:609
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
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:616
capture_const_range captures() const
Definition DeclCXX.h:1107
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1158
bool hasDefinition() const
Definition DeclCXX.h:562
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2054
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2154
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1069
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1129
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2058
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:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3195
bool isCallToStdMove() const
Definition Expr.cpp:3679
Expr * getCallee()
Definition Expr.h:3138
arg_range arguments()
Definition Expr.h:3243
CastKind getCastKind() const
Definition Expr.h:3768
Expr * getSubExpr()
Definition Expr.h:3774
static CharSourceRange getCharRange(SourceRange R)
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
Declaration of a class template.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
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:336
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:376
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
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)
DeclListNode::iterator iterator
Definition DeclBase.h:1409
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2279
bool isFileContext() const
Definition DeclBase.h:2217
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2627
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool isClosure() const
Definition DeclBase.h:2159
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2142
bool isNamespace() const
Definition DeclBase.h:2239
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
bool isTranslationUnit() const
Definition DeclBase.h:2222
bool isRecord() const
Definition DeclBase.h:2226
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2423
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2181
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2119
DeclContext * getNonTransparentContext()
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
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:64
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1294
ValueDecl * getDecl()
Definition Expr.h:1362
SourceLocation getBeginLoc() const
Definition Expr.h:1373
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:658
bool isModulePrivateSpecified() const
Definition DeclSpec.h:839
static const TST TST_typeof_unqualType
Definition DeclSpec.h:282
bool hasAutoTypeSpec() const
Definition DeclSpec.h:583
static const TST TST_typename
Definition DeclSpec.h:279
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:637
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:237
void ClearStorageClassSpecs()
Definition DeclSpec.h:503
bool isNoreturnSpecified() const
Definition DeclSpec.h:671
TST getTypeSpecType() const
Definition DeclSpec.h:525
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:498
SCS getStorageClassSpec() const
Definition DeclSpec.h:489
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:852
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:563
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:562
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:719
static const TST TST_interface
Definition DeclSpec.h:277
static const TST TST_typeofExpr
Definition DeclSpec.h:281
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:605
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:718
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:672
bool isExternInLinkageSpec() const
Definition DeclSpec.h:493
static const TST TST_union
Definition DeclSpec.h:275
SCS
storage-class-specifier
Definition DeclSpec.h:224
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:664
static const TST TST_int
Definition DeclSpec.h:258
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:840
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:535
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:798
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:490
ParsedAttributes & getAttributes()
Definition DeclSpec.h:883
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:634
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:606
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:665
Expr * getRepAsExpr() const
Definition DeclSpec.h:543
static const TST TST_enum
Definition DeclSpec.h:274
static const TST TST_decltype
Definition DeclSpec.h:284
static bool isDeclRep(TST T)
Definition DeclSpec.h:456
bool isInlineSpecified() const
Definition DeclSpec.h:647
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:607
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:283
static const TST TST_class
Definition DeclSpec.h:278
TypeSpecifierType TST
Definition DeclSpec.h:250
static const TST TST_void
Definition DeclSpec.h:252
void ClearConstexprSpec()
Definition DeclSpec.h:851
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:534
static const TST TST_atomic
Definition DeclSpec.h:294
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:499
Decl * getRepAsDecl() const
Definition DeclSpec.h:539
static const TST TST_unspecified
Definition DeclSpec.h:251
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:609
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:659
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:846
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:570
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:802
static const TSCS TSCS_thread_local
Definition DeclSpec.h:240
static const TST TST_error
Definition DeclSpec.h:304
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclSpec.h:654
bool isTypeSpecOwned() const
Definition DeclSpec.h:529
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:650
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:610
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:608
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:831
bool hasExplicitSpecifier() const
Definition DeclSpec.h:661
bool hasConstexprSpecifier() const
Definition DeclSpec.h:847
static const TST TST_typeofType
Definition DeclSpec.h:280
static const TST TST_auto
Definition DeclSpec.h:291
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:842
static const TST TST_struct
Definition DeclSpec.h:276
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:1078
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1093
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:344
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1243
bool isFromGlobalModule() const
Whether this declaration comes from global module.
T * getAttr() const
Definition DeclBase.h:581
bool hasAttrs() const
Definition DeclBase.h:526
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:528
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition DeclBase.h:783
bool isInNamedModule() const
Whether this declaration comes from a named module.
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition DeclBase.h:1168
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:178
void setTopLevelDeclInObjCContainer(bool V=true)
Definition DeclBase.h:646
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:910
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1236
@ FOK_None
Not a friend object.
Definition DeclBase.h:1234
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1235
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:604
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
void dropAttrs()
@ 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:1197
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2843
bool isInvalidDecl() const
Definition DeclBase.h:596
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1186
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:602
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:579
DeclContext * getDeclContext()
Definition DeclBase.h:456
attr_range attrs() const
Definition DeclBase.h:543
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void dropAttr()
Definition DeclBase.h:564
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:385
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition Decl.cpp:1638
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1252
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
Kind getKind() const
Definition DeclBase.h:450
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
bool isAnyOperatorDelete() const
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
bool isEmpty() const
Evaluates true when this declaration name is empty.
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:781
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:823
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition Decl.cpp:2066
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2070
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2004
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:832
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:856
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:815
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2016
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:838
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:2050
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1955
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2511
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2453
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2102
Expr * getAsmLabel() const
Definition DeclSpec.h:2757
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2796
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2738
void setRedeclaration(bool Val)
Definition DeclSpec.h:2819
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2391
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2394
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2139
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2688
void takeAttributesAppending(ParsedAttributes &attrs)
takeAttributesAppending - Takes attributes from the given ParsedAttributes set and add them to this d...
Definition DeclSpec.h:2731
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2768
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2718
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2449
bool isRedeclaration() const
Definition DeclSpec.h:2820
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2741
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2123
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2138
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:412
bool isFunctionDefinition() const
Definition DeclSpec.h:2792
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2121
bool hasInitializer() const
Definition DeclSpec.h:2801
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2788
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2117
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2408
bool isInvalidType() const
Definition DeclSpec.h:2769
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:400
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2137
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2381
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2804
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:391
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2109
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2542
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2385
A decomposition declaration.
Definition DeclCXX.h:4279
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, SourceLocation RSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3742
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1843
SourceRange getSourceRange() const
Definition DeclSpec.h:1891
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1889
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2544
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:241
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:992
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3562
llvm::APSInt getInitVal() const
Definition Decl.h:3582
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5797
const Expr * getInitExpr() const
Definition Decl.h:3580
Represents an enum.
Definition Decl.h:4150
enumerator_range enumerators() const
Definition Decl.h:4296
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4368
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4332
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4335
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4382
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5155
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5194
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4377
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5169
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4318
void setEnumKeyRange(SourceRange Range)
Definition Decl.h:4230
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4323
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
This represents one expression.
Definition Expr.h:113
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:178
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3126
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3122
bool isConstantInitializer(ASTContext &Ctx, bool ForRef=false, const Expr **Culprit=nullptr) const
Returns true if this expression can be emitted to IR as a constant, and thus can be used as a constan...
Definition Expr.cpp:3383
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3106
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:145
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3299
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3402
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4790
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3535
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:4775
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4836
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5930
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
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:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
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:103
Represents a function declaration or definition.
Definition Decl.h:2059
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2820
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2303
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2932
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2603
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4254
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3780
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4247
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4242
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3345
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2428
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2832
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2811
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4076
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3809
param_iterator param_end()
Definition Decl.h:2918
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3056
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2826
QualType getReturnType() const
Definition Decl.h:2980
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3753
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2516
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2504
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3661
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4362
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2575
void setWillHaveBody(bool V=true)
Definition Decl.h:2817
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions:
Definition Decl.h:2723
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2570
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4372
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3794
param_iterator param_begin()
Definition Decl.h:2917
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2958
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2440
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2667
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3273
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3422
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4306
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:3023
bool isStatic() const
Definition Decl.h:3064
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4595
void setTrivial(bool IT)
Definition Decl.h:2505
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4193
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2597
bool isDeletedAsWritten() const
Definition Decl.h:2671
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2480
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3665
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2484
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2555
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2476
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2810
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2396
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3415
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:3051
bool param_empty() const
Definition Decl.h:2916
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3215
void setRangeEnd(SourceLocation E)
Definition Decl.h:2332
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3749
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2512
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2548
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4618
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:3068
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4187
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2600
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4466
void setDefaulted(bool D=true)
Definition Decl.h:2513
bool isConsteval() const
Definition Decl.h:2609
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:2997
void setBody(Stmt *B)
Definition Decl.cpp:3283
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3679
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3161
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2586
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4214
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3873
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2325
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3191
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2562
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:3238
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition Decl.h:3034
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3735
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2816
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5352
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5384
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:6095
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5216
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
unsigned getNumParams() const
Definition TypeBase.h:5694
QualType getParamType(unsigned i) const
Definition TypeBase.h:5696
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5913
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5729
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5820
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5705
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5701
Declaration of a template function.
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.
Wrapper for source info for functions.
Definition TypeLoc.h:1675
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4723
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4835
CallingConv getCC() const
Definition TypeBase.h:4782
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4801
unsigned getRegParm() const
Definition TypeBase.h:4775
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4771
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4794
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4815
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4829
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4612
ExtInfo getExtInfo() const
Definition TypeBase.h:4968
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3849
unsigned getRegParmType() const
Definition TypeBase.h:4955
CallingConv getCallConv() const
Definition TypeBase.h:4967
QualType getReturnType() const
Definition TypeBase.h:4952
bool getCmseNSCallAttr() const
Definition TypeBase.h:4966
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.
StringRef getName() const
Return the actual identifier string.
iterator - Iterate over the decls of a specified declaration name.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2106
Represents a C array with an unspecified size.
Definition TypeBase.h:4007
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3606
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5824
void setInherited(bool I)
Definition Attr.h:163
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2613
child_range children()
Definition Expr.h:5552
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...
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.
@ 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:985
Represents the declaration of a label.
Definition Decl.h:525
bool isResolvedMSAsmLabel() const
Definition Decl.h:560
LabelStmt * getStmt() const
Definition Decl.h:549
bool isMSAsmLabel() const
Definition Decl.h:559
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
Definition ExprCXX.h:2088
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
FPExceptionModeKind getDefaultExceptionMode() const
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
bool isCompatibleWithMSVC() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
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:1437
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
Definition Lexer.cpp:1381
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3045
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3313
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
bool isAmbiguous() const
Definition Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
iterator end() const
Definition Lookup.h:359
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.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3495
Expr * getBase() const
Definition Expr.h:3489
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
Describes a module or submodule.
Definition Module.h:340
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:346
Module * Parent
The parent of this module.
Definition Module.h:389
bool isPrivateModule() const
Definition Module.h:451
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:869
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:885
bool isModulePartition() const
Is this a module partition.
Definition Module.h:874
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:441
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:241
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:426
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:943
@ ClassId_NSObject
Definition NSAPI.h:30
This represents a decl that may have a name.
Definition Decl.h:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
bool isLinkageValid() const
True if the computed linkage is valid.
Definition Decl.cpp:1086
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1096
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:445
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition Decl.h:480
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:430
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition Decl.cpp:1872
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:718
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1944
bool isExternallyVisible() const
Definition Decl.h:434
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition Decl.cpp:1133
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:398
Represent a C++ namespace.
Definition Decl.h:593
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:644
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.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static constexpr NestedNameSpecifier getGlobal()
bool containsErrors() const
Whether this nested name specifier contains an error.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2335
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition DeclObjC.h:2781
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:954
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition DeclObjC.cpp:78
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2603
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
known_extensions_range known_extensions() const
Definition DeclObjC.h:1768
Wrapper for source info for ObjC interfaces.
Definition TypeLoc.h:1303
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
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)
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
param_const_iterator param_end() const
Definition DeclObjC.h:361
param_const_iterator param_begin() const
Definition DeclObjC.h:357
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:352
bool isOptional() const
Definition DeclObjC.h:508
ParmVarDecl *const * param_iterator
Definition DeclObjC.h:353
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition TypeLoc.h:895
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(DeclGroupRef P)
Definition Ownership.h:61
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:1164
@ CSK_Normal
Normal lookup.
Definition Overload.h:1168
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1380
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.
MapType::iterator iterator
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1446
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1459
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1442
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3383
Represents a parameter to a function.
Definition Decl.h:1820
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1884
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1853
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1912
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:2948
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2971
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
static const ParsedAttributesView & none()
Definition ParsedAttr.h:830
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:910
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:950
AttributePool & getPool() const
Definition ParsedAttr.h:957
PipeType - OpenCL20.
Definition TypeBase.h:8275
Pointer-authentication qualifiers.
Definition TypeBase.h:153
bool isAddressDiscriminated() const
Definition TypeBase.h:266
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1525
Wrapper for source info for pointers.
Definition TypeLoc.h:1544
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
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 TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8530
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8524
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:85
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:3151
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:194
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1230
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
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:3217
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8446
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8572
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:79
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8486
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8498
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8540
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:3201
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition TypeBase.h:1449
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8519
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8567
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1841
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
bool isCanonical() const
Definition TypeBase.h:8503
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1325
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1458
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2916
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition TypeBase.h:1509
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition TypeBase.h:1514
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:73
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8386
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8393
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4984
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
bool hasConst() const
Definition TypeBase.h:458
bool hasVolatile() const
Definition TypeBase.h:468
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
bool empty() const
Definition TypeBase.h:648
static std::string getAddrSpaceAsString(LangAS AS)
Represents a struct/union/class.
Definition Decl.h:4464
field_range fields() const
Definition Decl.h:4667
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5313
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4664
field_iterator field_begin() const
Definition Decl.cpp:5356
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7557
void setMemberSpecialization()
Note that this member template is a specialization.
void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD)
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5472
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3172
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3215
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void setEntity(DeclContext *E)
Definition Scope.h:395
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:414
unsigned getDepth() const
Returns the depth of this scope. The translation-unit has scope depth 0.
Definition Scope.h:325
unsigned getNextFunctionPrototypeIndex()
Return the number of parameters declared in this function prototype, increasing it by one for the nex...
Definition Scope.h:335
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:284
void AddDecl(Decl *D)
Definition Scope.h:348
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
bool isTypeAliasScope() const
Determine whether this scope is a type alias scope.
Definition Scope.h:614
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:384
void RemoveDecl(Decl *D)
Definition Scope.h:356
void setLookupEntity(DeclContext *E)
Definition Scope.h:400
unsigned getMSLastManglingNumber() const
Definition Scope.h:372
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
unsigned getMSCurManglingNumber() const
Definition Scope.h:378
bool decl_empty() const
Definition Scope.h:346
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:467
unsigned getFunctionPrototypeDepth() const
Returns the number of function prototype scopes in this scope chain.
Definition Scope.h:329
Scope * getDeclParent()
Definition Scope.h:321
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition Scope.h:605
decl_range decls() const
Definition Scope.h:342
bool containedInPrototypeScope() const
containedInPrototypeScope - Return true if this or a parent scope is a FunctionPrototypeScope.
Definition Scope.cpp:106
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:473
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred within this scope.
Definition Scope.h:406
void applyNRVO()
Definition Scope.cpp:171
Scope * getTemplateParamParent()
Definition Scope.h:318
@ 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
void DiagnoseUnguardedBuiltinUsage(FunctionDecl *FD)
void checkNamedBarrierWrapper(RecordDecl *R)
Called in ActOnFields - whenever a C/C++ Record is being finalized.
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1640
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:744
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:211
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:874
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition SemaCUDA.cpp:939
void CheckEntryPoint(FunctionDecl *FD)
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:761
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:727
void deduceAddressSpace(VarDecl *Decl)
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:937
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:797
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:741
void ActOnVariableDeclarator(VarDecl *VD)
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
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.
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,...
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void ActOnVariableDeclarator(VarDecl *VD)
Function called when a variable declarator is created, which lets us implement the 'routine' 'functio...
OpenACCRoutineDeclAttr * mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old)
void ActOnFunctionDeclarator(FunctionDecl *FD)
Called when a function decl is created, which lets us implement the 'routine' 'doesn't match next thi...
void ActOnVariableInit(VarDecl *VD, QualType InitType)
Called when a variable is initialized, so we can implement the 'routine 'doesn't match the next thing...
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)
StmtResult BuildUnresolvedSYCLKernelCallStmt(CompoundStmt *Body, Expr *LaunchIdExpr)
Builds an UnresolvedSYCLKernelCallStmt to wrap 'Body'.
Definition SemaSYCL.cpp:819
StmtResult BuildSYCLKernelCallStmt(FunctionDecl *FD, CompoundStmt *Body, Expr *LaunchIdExpr)
Builds a SYCLKernelCallStmt to wrap 'Body' and to be used as the body of 'FD'.
Definition SemaSYCL.cpp:774
void CheckSYCLExternalFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:281
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:298
ExprResult BuildSYCLKernelLaunchIdExpr(FunctionDecl *FD, QualType KernelName)
Builds an expression for the lookup of a 'sycl_kernel_launch' template with 'KernelName' as an explic...
Definition SemaSYCL.cpp:428
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition SemaSwift.cpp:26
SwiftAttrAttr * mergeAttrAttr(Decl *D, const SwiftAttrAttr &SAA)
Definition SemaSwift.cpp:42
WebAssemblyExportNameAttr * mergeExportNameAttr(Decl *D, const WebAssemblyExportNameAttr &AL)
Definition SemaWasm.cpp:386
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition SemaWasm.cpp:353
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition SemaWasm.cpp:319
bool IsAlignAttr() const
Definition Sema.h:1949
Mode getAlignMode() const
Definition Sema.h:1951
A RAII object to temporarily push a declaration context.
Definition Sema.h:3584
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1412
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1424
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3810
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3820
static NameClassification Unknown()
Definition Sema.h:3790
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3794
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3838
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3826
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3800
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3832
static NameClassification UndeclaredNonType()
Definition Sema.h:3806
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3814
static NameClassification Error()
Definition Sema.h:3786
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12630
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12664
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
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.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1474
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition Sema.h:3688
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13244
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2702
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1165
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...
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
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',...
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.
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:8352
bool isFromSameSingleIncludeHeader(const Decl *PrevD, SourceLocation NewLoc)
Determine if a definition at NewLoc coincides with PrevD.
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9447
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9451
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9470
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9486
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9483
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9459
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9454
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
void ActOnPopScope(SourceLocation Loc, Scope *S)
void ActOnDefinedDeclarationSpecifier(Decl *D)
Called once it is known whether a tag declaration is an anonymous union or struct.
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
Decl * ActOnSkippedFunctionBody(Decl *Decl)
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
void deduceOpenCLAddressSpace(VarDecl *decl)
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...
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.
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...
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.
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val, SkipBodyInfo *SkipBody=nullptr)
void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID)
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings={})
SemaOpenMP & OpenMP()
Definition Sema.h:1559
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,...
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition Sema.h:4879
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1875
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:6597
bool areDocumentationDiagsEnabled(SourceLocation Loc)
Returns true if any of the documentation warnings is enabled at Loc.
Definition Sema.cpp:2789
Decl * ActOnParamDeclarator(Scope *S, Declarator &D, SourceLocation ExplicitThisLoc={})
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
void AddPragmaAttributes(Scope *S, Decl *D)
Adds the attributes that have been specified using the '#pragma clang attribute push' directives to t...
SemaCUDA & CUDA()
Definition Sema.h:1499
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)
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()
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:318
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Preprocessor & getPreprocessor() const
Definition Sema.h:934
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2106
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2100
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
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)
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)
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:54
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)
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
@ Default
= default ;
Definition Sema.h:4267
@ Delete
deleted-function-body
Definition Sema.h:4273
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,...
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.
bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS)
Check whether the given variable declaration has a size that fits within the address space it is decl...
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
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)
PersonalityAttr * mergePersonalityAttr(Decl *D, FunctionDecl *Routine, const AttributeCommonInfo &CI)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt)
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
SemaSYCL & SYCL()
Definition Sema.h:1584
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
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:1769
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
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:688
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
AvailabilityAttr * mergeAndInferAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, const IdentifierInfo *IIEnvironment, const IdentifierInfo *InferredPlatformII)
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ASTContext & Context
Definition Sema.h:1332
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:228
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2388
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void ActOnReenterFunctionPrototypeParams(Scope *S, ArrayRef< ParmVarDecl * > Params)
Add Params to scope, so a late-parsed attribute can name them.
void * SkippedDefinitionContext
Definition Sema.h:4491
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1544
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1399
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:80
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2103
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:3678
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
ASTContext & getASTContext() const
Definition Sema.h:935
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)
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.
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.
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:2099
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKin