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"
38#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
40#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
41#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
43#include "clang/Sema/DeclSpec.h"
46#include "clang/Sema/Lookup.h"
48#include "clang/Sema/Scope.h"
51#include "clang/Sema/SemaARM.h"
52#include "clang/Sema/SemaCUDA.h"
53#include "clang/Sema/SemaHLSL.h"
55#include "clang/Sema/SemaObjC.h"
58#include "clang/Sema/SemaPPC.h"
60#include "clang/Sema/SemaSYCL.h"
62#include "clang/Sema/SemaWasm.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/STLForwardCompat.h"
66#include "llvm/ADT/ScopeExit.h"
67#include "llvm/ADT/SmallPtrSet.h"
68#include "llvm/ADT/SmallString.h"
69#include "llvm/ADT/StringExtras.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/Support/SaveAndRestore.h"
72#include "llvm/TargetParser/Triple.h"
73#include <algorithm>
74#include <cstring>
75#include <optional>
76#include <unordered_map>
77
78using namespace clang;
79using namespace sema;
80
82 if (OwnedType) {
83 Decl *Group[2] = { OwnedType, Ptr };
85 }
86
88}
89
90namespace {
91
92class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
93 public:
94 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
95 bool AllowTemplates = false,
96 bool AllowNonTemplates = true)
97 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
98 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
99 WantExpressionKeywords = false;
100 WantCXXNamedCasts = false;
101 WantRemainingKeywords = false;
102 }
103
104 bool ValidateCandidate(const TypoCorrection &candidate) override {
105 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
106 if (!AllowInvalidDecl && ND->isInvalidDecl())
107 return false;
108
109 if (getAsTypeTemplateDecl(ND))
110 return AllowTemplates;
111
112 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
113 if (!IsType)
114 return false;
115
116 if (AllowNonTemplates)
117 return true;
118
119 // An injected-class-name of a class template (specialization) is valid
120 // as a template or as a non-template.
121 if (AllowTemplates) {
122 auto *RD = dyn_cast<CXXRecordDecl>(ND);
123 if (!RD || !RD->isInjectedClassName())
124 return false;
125 RD = cast<CXXRecordDecl>(RD->getDeclContext());
126 return RD->getDescribedClassTemplate() ||
128 }
129
130 return false;
131 }
132
133 return !WantClassName && candidate.isKeyword();
134 }
135
136 std::unique_ptr<CorrectionCandidateCallback> clone() override {
137 return std::make_unique<TypeNameValidatorCCC>(*this);
138 }
139
140 private:
141 bool AllowInvalidDecl;
142 bool WantClassName;
143 bool AllowTemplates;
144 bool AllowNonTemplates;
145};
146
147} // end anonymous namespace
148
150 TypeDecl *TD, SourceLocation NameLoc) {
151 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
152 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
153 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
154 FoundRD->isInjectedClassName() &&
155 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
156 Diag(NameLoc,
158 ? diag::ext_out_of_line_qualified_id_type_names_constructor
159 : diag::err_out_of_line_qualified_id_type_names_constructor)
160 << TD->getIdentifier() << /*Type=*/1
161 << 0 /*if any keyword was present, it was 'typename'*/;
162 }
163
164 DiagnoseUseOfDecl(TD, NameLoc);
165 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
191 if (BaseRD) {
192 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
193 Base.getType().getCanonicalType())) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207 CTD->findPartialSpecialization(Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(&II)) {
215 if (!isa<TypeDecl>(ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
257 // allowed. We'll fully resolve the lookup during template instantiation.
258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
262 QualType T =
263 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274}
275
277 Scope *S, CXXScopeSpec *SS, bool isClassName,
278 bool HasTrailingDot, ParsedType ObjectTypePtr,
279 bool IsCtorOrDtorName,
280 bool WantNontrivialTypeSourceInfo,
281 bool IsClassTemplateDeductionContext,
282 ImplicitTypenameContext AllowImplicitTypename,
283 IdentifierInfo **CorrectedII) {
284 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
285 // FIXME: Consider allowing this outside C++1z mode as an extension.
286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
288 !HasTrailingDot;
289
290 // Determine where we will perform name lookup.
291 DeclContext *LookupCtx = nullptr;
292 if (ObjectTypePtr) {
293 QualType ObjectType = ObjectTypePtr.get();
294 if (ObjectType->isRecordType())
295 LookupCtx = computeDeclContext(ObjectType);
296 } else if (SS && SS->isNotEmpty()) {
297 LookupCtx = computeDeclContext(*SS, false);
298
299 if (!LookupCtx) {
300 if (isDependentScopeSpecifier(*SS)) {
301 // C++ [temp.res]p3:
302 // A qualified-id that refers to a type and in which the
303 // nested-name-specifier depends on a template-parameter (14.6.2)
304 // shall be prefixed by the keyword typename to indicate that the
305 // qualified-id denotes a type, forming an
306 // elaborated-type-specifier (7.1.5.3).
307 //
308 // We therefore do not perform any name lookup if the result would
309 // refer to a member of an unknown specialization.
310 // In C++2a, in several contexts a 'typename' is not required. Also
311 // allow this as an extension.
312 if (IsImplicitTypename) {
313 if (AllowImplicitTypename == ImplicitTypenameContext::No)
314 return nullptr;
315 SourceLocation QualifiedLoc = SS->getRange().getBegin();
316 // FIXME: Defer the diagnostic after we build the type and use it.
317 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
318 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
319 SS->getScopeRep(), &II);
321 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
322 }
323
324 // We know from the grammar that this name refers to a type,
325 // so build a dependent node to describe the type.
326 if (WantNontrivialTypeSourceInfo)
327 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
328 (ImplicitTypenameContext)IsImplicitTypename)
329 .get();
330
333 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
335 SourceLocation(), QualifierLoc, II, NameLoc);
336 return ParsedType::make(T);
337 }
338
339 return nullptr;
340 }
341
342 if (!LookupCtx->isDependentContext() &&
343 RequireCompleteDeclContext(*SS, LookupCtx))
344 return nullptr;
345 }
346
347 // In the case where we know that the identifier is a class name, we know that
348 // it is a type declaration (struct, class, union or enum) so we can use tag
349 // name lookup.
350 //
351 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
352 // the component name of the type-name or simple-template-id is type-only.
353 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
354 LookupResult Result(*this, &II, NameLoc, Kind);
355 if (LookupCtx) {
356 // Perform "qualified" name lookup into the declaration context we
357 // computed, which is either the type of the base of a member access
358 // expression or the declaration context associated with a prior
359 // nested-name-specifier.
360 LookupQualifiedName(Result, LookupCtx);
361
362 if (ObjectTypePtr && Result.empty()) {
363 // C++ [basic.lookup.classref]p3:
364 // If the unqualified-id is ~type-name, the type-name is looked up
365 // in the context of the entire postfix-expression. If the type T of
366 // the object expression is of a class type C, the type-name is also
367 // looked up in the scope of class C. At least one of the lookups shall
368 // find a name that refers to (possibly cv-qualified) T.
369 LookupName(Result, S);
370 }
371 } else {
372 // Perform unqualified name lookup.
373 LookupName(Result, S);
374
375 // For unqualified lookup in a class template in MSVC mode, look into
376 // dependent base classes where the primary class template is known.
377 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
378 if (ParsedType TypeInBase =
379 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
380 return TypeInBase;
381 }
382 }
383
384 NamedDecl *IIDecl = nullptr;
385 UsingShadowDecl *FoundUsingShadow = nullptr;
386 switch (Result.getResultKind()) {
388 if (CorrectedII) {
389 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
390 AllowDeducedTemplate);
391 TypoCorrection Correction =
392 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
394 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
396 bool MemberOfUnknownSpecialization;
398 TemplateName.setIdentifier(NewII, NameLoc);
400 CXXScopeSpec NewSS, *NewSSPtr = SS;
401 if (SS && NNS) {
402 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
403 NewSSPtr = &NewSS;
404 }
405 if (Correction && (NNS || NewII != &II) &&
406 // Ignore a correction to a template type as the to-be-corrected
407 // identifier is not a template (typo correction for template names
408 // is handled elsewhere).
409 !(getLangOpts().CPlusPlus && NewSSPtr &&
410 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
411 Template, MemberOfUnknownSpecialization))) {
412 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
413 isClassName, HasTrailingDot, ObjectTypePtr,
414 IsCtorOrDtorName,
415 WantNontrivialTypeSourceInfo,
416 IsClassTemplateDeductionContext);
417 if (Ty) {
418 diagnoseTypo(Correction,
419 PDiag(diag::err_unknown_type_or_class_name_suggest)
420 << Result.getLookupName() << isClassName);
421 if (SS && NNS)
422 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
423 *CorrectedII = NewII;
424 return Ty;
425 }
426 }
427 }
428 Result.suppressDiagnostics();
429 return nullptr;
431 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
432 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
433 SS->getScopeRep(), &II);
434 TypeLocBuilder TLB;
438 TL.setNameLoc(NameLoc);
439 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
440 }
441 [[fallthrough]];
444 Result.suppressDiagnostics();
445 return nullptr;
446
448 // Recover from type-hiding ambiguities by hiding the type. We'll
449 // do the lookup again when looking for an object, and we can
450 // diagnose the error then. If we don't do this, then the error
451 // about hiding the type will be immediately followed by an error
452 // that only makes sense if the identifier was treated like a type.
453 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
454 Result.suppressDiagnostics();
455 return nullptr;
456 }
457
458 // Look to see if we have a type anywhere in the list of results.
459 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
460 Res != ResEnd; ++Res) {
461 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
463 RealRes) ||
464 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
465 if (!IIDecl ||
466 // Make the selection of the recovery decl deterministic.
467 RealRes->getLocation() < IIDecl->getLocation()) {
468 IIDecl = RealRes;
469 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
470 }
471 }
472 }
473
474 if (!IIDecl) {
475 // None of the entities we found is a type, so there is no way
476 // to even assume that the result is a type. In this case, don't
477 // complain about the ambiguity. The parser will either try to
478 // perform this lookup again (e.g., as an object name), which
479 // will produce the ambiguity, or will complain that it expected
480 // a type name.
481 Result.suppressDiagnostics();
482 return nullptr;
483 }
484
485 // We found a type within the ambiguous lookup; diagnose the
486 // ambiguity and then return that type. This might be the right
487 // answer, or it might not be, but it suppresses any attempt to
488 // perform the name lookup again.
489 break;
490
492 IIDecl = Result.getFoundDecl();
493 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
494 break;
495 }
496
497 assert(IIDecl && "Didn't find decl");
498
499 TypeLocBuilder TLB;
500 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
501 checkTypeDeclType(LookupCtx,
502 IsImplicitTypename ? DiagCtorKind::Implicit
504 TD, NameLoc);
505 QualType T;
506 if (FoundUsingShadow) {
507 T = Context.getUsingType(ElaboratedTypeKeyword::None,
508 SS ? SS->getScopeRep() : std::nullopt,
509 FoundUsingShadow);
510 if (!WantNontrivialTypeSourceInfo)
511 return ParsedType::make(T);
512 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
515 NameLoc);
516 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
518 SS ? SS->getScopeRep() : std::nullopt, Tag,
519 /*OwnsTag=*/false);
520 if (!WantNontrivialTypeSourceInfo)
521 return ParsedType::make(T);
522 auto TL = TLB.push<TagTypeLoc>(T);
524 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
526 TL.setNameLoc(NameLoc);
527 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
528 TN && !isa<ObjCTypeParamDecl>(TN)) {
529 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
530 SS ? SS->getScopeRep() : std::nullopt, TN);
531 if (!WantNontrivialTypeSourceInfo)
532 return ParsedType::make(T);
533 TLB.push<TypedefTypeLoc>(T).set(
534 /*ElaboratedKeywordLoc=*/SourceLocation(),
536 NameLoc);
537 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
538 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
539 SS ? SS->getScopeRep() : std::nullopt,
540 UD);
541 if (!WantNontrivialTypeSourceInfo)
542 return ParsedType::make(T);
543 TLB.push<UnresolvedUsingTypeLoc>(T).set(
544 /*ElaboratedKeywordLoc=*/SourceLocation(),
546 NameLoc);
547 } else {
548 T = Context.getTypeDeclType(TD);
549 if (!WantNontrivialTypeSourceInfo)
550 return ParsedType::make(T);
552 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
553 else
554 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
555 }
556 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
557 }
558
559 if (getLangOpts().HLSL) {
560 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
561 getAsTemplateNameDecl(IIDecl, /*AllowFunctionTemplates=*/false,
562 /*AllowDependent=*/false))) {
563 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(TD, NameLoc);
564 if (!ShorthandTy.isNull())
565 return ParsedType::make(ShorthandTy);
566 }
567 }
568
569 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
570 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
571 if (!HasTrailingDot) {
572 // FIXME: Support UsingType for this case.
573 QualType T = Context.getObjCInterfaceType(IDecl);
574 if (!WantNontrivialTypeSourceInfo)
575 return ParsedType::make(T);
576 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
577 TL.setNameLoc(NameLoc);
578 // FIXME: Pass in this source location.
579 TL.setNameEndLoc(NameLoc);
580 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
581 }
582 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
583 (void)DiagnoseUseOfDecl(UD, NameLoc);
584 // Recover with 'int'
585 return ParsedType::make(Context.IntTy);
586 } else if (AllowDeducedTemplate) {
587 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
588 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
589 // FIXME: Support UsingType here.
590 TemplateName Template = Context.getQualifiedTemplateName(
591 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
592 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
593 QualType T = Context.getDeducedTemplateSpecializationType(
595 Template);
598 TL.setNameLoc(NameLoc);
599 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
601 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
602 }
603 }
604
605 // As it's not plausibly a type, suppress diagnostics.
606 Result.suppressDiagnostics();
607 return nullptr;
608}
609
610// Builds a fake NNS for the given decl context.
613 for (;; DC = DC->getLookupParent()) {
614 DC = DC->getPrimaryContext();
615 auto *ND = dyn_cast<NamespaceDecl>(DC);
616 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
617 return NestedNameSpecifier(Context, ND, std::nullopt);
618 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
619 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
622 }
623 llvm_unreachable("something isn't in TU scope?");
624}
625
626/// Find the parent class with dependent bases of the innermost enclosing method
627/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
628/// up allowing unqualified dependent type names at class-level, which MSVC
629/// correctly rejects.
630static const CXXRecordDecl *
632 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
633 DC = DC->getPrimaryContext();
634 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
635 if (MD->getParent()->hasAnyDependentBases())
636 return MD->getParent();
637 }
638 return nullptr;
639}
640
642 SourceLocation NameLoc,
643 bool IsTemplateTypeArg) {
644 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
645
646 NestedNameSpecifier NNS = std::nullopt;
647 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
648 // If we weren't able to parse a default template argument, delay lookup
649 // until instantiation time by making a non-dependent DependentTypeName. We
650 // pretend we saw a NestedNameSpecifier referring to the current scope, and
651 // lookup is retried.
652 // FIXME: This hurts our diagnostic quality, since we get errors like "no
653 // type named 'Foo' in 'current_namespace'" when the user didn't write any
654 // name specifiers.
656 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
657 } else if (const CXXRecordDecl *RD =
659 // Build a DependentNameType that will perform lookup into RD at
660 // instantiation time.
661 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
662
663 // Diagnose that this identifier was undeclared, and retry the lookup during
664 // template instantiation.
665 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
666 << RD;
667 } else {
668 // This is not a situation that we should recover from.
669 return ParsedType();
670 }
671
672 QualType T =
673 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
674
675 // Build type location information. We synthesized the qualifier, so we have
676 // to build a fake NestedNameSpecifierLoc.
677 NestedNameSpecifierLocBuilder NNSLocBuilder;
678 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
679 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
680
681 TypeLocBuilder Builder;
682 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
683 DepTL.setNameLoc(NameLoc);
685 DepTL.setQualifierLoc(QualifierLoc);
686 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
687}
688
690 // Do a tag name lookup in this scope.
691 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
692 LookupName(R, S, false);
693 R.suppressDiagnostics();
694 if (R.getResultKind() == LookupResultKind::Found)
695 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
696 switch (TD->getTagKind()) {
702 return DeclSpec::TST_union;
704 return DeclSpec::TST_class;
706 return DeclSpec::TST_enum;
707 }
708 }
709
711}
712
714 if (!CurContext->isRecord())
715 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
716
717 switch (SS->getScopeRep().getKind()) {
719 return true;
721 QualType T(SS->getScopeRep().getAsType(), 0);
722 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
723 if (Context.hasSameUnqualifiedType(T, Base.getType()))
724 return true;
725 [[fallthrough]];
726 }
727 default:
728 return S->isFunctionPrototypeScope();
729 }
730}
731
733 SourceLocation IILoc,
734 Scope *S,
735 CXXScopeSpec *SS,
736 ParsedType &SuggestedType,
737 bool IsTemplateName) {
738 // Don't report typename errors for editor placeholders.
739 if (II->isEditorPlaceholder())
740 return;
741 // We don't have anything to suggest (yet).
742 SuggestedType = nullptr;
743
744 // There may have been a typo in the name of the type. Look up typo
745 // results, in case we have something that we can suggest.
746 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
747 /*AllowTemplates=*/IsTemplateName,
748 /*AllowNonTemplates=*/!IsTemplateName);
749 if (TypoCorrection Corrected =
752 // FIXME: Support error recovery for the template-name case.
753 bool CanRecover = !IsTemplateName;
754 if (Corrected.isKeyword()) {
755 // We corrected to a keyword.
756 diagnoseTypo(Corrected,
757 PDiag(IsTemplateName ? diag::err_no_template_suggest
758 : diag::err_unknown_typename_suggest)
759 << II);
760 II = Corrected.getCorrectionAsIdentifierInfo();
761 } else {
762 // We found a similarly-named type or interface; suggest that.
763 if (!SS || !SS->isSet()) {
764 diagnoseTypo(Corrected,
765 PDiag(IsTemplateName ? diag::err_no_template_suggest
766 : diag::err_unknown_typename_suggest)
767 << II, CanRecover);
768 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
769 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
770 bool DroppedSpecifier =
771 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
772 diagnoseTypo(Corrected,
773 PDiag(IsTemplateName
774 ? diag::err_no_member_template_suggest
775 : diag::err_unknown_nested_typename_suggest)
776 << II << DC << DroppedSpecifier << SS->getRange(),
777 CanRecover);
778 } else {
779 llvm_unreachable("could not have corrected a typo here");
780 }
781
782 if (!CanRecover)
783 return;
784
785 CXXScopeSpec tmpSS;
786 if (Corrected.getCorrectionSpecifier())
787 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
788 SourceRange(IILoc));
789 // FIXME: Support class template argument deduction here.
790 SuggestedType =
791 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
792 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
793 /*IsCtorOrDtorName=*/false,
794 /*WantNontrivialTypeSourceInfo=*/true);
795 }
796 return;
797 }
798
799 if (getLangOpts().CPlusPlus && !IsTemplateName) {
800 // See if II is a class template that the user forgot to pass arguments to.
801 UnqualifiedId Name;
802 Name.setIdentifier(II, IILoc);
803 CXXScopeSpec EmptySS;
804 TemplateTy TemplateResult;
805 bool MemberOfUnknownSpecialization;
806 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
807 Name, nullptr, true, TemplateResult,
808 MemberOfUnknownSpecialization) == TNK_Type_template) {
809 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
810 return;
811 }
812 }
813
814 // FIXME: Should we move the logic that tries to recover from a missing tag
815 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
816
817 if (!SS || (!SS->isSet() && !SS->isInvalid()))
818 Diag(IILoc, IsTemplateName ? diag::err_no_template
819 : diag::err_unknown_typename)
820 << II;
821 else if (DeclContext *DC = computeDeclContext(*SS, false))
822 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
823 : diag::err_typename_nested_not_found)
824 << II << DC << SS->getRange();
825 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
826 SuggestedType =
827 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
828 } else if (isDependentScopeSpecifier(*SS)) {
829 unsigned DiagID = diag::err_typename_missing;
830 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
831 DiagID = diag::ext_typename_missing;
832
833 SuggestedType =
834 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
835
836 Diag(SS->getRange().getBegin(), DiagID)
837 << GetTypeFromParser(SuggestedType)
838 << SourceRange(SS->getRange().getBegin(), IILoc)
839 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
840 } else {
841 assert(SS && SS->isInvalid() &&
842 "Invalid scope specifier has already been diagnosed");
843 }
844}
845
846/// Determine whether the given result set contains either a type name
847/// or
848static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
849 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
850 NextToken.is(tok::less);
851
852 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
854 return true;
855
856 if (CheckTemplate && isa<TemplateDecl>(*I))
857 return true;
858 }
859
860 return false;
861}
862
864 Scope *S, CXXScopeSpec &SS,
865 IdentifierInfo *&Name,
866 SourceLocation NameLoc) {
867 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
868 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
869 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
870 StringRef FixItTagName;
871 switch (Tag->getTagKind()) {
873 FixItTagName = "class ";
874 break;
875
877 FixItTagName = "enum ";
878 break;
879
881 FixItTagName = "struct ";
882 break;
883
885 FixItTagName = "__interface ";
886 break;
887
889 FixItTagName = "union ";
890 break;
891 }
892
893 StringRef TagName = FixItTagName.drop_back();
894 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
895 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
896 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
897
898 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
899 I != IEnd; ++I)
900 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
901 << Name << TagName;
902
903 // Replace lookup results with just the tag decl.
905 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
906 return true;
907 }
908
909 return false;
910}
911
913 IdentifierInfo *&Name,
914 SourceLocation NameLoc,
915 const Token &NextToken,
917 DeclarationNameInfo NameInfo(Name, NameLoc);
918 ObjCMethodDecl *CurMethod = getCurMethodDecl();
919
920 assert(NextToken.isNot(tok::coloncolon) &&
921 "parse nested name specifiers before calling ClassifyName");
922 if (getLangOpts().CPlusPlus && SS.isSet() &&
923 isCurrentClassName(*Name, S, &SS)) {
924 // Per [class.qual]p2, this names the constructors of SS, not the
925 // injected-class-name. We don't have a classification for that.
926 // There's not much point caching this result, since the parser
927 // will reject it later.
929 }
930
931 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
932 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
933 /*AllowBuiltinCreation=*/!CurMethod);
934
935 if (SS.isInvalid())
937
938 // For unqualified lookup in a class template in MSVC mode, look into
939 // dependent base classes where the primary class template is known.
940 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
941 if (ParsedType TypeInBase =
942 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
943 return TypeInBase;
944 }
945
946 // Perform lookup for Objective-C instance variables (including automatically
947 // synthesized instance variables), if we're in an Objective-C method.
948 // FIXME: This lookup really, really needs to be folded in to the normal
949 // unqualified lookup mechanism.
950 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
951 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
952 if (Ivar.isInvalid())
954 if (Ivar.isUsable())
956
957 // We defer builtin creation until after ivar lookup inside ObjC methods.
958 if (Result.empty())
960 }
961
962 bool SecondTry = false;
963 bool IsFilteredTemplateName = false;
964
965Corrected:
966 switch (Result.getResultKind()) {
968 // If an unqualified-id is followed by a '(', then we have a function
969 // call.
970 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
971 // In C++, this is an ADL-only call.
972 // FIXME: Reference?
975
976 // C90 6.3.2.2:
977 // If the expression that precedes the parenthesized argument list in a
978 // function call consists solely of an identifier, and if no
979 // declaration is visible for this identifier, the identifier is
980 // implicitly declared exactly as if, in the innermost block containing
981 // the function call, the declaration
982 //
983 // extern int identifier ();
984 //
985 // appeared.
986 //
987 // We also allow this in C99 as an extension. However, this is not
988 // allowed in all language modes as functions without prototypes may not
989 // be supported.
990 if (getLangOpts().implicitFunctionsAllowed()) {
991 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
993 }
994 }
995
996 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
997 // In C++20 onwards, this could be an ADL-only call to a function
998 // template, and we're required to assume that this is a template name.
999 //
1000 // FIXME: Find a way to still do typo correction in this case.
1002 Context.getAssumedTemplateName(NameInfo.getName());
1004 }
1005
1006 // In C, we first see whether there is a tag type by the same name, in
1007 // which case it's likely that the user just forgot to write "enum",
1008 // "struct", or "union".
1009 if (!getLangOpts().CPlusPlus && !SecondTry &&
1010 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1011 break;
1012 }
1013
1014 // Perform typo correction to determine if there is another name that is
1015 // close to this name.
1016 if (!SecondTry && CCC) {
1017 SecondTry = true;
1018 if (TypoCorrection Corrected =
1019 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1020 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1021 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1022 unsigned QualifiedDiag = diag::err_no_member_suggest;
1023
1024 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1025 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1026 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1027 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1028 UnqualifiedDiag = diag::err_no_template_suggest;
1029 QualifiedDiag = diag::err_no_member_template_suggest;
1030 } else if (UnderlyingFirstDecl &&
1031 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1032 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1033 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1034 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1035 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1036 }
1037
1038 if (SS.isEmpty()) {
1039 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1040 } else {// FIXME: is this even reachable? Test it.
1041 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1042 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1043 Name->getName() == CorrectedStr;
1044 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1045 << Name << computeDeclContext(SS, false)
1046 << DroppedSpecifier << SS.getRange());
1047 }
1048
1049 // Update the name, so that the caller has the new name.
1050 Name = Corrected.getCorrectionAsIdentifierInfo();
1051
1052 // Typo correction corrected to a keyword.
1053 if (Corrected.isKeyword())
1054 return Name;
1055
1056 // Also update the LookupResult...
1057 // FIXME: This should probably go away at some point
1058 Result.clear();
1059 Result.setLookupName(Corrected.getCorrection());
1060 if (FirstDecl)
1061 Result.addDecl(FirstDecl);
1062
1063 // If we found an Objective-C instance variable, let
1064 // LookupInObjCMethod build the appropriate expression to
1065 // reference the ivar.
1066 // FIXME: This is a gross hack.
1067 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1068 DeclResult R =
1069 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1070 if (R.isInvalid())
1072 if (R.isUsable())
1073 return NameClassification::NonType(Ivar);
1074 }
1075
1076 goto Corrected;
1077 }
1078 }
1079
1080 // We failed to correct; just fall through and let the parser deal with it.
1081 Result.suppressDiagnostics();
1083
1085 // We performed name lookup into the current instantiation, and there were
1086 // dependent bases, so we treat this result the same way as any other
1087 // dependent nested-name-specifier.
1088
1089 // C++ [temp.res]p2:
1090 // A name used in a template declaration or definition and that is
1091 // dependent on a template-parameter is assumed not to name a type
1092 // unless the applicable name lookup finds a type name or the name is
1093 // qualified by the keyword typename.
1094 //
1095 // FIXME: If the next token is '<', we might want to ask the parser to
1096 // perform some heroics to see if we actually have a
1097 // template-argument-list, which would indicate a missing 'template'
1098 // keyword here.
1100 }
1101
1105 break;
1106
1108 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1109 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false)) {
1111 // C++ [temp.local]p3:
1112 // A lookup that finds an injected-class-name (10.2) can result in an
1113 // ambiguity in certain cases (for example, if it is found in more than
1114 // one base class). If all of the injected-class-names that are found
1115 // refer to specializations of the same class template, and if the name
1116 // is followed by a template-argument-list, the reference refers to the
1117 // class template itself and not a specialization thereof, and is not
1118 // ambiguous.
1119 //
1120 // This filtering can make an ambiguous result into an unambiguous one,
1121 // so try again after filtering out template names.
1123 if (!Result.isAmbiguous()) {
1124 IsFilteredTemplateName = true;
1125 break;
1126 }
1127 }
1128
1129 // Diagnose the ambiguity and return an error.
1131 }
1132
1133 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1134 (IsFilteredTemplateName ||
1136 Result, /*AllowFunctionTemplates=*/true,
1137 /*AllowDependent=*/false,
1138 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1140 // C++ [temp.names]p3:
1141 // After name lookup (3.4) finds that a name is a template-name or that
1142 // an operator-function-id or a literal- operator-id refers to a set of
1143 // overloaded functions any member of which is a function template if
1144 // this is followed by a <, the < is always taken as the delimiter of a
1145 // template-argument-list and never as the less-than operator.
1146 // C++2a [temp.names]p2:
1147 // A name is also considered to refer to a template if it is an
1148 // unqualified-id followed by a < and name lookup finds either one
1149 // or more functions or finds nothing.
1150 if (!IsFilteredTemplateName)
1152
1153 bool IsFunctionTemplate;
1154 bool IsVarTemplate;
1156 if (Result.end() - Result.begin() > 1) {
1157 IsFunctionTemplate = true;
1158 Template = Context.getOverloadedTemplateName(Result.begin(),
1159 Result.end());
1160 } else if (!Result.empty()) {
1162 *Result.begin(), /*AllowFunctionTemplates=*/true,
1163 /*AllowDependent=*/false));
1164 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1165 IsVarTemplate = isa<VarTemplateDecl>(TD);
1166
1167 UsingShadowDecl *FoundUsingShadow =
1168 dyn_cast<UsingShadowDecl>(*Result.begin());
1169 assert(!FoundUsingShadow ||
1170 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1171 Template = Context.getQualifiedTemplateName(
1172 SS.getScopeRep(),
1173 /*TemplateKeyword=*/false,
1174 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1175 } else {
1176 // All results were non-template functions. This is a function template
1177 // name.
1178 IsFunctionTemplate = true;
1179 Template = Context.getAssumedTemplateName(NameInfo.getName());
1180 }
1181
1182 if (IsFunctionTemplate) {
1183 // Function templates always go through overload resolution, at which
1184 // point we'll perform the various checks (e.g., accessibility) we need
1185 // to based on which function we selected.
1186 Result.suppressDiagnostics();
1187
1189 }
1190
1191 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1193 }
1194
1195 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1196 QualType T;
1197 TypeLocBuilder TLB;
1198 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1199 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1200 USD);
1201 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1202 SS.getWithLocInContext(Context), NameLoc);
1203 } else {
1204 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1205 Type);
1206 if (isa<TagType>(T)) {
1207 auto TTL = TLB.push<TagTypeLoc>(T);
1209 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1210 TTL.setNameLoc(NameLoc);
1211 } else if (isa<TypedefType>(T)) {
1212 TLB.push<TypedefTypeLoc>(T).set(
1213 /*ElaboratedKeywordLoc=*/SourceLocation(),
1214 SS.getWithLocInContext(Context), NameLoc);
1215 } else if (isa<UnresolvedUsingType>(T)) {
1216 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1217 /*ElaboratedKeywordLoc=*/SourceLocation(),
1218 SS.getWithLocInContext(Context), NameLoc);
1219 } else {
1220 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1221 }
1222 }
1223 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
1224 };
1225
1226 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1227 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1228 DiagnoseUseOfDecl(Type, NameLoc);
1229 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1230 return BuildTypeFor(Type, *Result.begin());
1231 }
1232
1233 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1234 if (!Class) {
1235 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1236 if (ObjCCompatibleAliasDecl *Alias =
1237 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1238 Class = Alias->getClassInterface();
1239 }
1240
1241 if (Class) {
1242 DiagnoseUseOfDecl(Class, NameLoc);
1243
1244 if (NextToken.is(tok::period)) {
1245 // Interface. <something> is parsed as a property reference expression.
1246 // Just return "unknown" as a fall-through for now.
1247 Result.suppressDiagnostics();
1249 }
1250
1251 QualType T = Context.getObjCInterfaceType(Class);
1252 return ParsedType::make(T);
1253 }
1254
1256 // We want to preserve the UsingShadowDecl for concepts.
1257 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1261 }
1262
1263 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1264 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1266 }
1267
1268 // We can have a type template here if we're classifying a template argument.
1273
1274 // Check for a tag type hidden by a non-type decl in a few cases where it
1275 // seems likely a type is wanted instead of the non-type that was found.
1276 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1277 if ((NextToken.is(tok::identifier) ||
1278 (NextIsOp &&
1279 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1280 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1281 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1282 DiagnoseUseOfDecl(Type, NameLoc);
1283 return BuildTypeFor(Type, *Result.begin());
1284 }
1285
1286 // If we already know which single declaration is referenced, just annotate
1287 // that declaration directly. Defer resolving even non-overloaded class
1288 // member accesses, as we need to defer certain access checks until we know
1289 // the context.
1290 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1291 if (Result.isSingleResult() && !ADL &&
1292 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1293 return NameClassification::NonType(Result.getRepresentativeDecl());
1294
1295 // Otherwise, this is an overload set that we will need to resolve later.
1296 Result.suppressDiagnostics();
1298 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1299 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1300 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1301}
1302
1305 SourceLocation NameLoc) {
1306 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1307 CXXScopeSpec SS;
1308 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1309 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1310}
1311
1314 IdentifierInfo *Name,
1315 SourceLocation NameLoc,
1316 bool IsAddressOfOperand) {
1317 DeclarationNameInfo NameInfo(Name, NameLoc);
1318 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1319 NameInfo, IsAddressOfOperand,
1320 /*TemplateArgs=*/nullptr);
1321}
1322
1325 SourceLocation NameLoc,
1326 const Token &NextToken) {
1327 if (getCurMethodDecl() && SS.isEmpty())
1328 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1329 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1330
1331 // Reconstruct the lookup result.
1332 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1333 Result.addDecl(Found);
1334 Result.resolveKind();
1335
1336 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1337 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1338}
1339
1341 // For an implicit class member access, transform the result into a member
1342 // access expression if necessary.
1343 auto *ULE = cast<UnresolvedLookupExpr>(E);
1344 if ((*ULE->decls_begin())->isCXXClassMember()) {
1345 CXXScopeSpec SS;
1346 SS.Adopt(ULE->getQualifierLoc());
1347
1348 // Reconstruct the lookup result.
1349 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1351 Result.setNamingClass(ULE->getNamingClass());
1352 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1353 Result.addDecl(*I, I.getAccess());
1354 Result.resolveKind();
1356 nullptr, S);
1357 }
1358
1359 // Otherwise, this is already in the form we needed, and no further checks
1360 // are necessary.
1361 return ULE;
1362}
1363
1383
1385 assert(DC->getLexicalParent() == CurContext &&
1386 "The next DeclContext should be lexically contained in the current one.");
1387 CurContext = DC;
1388 if (S)
1389 S->setEntity(DC);
1390}
1391
1393 assert(CurContext && "DeclContext imbalance!");
1394
1395 CurContext = CurContext->getLexicalParent();
1396 assert(CurContext && "Popped translation unit!");
1397}
1398
1400 Decl *D) {
1401 // Unlike PushDeclContext, the context to which we return is not necessarily
1402 // the containing DC of TD, because the new context will be some pre-existing
1403 // TagDecl definition instead of a fresh one.
1404 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1405 CurContext = cast<TagDecl>(D)->getDefinition();
1406 assert(CurContext && "skipping definition of undefined tag");
1407 // Start lookups from the parent of the current context; we don't want to look
1408 // into the pre-existing complete definition.
1409 S->setEntity(CurContext->getLookupParent());
1410 return Result;
1411}
1412
1416
1418 // C++0x [basic.lookup.unqual]p13:
1419 // A name used in the definition of a static data member of class
1420 // X (after the qualified-id of the static member) is looked up as
1421 // if the name was used in a member function of X.
1422 // C++0x [basic.lookup.unqual]p14:
1423 // If a variable member of a namespace is defined outside of the
1424 // scope of its namespace then any name used in the definition of
1425 // the variable member (after the declarator-id) is looked up as
1426 // if the definition of the variable member occurred in its
1427 // namespace.
1428 // Both of these imply that we should push a scope whose context
1429 // is the semantic context of the declaration. We can't use
1430 // PushDeclContext here because that context is not necessarily
1431 // lexically contained in the current context. Fortunately,
1432 // the containing scope should have the appropriate information.
1433
1434 assert(!S->getEntity() && "scope already has entity");
1435
1436#ifndef NDEBUG
1437 Scope *Ancestor = S->getParent();
1438 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1439 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1440#endif
1441
1442 CurContext = DC;
1443 S->setEntity(DC);
1444
1445 if (S->getParent()->isTemplateParamScope()) {
1446 // Also set the corresponding entities for all immediately-enclosing
1447 // template parameter scopes.
1449 }
1450}
1451
1453 assert(S->getEntity() == CurContext && "Context imbalance!");
1454
1455 // Switch back to the lexical context. The safety of this is
1456 // enforced by an assert in EnterDeclaratorContext.
1457 Scope *Ancestor = S->getParent();
1458 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1459 CurContext = Ancestor->getEntity();
1460
1461 // We don't need to do anything with the scope, which is going to
1462 // disappear.
1463}
1464
1466 assert(S->isTemplateParamScope() &&
1467 "expected to be initializing a template parameter scope");
1468
1469 // C++20 [temp.local]p7:
1470 // In the definition of a member of a class template that appears outside
1471 // of the class template definition, the name of a member of the class
1472 // template hides the name of a template-parameter of any enclosing class
1473 // templates (but not a template-parameter of the member if the member is a
1474 // class or function template).
1475 // C++20 [temp.local]p9:
1476 // In the definition of a class template or in the definition of a member
1477 // of such a template that appears outside of the template definition, for
1478 // each non-dependent base class (13.8.2.1), if the name of the base class
1479 // or the name of a member of the base class is the same as the name of a
1480 // template-parameter, the base class name or member name hides the
1481 // template-parameter name (6.4.10).
1482 //
1483 // This means that a template parameter scope should be searched immediately
1484 // after searching the DeclContext for which it is a template parameter
1485 // scope. For example, for
1486 // template<typename T> template<typename U> template<typename V>
1487 // void N::A<T>::B<U>::f(...)
1488 // we search V then B<U> (and base classes) then U then A<T> (and base
1489 // classes) then T then N then ::.
1490 unsigned ScopeDepth = getTemplateDepth(S);
1491 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1492 DeclContext *SearchDCAfterScope = DC;
1493 for (; DC; DC = DC->getLookupParent()) {
1494 if (const TemplateParameterList *TPL =
1495 cast<Decl>(DC)->getDescribedTemplateParams()) {
1496 unsigned DCDepth = TPL->getDepth() + 1;
1497 if (DCDepth > ScopeDepth)
1498 continue;
1499 if (ScopeDepth == DCDepth)
1500 SearchDCAfterScope = DC = DC->getLookupParent();
1501 break;
1502 }
1503 }
1504 S->setLookupEntity(SearchDCAfterScope);
1505 }
1506}
1507
1509 // We assume that the caller has already called
1510 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1511 FunctionDecl *FD = D->getAsFunction();
1512 if (!FD)
1513 return;
1514
1515 // Same implementation as PushDeclContext, but enters the context
1516 // from the lexical parent, rather than the top-level class.
1517 assert(CurContext == FD->getLexicalParent() &&
1518 "The next DeclContext should be lexically contained in the current one.");
1519 CurContext = FD;
1521
1522 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1523 ParmVarDecl *Param = FD->getParamDecl(P);
1524 // If the parameter has an identifier, then add it to the scope
1525 if (Param->getIdentifier()) {
1526 S->AddDecl(Param);
1527 IdResolver.AddDecl(Param);
1528 }
1529 }
1530}
1531
1533 // Same implementation as PopDeclContext, but returns to the lexical parent,
1534 // rather than the top-level class.
1535 assert(CurContext && "DeclContext imbalance!");
1536 CurContext = CurContext->getLexicalParent();
1537 assert(CurContext && "Popped translation unit!");
1538}
1539
1540/// Determine whether overloading is allowed for a new function
1541/// declaration considering prior declarations of the same name.
1542///
1543/// This routine determines whether overloading is possible, not
1544/// whether a new declaration actually overloads a previous one.
1545/// It will return true in C++ (where overloads are always permitted)
1546/// or, as a C extension, when either the new declaration or a
1547/// previous one is declared with the 'overloadable' attribute.
1549 ASTContext &Context,
1550 const FunctionDecl *New) {
1551 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1552 return true;
1553
1554 // Multiversion function declarations are not overloads in the
1555 // usual sense of that term, but lookup will report that an
1556 // overload set was found if more than one multiversion function
1557 // declaration is present for the same name. It is therefore
1558 // inadequate to assume that some prior declaration(s) had
1559 // the overloadable attribute; checking is required. Since one
1560 // declaration is permitted to omit the attribute, it is necessary
1561 // to check at least two; hence the 'any_of' check below. Note that
1562 // the overloadable attribute is implicitly added to declarations
1563 // that were required to have it but did not.
1564 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1565 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1566 return ND->hasAttr<OverloadableAttr>();
1567 });
1568 } else if (Previous.getResultKind() == LookupResultKind::Found)
1569 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1570
1571 return false;
1572}
1573
1574void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1575 // Move up the scope chain until we find the nearest enclosing
1576 // non-transparent context. The declaration will be introduced into this
1577 // scope.
1578 while (S->getEntity() && S->getEntity()->isTransparentContext())
1579 S = S->getParent();
1580
1581 // Add scoped declarations into their context, so that they can be
1582 // found later. Declarations without a context won't be inserted
1583 // into any context.
1584 if (AddToContext)
1585 CurContext->addDecl(D);
1586
1587 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1588 // are function-local declarations.
1589 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1590 if (!S->getFnParent())
1591 return;
1592
1593 // Even inside a function, an out-of-line definition of a type that is
1594 // nested inside a local class must not be pushed into the enclosing
1595 // function scope. For example:
1596 //
1597 // class A { public: class B; };
1598 // class A::B {}; // out-of-line definition inside the function
1599 // B b; // must fail - only A::B is valid
1600 // Wrapper{B{}} // must also fail
1601 //
1602 // Per C++ scoping rules only the qualified form A::B is accessible.
1603 // Without this guard, PushOnScopeChains would add B to the function's
1604 // local scope, making it findable via unqualified lookup, which is
1605 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1606 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1607 // of a local class being defined out-of-line.
1609 return;
1610 }
1611
1612 // Template instantiations should also not be pushed into scope.
1613 if (isa<FunctionDecl>(D) &&
1614 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1615 return;
1616
1617 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1618 S->AddDecl(D);
1619 return;
1620 }
1621 // If this replaces anything in the current scope,
1623 IEnd = IdResolver.end();
1624 for (; I != IEnd; ++I) {
1625 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1626 S->RemoveDecl(*I);
1627 IdResolver.RemoveDecl(*I);
1628
1629 // Should only need to replace one decl.
1630 break;
1631 }
1632 }
1633
1634 S->AddDecl(D);
1635
1636 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1637 // Implicitly-generated labels may end up getting generated in an order that
1638 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1639 // the label at the appropriate place in the identifier chain.
1640 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1641 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1642 if (IDC == CurContext) {
1643 if (!S->isDeclScope(*I))
1644 continue;
1645 } else if (IDC->Encloses(CurContext))
1646 break;
1647 }
1648
1649 IdResolver.InsertDeclAfter(I, D);
1650 } else {
1651 IdResolver.AddDecl(D);
1652 }
1654}
1655
1657 bool AllowInlineNamespace) const {
1658 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1659}
1660
1662 DeclContext *TargetDC = DC->getPrimaryContext();
1663 do {
1664 if (DeclContext *ScopeDC = S->getEntity())
1665 if (ScopeDC->getPrimaryContext() == TargetDC)
1666 return S;
1667 } while ((S = S->getParent()));
1668
1669 return nullptr;
1670}
1671
1673 DeclContext*,
1674 ASTContext&);
1675
1677 bool ConsiderLinkage,
1678 bool AllowInlineNamespace) {
1679 LookupResult::Filter F = R.makeFilter();
1680 while (F.hasNext()) {
1681 NamedDecl *D = F.next();
1682
1683 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1684 continue;
1685
1686 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1687 continue;
1688
1689 F.erase();
1690 }
1691
1692 F.done();
1693}
1694
1696 if (auto *VD = dyn_cast<VarDecl>(D))
1697 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1698 if (auto *FD = dyn_cast<FunctionDecl>(D))
1699 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1700 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1701 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1702
1703 return false;
1704}
1705
1707 // [module.interface]p7:
1708 // A declaration is attached to a module as follows:
1709 // - If the declaration is a non-dependent friend declaration that nominates a
1710 // function with a declarator-id that is a qualified-id or template-id or that
1711 // nominates a class other than with an elaborated-type-specifier with neither
1712 // a nested-name-specifier nor a simple-template-id, it is attached to the
1713 // module to which the friend is attached ([basic.link]).
1714 if (New->getFriendObjectKind() &&
1715 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1716 New->setLocalOwningModule(Old->getOwningModule());
1718 return false;
1719 }
1720
1721 // Although we have questions for the module ownership of implicit
1722 // instantiations, it should be sure that we shouldn't diagnose the
1723 // redeclaration of incorrect module ownership for different implicit
1724 // instantiations in different modules. We will diagnose the redeclaration of
1725 // incorrect module ownership for the template itself.
1727 return false;
1728
1729 Module *NewM = New->getOwningModule();
1730 Module *OldM = Old->getOwningModule();
1731
1732 if (NewM && NewM->isPrivateModule())
1733 NewM = NewM->Parent;
1734 if (OldM && OldM->isPrivateModule())
1735 OldM = OldM->Parent;
1736
1737 if (NewM == OldM)
1738 return false;
1739
1740 if (NewM && OldM) {
1741 // A module implementation unit has visibility of the decls in its
1742 // implicitly imported interface.
1743 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1744 return false;
1745
1746 // Partitions are part of the module, but a partition could import another
1747 // module, so verify that the PMIs agree.
1748 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1749 getASTContext().isInSameModule(NewM, OldM))
1750 return false;
1751 }
1752
1753 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1754 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1755 if (NewIsModuleInterface || OldIsModuleInterface) {
1756 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1757 // if a declaration of D [...] appears in the purview of a module, all
1758 // other such declarations shall appear in the purview of the same module
1759 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1760 << New
1761 << NewIsModuleInterface
1762 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1763 << OldIsModuleInterface
1764 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1765 Diag(Old->getLocation(), diag::note_previous_declaration);
1766 New->setInvalidDecl();
1767 return true;
1768 }
1769
1770 return false;
1771}
1772
1774 // [module.interface]p1:
1775 // An export-declaration shall inhabit a namespace scope.
1776 //
1777 // So it is meaningless to talk about redeclaration which is not at namespace
1778 // scope.
1779 if (!New->getLexicalDeclContext()
1780 ->getNonTransparentContext()
1781 ->isFileContext() ||
1782 !Old->getLexicalDeclContext()
1784 ->isFileContext())
1785 return false;
1786
1787 bool IsNewExported = New->isInExportDeclContext();
1788 bool IsOldExported = Old->isInExportDeclContext();
1789
1790 // It should be irrevelant if both of them are not exported.
1791 if (!IsNewExported && !IsOldExported)
1792 return false;
1793
1794 if (IsOldExported)
1795 return false;
1796
1797 // If the Old declaration are not attached to named modules
1798 // and the New declaration are attached to global module.
1799 // It should be fine to allow the export since it doesn't change
1800 // the linkage of declarations. See
1801 // https://github.com/llvm/llvm-project/issues/98583 for details.
1802 if (!Old->isInNamedModule() && New->getOwningModule() &&
1803 New->getOwningModule()->isImplicitGlobalModule())
1804 return false;
1805
1806 assert(IsNewExported);
1807
1808 auto Lk = Old->getFormalLinkage();
1809 int S = 0;
1810 if (Lk == Linkage::Internal)
1811 S = 1;
1812 else if (Lk == Linkage::Module)
1813 S = 2;
1814 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1815 Diag(Old->getLocation(), diag::note_previous_declaration);
1816 return true;
1817}
1818
1821 return true;
1822
1824 return true;
1825
1826 return false;
1827}
1828
1830 const NamedDecl *Old) const {
1831 assert(getASTContext().isSameEntity(New, Old) &&
1832 "New and Old are not the same definition, we should diagnostic it "
1833 "immediately instead of checking it.");
1834 assert(const_cast<Sema *>(this)->isReachable(New) &&
1835 const_cast<Sema *>(this)->isReachable(Old) &&
1836 "We shouldn't see unreachable definitions here.");
1837
1838 Module *NewM = New->getOwningModule();
1839 Module *OldM = Old->getOwningModule();
1840
1841 // We only checks for named modules here. The header like modules is skipped.
1842 // FIXME: This is not right if we import the header like modules in the module
1843 // purview.
1844 //
1845 // For example, assuming "header.h" provides definition for `D`.
1846 // ```C++
1847 // //--- M.cppm
1848 // export module M;
1849 // import "header.h"; // or #include "header.h" but import it by clang modules
1850 // actually.
1851 //
1852 // //--- Use.cpp
1853 // import M;
1854 // import "header.h"; // or uses clang modules.
1855 // ```
1856 //
1857 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1858 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1859 // reject it. But the current implementation couldn't detect the case since we
1860 // don't record the information about the importee modules.
1861 //
1862 // But this might not be painful in practice. Since the design of C++20 Named
1863 // Modules suggests us to use headers in global module fragment instead of
1864 // module purview.
1865 if (NewM && NewM->isHeaderLikeModule())
1866 NewM = nullptr;
1867 if (OldM && OldM->isHeaderLikeModule())
1868 OldM = nullptr;
1869
1870 if (!NewM && !OldM)
1871 return true;
1872
1873 // [basic.def.odr]p14.3
1874 // Each such definition shall not be attached to a named module
1875 // ([module.unit]).
1876 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1877 return true;
1878
1879 // Then New and Old lives in the same TU if their share one same module unit.
1880 if (NewM)
1881 NewM = NewM->getTopLevelModule();
1882 if (OldM)
1883 OldM = OldM->getTopLevelModule();
1884 return OldM == NewM;
1885}
1886
1888 if (D->getDeclContext()->isFileContext())
1889 return false;
1890
1891 return isa<UsingShadowDecl>(D) ||
1894}
1895
1896/// Removes using shadow declarations not at class scope from the lookup
1897/// results.
1899 LookupResult::Filter F = R.makeFilter();
1900 while (F.hasNext())
1902 F.erase();
1903
1904 F.done();
1905}
1906
1907/// Check for this common pattern:
1908/// @code
1909/// class S {
1910/// S(const S&); // DO NOT IMPLEMENT
1911/// void operator=(const S&); // DO NOT IMPLEMENT
1912/// };
1913/// @endcode
1915 // FIXME: Should check for private access too but access is set after we get
1916 // the decl here.
1918 return false;
1919
1920 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1921 return CD->isCopyConstructor();
1922 return D->isCopyAssignmentOperator();
1923}
1924
1925bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1926 const DeclContext *DC = D->getDeclContext();
1927 while (!DC->isTranslationUnit()) {
1928 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1929 if (!RD->hasNameForLinkage())
1930 return true;
1931 }
1932 DC = DC->getParent();
1933 }
1934
1935 return !D->isExternallyVisible();
1936}
1937
1939 assert(D);
1940
1941 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1942 return false;
1943
1944 // Ignore all entities declared within templates, and out-of-line definitions
1945 // of members of class templates.
1946 if (D->getDeclContext()->isDependentContext() ||
1948 return false;
1949
1950 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1951 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1952 return false;
1953 // A non-out-of-line declaration of a member specialization was implicitly
1954 // instantiated; it's the out-of-line declaration that we're interested in.
1955 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1956 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1957 return false;
1958
1959 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1960 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1961 return false;
1962 } else {
1963 // 'static inline' functions are defined in headers; don't warn.
1964 if (FD->isInlined() && !isMainFileLoc(FD->getLocation()))
1965 return false;
1966 }
1967
1968 if (FD->doesThisDeclarationHaveABody() &&
1969 Context.DeclMustBeEmitted(FD))
1970 return false;
1971 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1972 // Constants and utility variables are defined in headers with internal
1973 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1974 // like "inline".)
1975 if (!isMainFileLoc(VD->getLocation()))
1976 return false;
1977
1978 if (Context.DeclMustBeEmitted(VD))
1979 return false;
1980
1981 if (VD->isStaticDataMember() &&
1982 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1983 return false;
1984 if (VD->isStaticDataMember() &&
1985 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1986 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1987 return false;
1988
1989 if (VD->isInline() && !isMainFileLoc(VD->getLocation()))
1990 return false;
1991 } else {
1992 return false;
1993 }
1994
1995 // Only warn for unused decls internal to the translation unit.
1996 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1997 // for inline functions defined in the main source file, for instance.
1998 return mightHaveNonExternalLinkage(D);
1999}
2000
2002 if (!D)
2003 return;
2004
2005 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2006 const FunctionDecl *First = FD->getFirstDecl();
2008 return; // First should already be in the vector.
2009 }
2010
2011 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2012 const VarDecl *First = VD->getFirstDecl();
2014 return; // First should already be in the vector.
2015 }
2016
2018 UnusedFileScopedDecls.push_back(D);
2019}
2020
2021static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2022 const NamedDecl *D) {
2023 if (D->isInvalidDecl())
2024 return false;
2025
2026 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2027 // For a decomposition declaration, warn if none of the bindings are
2028 // referenced, instead of if the variable itself is referenced (which
2029 // it is, by the bindings' expressions).
2030 bool IsAllIgnored = true;
2031 for (const auto *BD : DD->bindings()) {
2032 if (BD->isReferenced())
2033 return false;
2034 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2035 BD->hasAttr<UnusedAttr>());
2036 }
2037 if (IsAllIgnored)
2038 return false;
2039 } else if (!D->getDeclName()) {
2040 return false;
2041 } else if (D->isReferenced() || D->isUsed()) {
2042 return false;
2043 }
2044
2045 if (D->isPlaceholderVar(LangOpts))
2046 return false;
2047
2048 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2049 D->hasAttr<CleanupAttr>())
2050 return false;
2051
2052 if (isa<LabelDecl>(D))
2053 return true;
2054
2055 // Except for labels, we only care about unused decls that are local to
2056 // functions.
2057 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2058 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2059 // For dependent types, the diagnostic is deferred.
2060 WithinFunction =
2061 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2062 if (!WithinFunction)
2063 return false;
2064
2065 if (isa<TypedefNameDecl>(D))
2066 return true;
2067
2068 // White-list anything that isn't a local variable.
2070 return false;
2071
2072 // Types of valid local variables should be complete, so this should succeed.
2073 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2074
2075 const Expr *Init = VD->getInit();
2076 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2077 Init = Cleanups->getSubExpr();
2078
2079 const auto *Ty = VD->getType().getTypePtr();
2080
2081 // Only look at the outermost level of typedef.
2082 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2083 // Allow anything marked with __attribute__((unused)).
2084 if (TT->getDecl()->hasAttr<UnusedAttr>())
2085 return false;
2086 }
2087
2088 // Warn for reference variables whose initializtion performs lifetime
2089 // extension.
2090 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2091 MTE && MTE->getExtendingDecl()) {
2092 Ty = VD->getType().getNonReferenceType().getTypePtr();
2093 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2094 }
2095
2096 // If we failed to complete the type for some reason, or if the type is
2097 // dependent, don't diagnose the variable.
2098 if (Ty->isIncompleteType() || Ty->isDependentType())
2099 return false;
2100
2101 // Look at the element type to ensure that the warning behaviour is
2102 // consistent for both scalars and arrays.
2103 Ty = Ty->getBaseElementTypeUnsafe();
2104
2105 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2106 if (Tag->hasAttr<UnusedAttr>())
2107 return false;
2108
2109 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2110 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2111 return false;
2112
2113 if (Init) {
2114 const auto *Construct =
2115 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2116 if (Construct && !Construct->isElidable()) {
2117 const CXXConstructorDecl *CD = Construct->getConstructor();
2118 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2119 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2120 return false;
2121 }
2122
2123 // Suppress the warning if we don't know how this is constructed, and
2124 // it could possibly be non-trivial constructor.
2125 if (Init->isTypeDependent()) {
2126 for (const CXXConstructorDecl *Ctor : RD->ctors())
2127 if (!Ctor->isTrivial())
2128 return false;
2129 }
2130
2131 // Suppress the warning if the constructor is unresolved because
2132 // its arguments are dependent.
2134 return false;
2135 }
2136 }
2137 }
2138
2139 // TODO: __attribute__((unused)) templates?
2140 }
2141
2142 return true;
2143}
2144
2146 FixItHint &Hint) {
2147 if (isa<LabelDecl>(D)) {
2149 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2150 /*SkipTrailingWhitespaceAndNewline=*/false);
2151 if (AfterColon.isInvalid())
2152 return;
2154 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2155 }
2156}
2157
2160 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2161}
2162
2164 DiagReceiverTy DiagReceiver) {
2165 if (D->isDependentType())
2166 return;
2167
2168 for (auto *TmpD : D->decls()) {
2169 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2170 DiagnoseUnusedDecl(T, DiagReceiver);
2171 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2172 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2173 }
2174}
2175
2178 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2179}
2180
2183 return;
2184
2185 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2186 // typedefs can be referenced later on, so the diagnostics are emitted
2187 // at end-of-translation-unit.
2189 return;
2190 }
2191
2192 FixItHint Hint;
2194
2195 unsigned DiagID;
2196 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2197 DiagID = diag::warn_unused_exception_param;
2198 else if (isa<LabelDecl>(D))
2199 DiagID = diag::warn_unused_label;
2200 else
2201 DiagID = diag::warn_unused_variable;
2202
2203 SourceLocation DiagLoc = D->getLocation();
2204 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2205}
2206
2208 DiagReceiverTy DiagReceiver) {
2209 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2210 // it's not really unused.
2211 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2212 return;
2213
2214 // In C++, `_` variables behave as if they were maybe_unused
2215 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2216 return;
2217
2218 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2219
2220 if (Ty->isReferenceType() || Ty->isDependentType())
2221 return;
2222
2223 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2224 if (Tag->hasAttr<UnusedAttr>())
2225 return;
2226 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2227 // mimic gcc's behavior.
2228 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2229 RD && !RD->hasAttr<WarnUnusedAttr>())
2230 return;
2231 }
2232
2233 // Don't warn on volatile file-scope variables. They are visible beyond their
2234 // declaring function and writes to them could be observable side effects.
2235 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2236 return;
2237
2238 // Don't warn about __block Objective-C pointer variables, as they might
2239 // be assigned in the block but not used elsewhere for the purpose of lifetime
2240 // extension.
2241 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2242 return;
2243
2244 // Don't warn about Objective-C pointer variables with precise lifetime
2245 // semantics; they can be used to ensure ARC releases the object at a known
2246 // time, which may mean assignment but no other references.
2247 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2248 return;
2249
2250 auto iter = RefsMinusAssignments.find(VD->getCanonicalDecl());
2251 if (iter == RefsMinusAssignments.end())
2252 return;
2253
2254 assert(iter->getSecond() >= 0 &&
2255 "Found a negative number of references to a VarDecl");
2256 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2257 // Assume the given VarDecl is "used" if its ref count stored in
2258 // `RefMinusAssignments` is positive, with one exception.
2259 //
2260 // For a C++ variable whose decl (with initializer) entirely consist the
2261 // condition expression of a if/while/for construct,
2262 // Clang creates a DeclRefExpr for the condition expression rather than a
2263 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2264 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2265 // used in the body of the if/while/for construct.
2266 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2267 if (!UnusedCXXCondDecl)
2268 return;
2269 }
2270
2271 unsigned DiagID;
2272 if (isa<ParmVarDecl>(VD))
2273 DiagID = diag::warn_unused_but_set_parameter;
2274 else if (VD->isFileVarDecl())
2275 DiagID = diag::warn_unused_but_set_global;
2276 else
2277 DiagID = diag::warn_unused_but_set_variable;
2278 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2279}
2280
2282 Sema::DiagReceiverTy DiagReceiver) {
2283 // Verify that we have no forward references left. If so, there was a goto
2284 // or address of a label taken, but no definition of it. Label fwd
2285 // definitions are indicated with a null substmt which is also not a resolved
2286 // MS inline assembly label name.
2287 bool Diagnose = false;
2288 if (L->isMSAsmLabel())
2289 Diagnose = !L->isResolvedMSAsmLabel();
2290 else
2291 Diagnose = L->getStmt() == nullptr;
2292 if (Diagnose)
2293 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2294 << L);
2295}
2296
2298 S->applyNRVO();
2299
2300 if (S->decl_empty()) return;
2302 "Scope shouldn't contain decls!");
2303
2304 /// We visit the decls in non-deterministic order, but we want diagnostics
2305 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2306 /// and sort the diagnostics before emitting them, after we visited all decls.
2307 struct LocAndDiag {
2308 SourceLocation Loc;
2309 std::optional<SourceLocation> PreviousDeclLoc;
2311 };
2313 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2314 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2315 };
2316 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2317 SourceLocation PreviousDeclLoc,
2318 PartialDiagnostic PD) {
2319 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2320 };
2321
2322 for (auto *TmpD : S->decls()) {
2323 assert(TmpD && "This decl didn't get pushed??");
2324
2325 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2326 NamedDecl *D = cast<NamedDecl>(TmpD);
2327
2328 // Diagnose unused variables in this scope.
2330 DiagnoseUnusedDecl(D, addDiag);
2331 if (const auto *RD = dyn_cast<RecordDecl>(D))
2332 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2333 // Wait until end of TU to diagnose internal linkage file vars.
2334 if (auto *VD = dyn_cast<VarDecl>(D);
2335 VD && !VD->isInternalLinkageFileVar()) {
2336 DiagnoseUnusedButSetDecl(VD, addDiag);
2337 RefsMinusAssignments.erase(VD->getCanonicalDecl());
2338 }
2339 }
2340
2341 if (!D->getDeclName()) continue;
2342
2343 // If this was a forward reference to a label, verify it was defined.
2344 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2345 CheckPoppedLabel(LD, *this, addDiag);
2346
2347 // Partial translation units that are created in incremental processing must
2348 // not clean up the IdResolver because PTUs should take into account the
2349 // declarations that came from previous PTUs.
2350 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2352 IdResolver.RemoveDecl(D);
2353
2354 // Warn on it if we are shadowing a declaration.
2355 auto ShadowI = ShadowingDecls.find(D);
2356 if (ShadowI != ShadowingDecls.end()) {
2357 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2358 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2359 PDiag(diag::warn_ctor_parm_shadows_field)
2360 << D << FD << FD->getParent());
2361 }
2362 ShadowingDecls.erase(ShadowI);
2363 }
2364 }
2365
2366 llvm::sort(DeclDiags,
2367 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2368 // The particular order for diagnostics is not important, as long
2369 // as the order is deterministic. Using the raw location is going
2370 // to generally be in source order unless there are macro
2371 // expansions involved.
2372 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2373 });
2374 for (const LocAndDiag &D : DeclDiags) {
2375 Diag(D.Loc, D.PD);
2376 if (D.PreviousDeclLoc)
2377 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2378 }
2379}
2380
2382 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2383 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2384 (S->isClassScope() && !getLangOpts().CPlusPlus))
2385 S = S->getParent();
2386 return S;
2387}
2388
2389static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2391 switch (Error) {
2393 return "";
2395 return BuiltinInfo.getHeaderName(ID);
2397 return "stdio.h";
2399 return "setjmp.h";
2401 return "ucontext.h";
2402 }
2403 llvm_unreachable("unhandled error kind");
2404}
2405
2407 unsigned ID, SourceLocation Loc) {
2408 DeclContext *Parent = Context.getTranslationUnitDecl();
2409
2410 if (getLangOpts().CPlusPlus) {
2412 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2413 CLinkageDecl->setImplicit();
2414 Parent->addDecl(CLinkageDecl);
2415 Parent = CLinkageDecl;
2416 }
2417
2419 if (Context.BuiltinInfo.isImmediate(ID)) {
2420 assert(getLangOpts().CPlusPlus20 &&
2421 "consteval builtins should only be available in C++20 mode");
2422 ConstexprKind = ConstexprSpecKind::Consteval;
2423 }
2424
2426 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2427 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2428 Type->isFunctionProtoType(), ConstexprKind);
2429 New->setImplicit();
2430 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2431
2432 // Create Decl objects for each parameter, adding them to the
2433 // FunctionDecl.
2434 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2436 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2438 Context, New, SourceLocation(), SourceLocation(), nullptr,
2439 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2440 parm->setScopeInfo(0, i);
2441 Params.push_back(parm);
2442 }
2443 New->setParams(Params);
2444 }
2445
2447 return New;
2448}
2449
2451 Scope *S, bool ForRedeclaration,
2452 SourceLocation Loc) {
2454
2456 QualType R = Context.GetBuiltinType(ID, Error);
2457 if (Error) {
2458 if (!ForRedeclaration)
2459 return nullptr;
2460
2461 // If we have a builtin without an associated type we should not emit a
2462 // warning when we were not able to find a type for it.
2464 Context.BuiltinInfo.allowTypeMismatch(ID))
2465 return nullptr;
2466
2467 // If we could not find a type for setjmp it is because the jmp_buf type was
2468 // not defined prior to the setjmp declaration.
2470 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2471 << Context.BuiltinInfo.getName(ID);
2472 return nullptr;
2473 }
2474
2475 // Generally, we emit a warning that the declaration requires the
2476 // appropriate header.
2477 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2478 << getHeaderName(Context.BuiltinInfo, ID, Error)
2479 << Context.BuiltinInfo.getName(ID);
2480 return nullptr;
2481 }
2482
2483 if (!ForRedeclaration &&
2484 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2485 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2486 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2487 : diag::ext_implicit_lib_function_decl)
2488 << Context.BuiltinInfo.getName(ID) << R;
2489 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2490 Diag(Loc, diag::note_include_header_or_declare)
2491 << Header << Context.BuiltinInfo.getName(ID);
2492 }
2493
2494 if (R.isNull())
2495 return nullptr;
2496
2497 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2499
2500 // TUScope is the translation-unit scope to insert this function into.
2501 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2502 // relate Scopes to DeclContexts, and probably eliminate CurContext
2503 // entirely, but we're not there yet.
2504 DeclContext *SavedContext = CurContext;
2505 CurContext = New->getDeclContext();
2507 CurContext = SavedContext;
2508 return New;
2509}
2510
2511/// Typedef declarations don't have linkage, but they still denote the same
2512/// entity if their types are the same.
2513/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2514/// isSameEntity.
2515static void
2518 // This is only interesting when modules are enabled.
2519 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2520 return;
2521
2522 // Empty sets are uninteresting.
2523 if (Previous.empty())
2524 return;
2525
2526 LookupResult::Filter Filter = Previous.makeFilter();
2527 while (Filter.hasNext()) {
2528 NamedDecl *Old = Filter.next();
2529
2530 // Non-hidden declarations are never ignored.
2531 if (S.isVisible(Old))
2532 continue;
2533
2534 // Declarations of the same entity are not ignored, even if they have
2535 // different linkages.
2536 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2537 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2538 Decl->getUnderlyingType()))
2539 continue;
2540
2541 // If both declarations give a tag declaration a typedef name for linkage
2542 // purposes, then they declare the same entity.
2543 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2544 Decl->getAnonDeclWithTypedefName())
2545 continue;
2546 }
2547
2548 Filter.erase();
2549 }
2550
2551 Filter.done();
2552}
2553
2555 QualType OldType;
2556 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2557 OldType = OldTypedef->getUnderlyingType();
2558 else
2559 OldType = Context.getTypeDeclType(Old);
2560 QualType NewType = New->getUnderlyingType();
2561
2562 if (NewType->isVariablyModifiedType()) {
2563 // Must not redefine a typedef with a variably-modified type.
2564 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2565 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2566 << Kind << NewType;
2567 if (Old->getLocation().isValid())
2568 notePreviousDefinition(Old, New->getLocation());
2569 New->setInvalidDecl();
2570 return true;
2571 }
2572
2573 if (OldType != NewType &&
2574 !OldType->isDependentType() &&
2575 !NewType->isDependentType() &&
2576 !Context.hasSameType(OldType, NewType)) {
2577 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2578 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2579 << Kind << NewType << OldType;
2580 if (Old->getLocation().isValid())
2581 notePreviousDefinition(Old, New->getLocation());
2582 New->setInvalidDecl();
2583 return true;
2584 }
2585 return false;
2586}
2587
2589 LookupResult &OldDecls) {
2590 // If the new decl is known invalid already, don't bother doing any
2591 // merging checks.
2592 if (New->isInvalidDecl()) return;
2593
2594 // Allow multiple definitions for ObjC built-in typedefs.
2595 // FIXME: Verify the underlying types are equivalent!
2596 if (getLangOpts().ObjC) {
2597 const IdentifierInfo *TypeID = New->getIdentifier();
2598 switch (TypeID->getLength()) {
2599 default: break;
2600 case 2:
2601 {
2602 if (!TypeID->isStr("id"))
2603 break;
2604 QualType T = New->getUnderlyingType();
2605 if (!T->isPointerType())
2606 break;
2607 if (!T->isVoidPointerType()) {
2609 if (!PT->isStructureType())
2610 break;
2611 }
2612 Context.setObjCIdRedefinitionType(T);
2613 // Install the built-in type for 'id', ignoring the current definition.
2614 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2615 Context.getObjCIdType());
2616 return;
2617 }
2618 case 5:
2619 if (!TypeID->isStr("Class"))
2620 break;
2621 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2622 // Install the built-in type for 'Class', ignoring the current definition.
2623 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2624 Context.getObjCClassType());
2625 return;
2626 case 3:
2627 if (!TypeID->isStr("SEL"))
2628 break;
2629 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2630 // Install the built-in type for 'SEL', ignoring the current definition.
2631 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2632 Context.getObjCSelType());
2633 return;
2634 }
2635 // Fall through - the typedef name was not a builtin type.
2636 }
2637
2638 // Verify the old decl was also a type.
2639 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2640 if (!Old) {
2641 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2642 << New->getDeclName();
2643
2644 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2645 if (OldD->getLocation().isValid())
2646 notePreviousDefinition(OldD, New->getLocation());
2647
2648 return New->setInvalidDecl();
2649 }
2650
2651 // If the old declaration is invalid, just give up here.
2652 if (Old->isInvalidDecl())
2653 return New->setInvalidDecl();
2654
2655 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2656 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2657 auto *NewTag = New->getAnonDeclWithTypedefName();
2658 NamedDecl *Hidden = nullptr;
2659 if (OldTag && NewTag &&
2660 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2661 !hasVisibleDefinition(OldTag, &Hidden)) {
2662 // There is a definition of this tag, but it is not visible. Use it
2663 // instead of our tag.
2664 if (OldTD->isModed())
2665 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2666 OldTD->getUnderlyingType());
2667 else
2668 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2669
2670 // Make the old tag definition visible.
2672
2674 }
2675 }
2676
2677 // If the typedef types are not identical, reject them in all languages and
2678 // with any extensions enabled.
2679 if (isIncompatibleTypedef(Old, New))
2680 return;
2681
2682 // The types match. Link up the redeclaration chain and merge attributes if
2683 // the old declaration was a typedef.
2684 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2685 New->setPreviousDecl(Typedef);
2687 }
2688
2689 if (getLangOpts().MicrosoftExt)
2690 return;
2691
2692 if (getLangOpts().CPlusPlus) {
2693 // C++ [dcl.typedef]p2:
2694 // In a given non-class scope, a typedef specifier can be used to
2695 // redefine the name of any type declared in that scope to refer
2696 // to the type to which it already refers.
2698 return;
2699
2700 // C++0x [dcl.typedef]p4:
2701 // In a given class scope, a typedef specifier can be used to redefine
2702 // any class-name declared in that scope that is not also a typedef-name
2703 // to refer to the type to which it already refers.
2704 //
2705 // This wording came in via DR424, which was a correction to the
2706 // wording in DR56, which accidentally banned code like:
2707 //
2708 // struct S {
2709 // typedef struct A { } A;
2710 // };
2711 //
2712 // in the C++03 standard. We implement the C++0x semantics, which
2713 // allow the above but disallow
2714 //
2715 // struct S {
2716 // typedef int I;
2717 // typedef int I;
2718 // };
2719 //
2720 // since that was the intent of DR56.
2721 if (!isa<TypedefNameDecl>(Old))
2722 return;
2723
2724 Diag(New->getLocation(), diag::err_redefinition)
2725 << New->getDeclName();
2726 notePreviousDefinition(Old, New->getLocation());
2727 return New->setInvalidDecl();
2728 }
2729
2730 // Modules always permit redefinition of typedefs, as does C11.
2731 if (getLangOpts().Modules || getLangOpts().C11)
2732 return;
2733
2734 // If we have a redefinition of a typedef in C, emit a warning. This warning
2735 // is normally mapped to an error, but can be controlled with
2736 // -Wtypedef-redefinition. If either the original or the redefinition is
2737 // in a system header, don't emit this for compatibility with GCC.
2738 if (getDiagnostics().getSuppressSystemWarnings() &&
2739 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2740 (Old->isImplicit() ||
2741 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2742 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2743 return;
2744
2745 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2746 << New->getDeclName();
2747 notePreviousDefinition(Old, New->getLocation());
2748}
2749
2751 // If this was an unscoped enumeration, yank all of its enumerators
2752 // out of the scope.
2753 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2754 Scope *EnumScope = getNonFieldDeclScope(S);
2755 for (auto *ECD : ED->enumerators()) {
2756 assert(EnumScope->isDeclScope(ECD));
2757 EnumScope->RemoveDecl(ECD);
2758 IdResolver.RemoveDecl(ECD);
2759 }
2760 }
2761}
2762
2763/// DeclhasAttr - returns true if decl Declaration already has the target
2764/// attribute.
2765static bool DeclHasAttr(const Decl *D, const Attr *A) {
2766 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2767 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2768 for (const auto *i : D->attrs())
2769 if (i->getKind() == A->getKind()) {
2770 if (Ann) {
2771 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2772 return true;
2773 continue;
2774 }
2775 // FIXME: Don't hardcode this check
2776 if (OA && isa<OwnershipAttr>(i))
2777 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2778 return true;
2779 }
2780
2781 return false;
2782}
2783
2785 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2786 return VD->isThisDeclarationADefinition();
2787 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2788 return TD->isCompleteDefinition() || TD->isBeingDefined();
2789 return true;
2790}
2791
2792/// Merge alignment attributes from \p Old to \p New, taking into account the
2793/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2794///
2795/// \return \c true if any attributes were added to \p New.
2796static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2797 // Look for alignas attributes on Old, and pick out whichever attribute
2798 // specifies the strictest alignment requirement.
2799 AlignedAttr *OldAlignasAttr = nullptr;
2800 AlignedAttr *OldStrictestAlignAttr = nullptr;
2801 unsigned OldAlign = 0;
2802 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2803 // FIXME: We have no way of representing inherited dependent alignments
2804 // in a case like:
2805 // template<int A, int B> struct alignas(A) X;
2806 // template<int A, int B> struct alignas(B) X {};
2807 // For now, we just ignore any alignas attributes which are not on the
2808 // definition in such a case.
2809 if (I->isAlignmentDependent())
2810 return false;
2811
2812 if (I->isAlignas())
2813 OldAlignasAttr = I;
2814
2815 unsigned Align = I->getAlignment(S.Context);
2816 if (Align > OldAlign) {
2817 OldAlign = Align;
2818 OldStrictestAlignAttr = I;
2819 }
2820 }
2821
2822 // Look for alignas attributes on New.
2823 AlignedAttr *NewAlignasAttr = nullptr;
2824 unsigned NewAlign = 0;
2825 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2826 if (I->isAlignmentDependent())
2827 return false;
2828
2829 if (I->isAlignas())
2830 NewAlignasAttr = I;
2831
2832 unsigned Align = I->getAlignment(S.Context);
2833 if (Align > NewAlign)
2834 NewAlign = Align;
2835 }
2836
2837 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2838 // Both declarations have 'alignas' attributes. We require them to match.
2839 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2840 // fall short. (If two declarations both have alignas, they must both match
2841 // every definition, and so must match each other if there is a definition.)
2842
2843 // If either declaration only contains 'alignas(0)' specifiers, then it
2844 // specifies the natural alignment for the type.
2845 if (OldAlign == 0 || NewAlign == 0) {
2846 QualType Ty;
2847 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2848 Ty = VD->getType();
2849 else
2851
2852 if (OldAlign == 0)
2853 OldAlign = S.Context.getTypeAlign(Ty);
2854 if (NewAlign == 0)
2855 NewAlign = S.Context.getTypeAlign(Ty);
2856 }
2857
2858 if (OldAlign != NewAlign) {
2859 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2862 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2863 }
2864 }
2865
2866 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2867 // C++11 [dcl.align]p6:
2868 // if any declaration of an entity has an alignment-specifier,
2869 // every defining declaration of that entity shall specify an
2870 // equivalent alignment.
2871 // C11 6.7.5/7:
2872 // If the definition of an object does not have an alignment
2873 // specifier, any other declaration of that object shall also
2874 // have no alignment specifier.
2875 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2876 << OldAlignasAttr;
2877 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2878 << OldAlignasAttr;
2879 }
2880
2881 bool AnyAdded = false;
2882
2883 // Ensure we have an attribute representing the strictest alignment.
2884 if (OldAlign > NewAlign) {
2885 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2886 Clone->setInherited(true);
2887 New->addAttr(Clone);
2888 AnyAdded = true;
2889 }
2890
2891 // Ensure we have an alignas attribute if the old declaration had one.
2892 if (OldAlignasAttr && !NewAlignasAttr &&
2893 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2894 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2895 Clone->setInherited(true);
2896 New->addAttr(Clone);
2897 AnyAdded = true;
2898 }
2899
2900 return AnyAdded;
2901}
2902
2903#define WANT_DECL_MERGE_LOGIC
2904#include "clang/Sema/AttrParsedAttrImpl.inc"
2905#undef WANT_DECL_MERGE_LOGIC
2906
2908 const InheritableAttr *Attr,
2910 // Diagnose any mutual exclusions between the attribute that we want to add
2911 // and attributes that already exist on the declaration.
2912 if (!DiagnoseMutualExclusions(S, D, Attr))
2913 return false;
2914
2915 // This function copies an attribute Attr from a previous declaration to the
2916 // new declaration D if the new declaration doesn't itself have that attribute
2917 // yet or if that attribute allows duplicates.
2918 // If you're adding a new attribute that requires logic different from
2919 // "use explicit attribute on decl if present, else use attribute from
2920 // previous decl", for example if the attribute needs to be consistent
2921 // between redeclarations, you need to call a custom merge function here.
2922 InheritableAttr *NewAttr = nullptr;
2923 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) {
2924 const IdentifierInfo *InferredPlatformII = nullptr;
2925 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2926 InferredPlatformII = Inf->getPlatform();
2928 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2929 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2930 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2931 AA->getPriority(), AA->getEnvironment(), InferredPlatformII);
2932 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2933 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2934 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2935 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2936 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2937 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2938 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2939 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2940 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2941 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2942 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2943 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2944 FA->getFirstArg());
2945 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2946 NewAttr = S.mergeFormatMatchesAttr(
2947 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2948 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2949 NewAttr = S.mergeModularFormatAttr(
2950 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2951 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2952 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2953 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2954 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2955 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2956 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2957 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2958 IA->getInheritanceModel());
2959 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2960 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2961 &S.Context.Idents.get(AA->getSpelling()));
2962 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2965 // CUDA target attributes are part of function signature for
2966 // overloading purposes and must not be merged.
2967 return false;
2968 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2969 NewAttr = S.mergeMinSizeAttr(D, *MA);
2970 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2971 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2972 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2973 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2974 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2975 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2976 else if (isa<AlignedAttr>(Attr))
2977 // AlignedAttrs are handled separately, because we need to handle all
2978 // such attributes on a declaration at the same time.
2979 NewAttr = nullptr;
2984 NewAttr = nullptr;
2985 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2986 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2987 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2988 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2989 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2990 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2991 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2992 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2993 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2994 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2995 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2996 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2997 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2998 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2999 NT->getZ());
3000 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
3001 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
3002 WS->getPreferred(),
3003 WS->getSpelledArgsCount());
3004 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
3005 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
3006 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
3007 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
3008 else if (isa<SuppressAttr>(Attr))
3009 // Do nothing. Each redeclaration should be suppressed separately.
3010 NewAttr = nullptr;
3011 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
3012 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
3013 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
3014 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
3015 else if (const auto *PA = dyn_cast<PersonalityAttr>(Attr))
3016 NewAttr = S.mergePersonalityAttr(D, PA->getRoutine(), *PA);
3017
3018 if (NewAttr) {
3019 NewAttr->setInherited(true);
3020 D->addAttr(NewAttr);
3021 if (isa<MSInheritanceAttr>(NewAttr))
3023 return true;
3024 }
3025
3026 return false;
3027}
3028
3029static const NamedDecl *getDefinition(const Decl *D) {
3030 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3031 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3032 return Def;
3033 return nullptr;
3034 }
3035 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3036 const VarDecl *Def = VD->getDefinition();
3037 if (Def)
3038 return Def;
3039 return VD->getActingDefinition();
3040 }
3041 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3042 const FunctionDecl *Def = nullptr;
3043 if (FD->isDefined(Def, true))
3044 return Def;
3045 }
3046 return nullptr;
3047}
3048
3049static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3050 for (const auto *Attribute : D->attrs())
3051 if (Attribute->getKind() == Kind)
3052 return true;
3053 return false;
3054}
3055
3056/// checkNewAttributesAfterDef - If we already have a definition, check that
3057/// there are no new attributes in this declaration.
3058static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3059 if (!New->hasAttrs())
3060 return;
3061
3062 const NamedDecl *Def = getDefinition(Old);
3063 if (!Def || Def == New)
3064 return;
3065
3066 AttrVec &NewAttributes = New->getAttrs();
3067 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3068 Attr *NewAttribute = NewAttributes[I];
3069
3070 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3072 SkipBodyInfo SkipBody;
3073 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3074
3075 // If we're skipping this definition, drop the "alias" attribute.
3076 if (SkipBody.ShouldSkip) {
3077 NewAttributes.erase(NewAttributes.begin() + I);
3078 --E;
3079 continue;
3080 }
3081 } else {
3082 VarDecl *VD = cast<VarDecl>(New);
3083 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3085 ? diag::err_alias_after_tentative
3086 : diag::err_redefinition;
3087 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3088 if (Diag == diag::err_redefinition)
3089 S.notePreviousDefinition(Def, VD->getLocation());
3090 else
3091 S.Diag(Def->getLocation(), diag::note_previous_definition);
3092 VD->setInvalidDecl();
3093 }
3094 ++I;
3095 continue;
3096 }
3097
3098 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3099 // Tentative definitions are only interesting for the alias check above.
3100 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3101 ++I;
3102 continue;
3103 }
3104 }
3105
3106 if (hasAttribute(Def, NewAttribute->getKind())) {
3107 ++I;
3108 continue; // regular attr merging will take care of validating this.
3109 }
3110
3111 if (isa<C11NoReturnAttr>(NewAttribute)) {
3112 // C's _Noreturn is allowed to be added to a function after it is defined.
3113 ++I;
3114 continue;
3115 } else if (isa<UuidAttr>(NewAttribute)) {
3116 // msvc will allow a subsequent definition to add an uuid to a class
3117 ++I;
3118 continue;
3120 NewAttribute) &&
3121 NewAttribute->isStandardAttributeSyntax()) {
3122 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3123 // deprecated attribute can later be re-declared with the attribute and
3124 // vice-versa.
3125 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3126 // maybe_unused attribute can later be redeclared with the attribute and
3127 // vice versa.
3128 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3129 // nodiscard attribute can later be redeclared with the attribute and
3130 // vice-versa.
3131 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3132 ++I;
3133 continue;
3134 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3135 if (AA->isAlignas()) {
3136 // C++11 [dcl.align]p6:
3137 // if any declaration of an entity has an alignment-specifier,
3138 // every defining declaration of that entity shall specify an
3139 // equivalent alignment.
3140 // C11 6.7.5/7:
3141 // If the definition of an object does not have an alignment
3142 // specifier, any other declaration of that object shall also
3143 // have no alignment specifier.
3144 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3145 << AA;
3146 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3147 << AA;
3148 NewAttributes.erase(NewAttributes.begin() + I);
3149 --E;
3150 continue;
3151 }
3152 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3153 // If there is a C definition followed by a redeclaration with this
3154 // attribute then there are two different definitions. In C++, prefer the
3155 // standard diagnostics.
3156 if (!S.getLangOpts().CPlusPlus) {
3157 S.Diag(NewAttribute->getLocation(),
3158 diag::err_loader_uninitialized_redeclaration);
3159 S.Diag(Def->getLocation(), diag::note_previous_definition);
3160 NewAttributes.erase(NewAttributes.begin() + I);
3161 --E;
3162 continue;
3163 }
3164 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3165 cast<VarDecl>(New)->isInline() &&
3166 !cast<VarDecl>(New)->isInlineSpecified()) {
3167 // Don't warn about applying selectany to implicitly inline variables.
3168 // Older compilers and language modes would require the use of selectany
3169 // to make such variables inline, and it would have no effect if we
3170 // honored it.
3171 ++I;
3172 continue;
3173 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3174 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3175 // declarations after definitions.
3176 ++I;
3177 continue;
3178 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3179 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3180 // error since the definition will have already been created without
3181 // the semantic effects of the attribute having been applied.
3182 S.Diag(NewAttribute->getLocation(),
3183 diag::err_sycl_entry_point_after_definition)
3184 << NewAttribute;
3185 S.Diag(Def->getLocation(), diag::note_previous_definition);
3186 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3187 ++I;
3188 continue;
3189 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3190 // SYCLExternalAttr may be added after a definition.
3191 ++I;
3192 continue;
3193 }
3194
3195 S.Diag(NewAttribute->getLocation(),
3196 diag::warn_attribute_precede_definition);
3197 S.Diag(Def->getLocation(), diag::note_previous_definition);
3198 NewAttributes.erase(NewAttributes.begin() + I);
3199 --E;
3200 }
3201}
3202
3203static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3204 const ConstInitAttr *CIAttr,
3205 bool AttrBeforeInit) {
3206 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3207
3208 // Figure out a good way to write this specifier on the old declaration.
3209 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3210 // enough of the attribute list spelling information to extract that without
3211 // heroics.
3212 std::string SuitableSpelling;
3213 if (S.getLangOpts().CPlusPlus20)
3214 SuitableSpelling = std::string(
3215 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3216 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3217 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3218 InsertLoc, {tok::l_square, tok::l_square,
3219 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3220 S.PP.getIdentifierInfo("require_constant_initialization"),
3221 tok::r_square, tok::r_square}));
3222 if (SuitableSpelling.empty())
3223 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3224 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3225 S.PP.getIdentifierInfo("require_constant_initialization"),
3226 tok::r_paren, tok::r_paren}));
3227 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3228 SuitableSpelling = "constinit";
3229 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3230 SuitableSpelling = "[[clang::require_constant_initialization]]";
3231 if (SuitableSpelling.empty())
3232 SuitableSpelling = "__attribute__((require_constant_initialization))";
3233 SuitableSpelling += " ";
3234
3235 if (AttrBeforeInit) {
3236 // extern constinit int a;
3237 // int a = 0; // error (missing 'constinit'), accepted as extension
3238 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3239 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3240 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3241 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3242 } else {
3243 // int a = 0;
3244 // constinit extern int a; // error (missing 'constinit')
3245 S.Diag(CIAttr->getLocation(),
3246 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3247 : diag::warn_require_const_init_added_too_late)
3248 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3249 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3250 << CIAttr->isConstinit()
3251 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3252 }
3253}
3254
3257 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3258 UsedAttr *NewAttr = OldAttr->clone(Context);
3259 NewAttr->setInherited(true);
3260 New->addAttr(NewAttr);
3261 }
3262 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3263 RetainAttr *NewAttr = OldAttr->clone(Context);
3264 NewAttr->setInherited(true);
3265 New->addAttr(NewAttr);
3266 }
3267
3268 if (!Old->hasAttrs() && !New->hasAttrs())
3269 return;
3270
3271 // [dcl.constinit]p1:
3272 // If the [constinit] specifier is applied to any declaration of a
3273 // variable, it shall be applied to the initializing declaration.
3274 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3275 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3276 if (bool(OldConstInit) != bool(NewConstInit)) {
3277 const auto *OldVD = cast<VarDecl>(Old);
3278 auto *NewVD = cast<VarDecl>(New);
3279
3280 // Find the initializing declaration. Note that we might not have linked
3281 // the new declaration into the redeclaration chain yet.
3282 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3283 if (!InitDecl &&
3284 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3285 InitDecl = NewVD;
3286
3287 if (InitDecl == NewVD) {
3288 // This is the initializing declaration. If it would inherit 'constinit',
3289 // that's ill-formed. (Note that we do not apply this to the attribute
3290 // form).
3291 if (OldConstInit && OldConstInit->isConstinit())
3292 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3293 /*AttrBeforeInit=*/true);
3294 } else if (NewConstInit) {
3295 // This is the first time we've been told that this declaration should
3296 // have a constant initializer. If we already saw the initializing
3297 // declaration, this is too late.
3298 if (InitDecl && InitDecl != NewVD) {
3299 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3300 /*AttrBeforeInit=*/false);
3301 NewVD->dropAttr<ConstInitAttr>();
3302 }
3303 }
3304 }
3305
3306 // Attributes declared post-definition are currently ignored.
3307 checkNewAttributesAfterDef(*this, New, Old);
3308
3309 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3310 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3311 if (!OldA->isEquivalent(NewA)) {
3312 // This redeclaration changes __asm__ label.
3313 Diag(New->getLocation(), diag::err_different_asm_label);
3314 Diag(OldA->getLocation(), diag::note_previous_declaration);
3315 }
3316 } else if (Old->isUsed()) {
3317 // This redeclaration adds an __asm__ label to a declaration that has
3318 // already been ODR-used.
3319 Diag(New->getLocation(), diag::err_late_asm_label_name)
3320 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3321 }
3322 }
3323
3324 // Re-declaration cannot add abi_tag's.
3325 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3326 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3327 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3328 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3329 Diag(NewAbiTagAttr->getLocation(),
3330 diag::err_new_abi_tag_on_redeclaration)
3331 << NewTag;
3332 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3333 }
3334 }
3335 } else {
3336 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3337 Diag(Old->getLocation(), diag::note_previous_declaration);
3338 }
3339 }
3340
3341 // This redeclaration adds a section attribute.
3342 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3343 if (auto *VD = dyn_cast<VarDecl>(New)) {
3344 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3345 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3346 Diag(Old->getLocation(), diag::note_previous_declaration);
3347 }
3348 }
3349 }
3350
3351 // Redeclaration adds code-seg attribute.
3352 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3353 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3354 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3355 Diag(New->getLocation(), diag::warn_mismatched_section)
3356 << 0 /*codeseg*/;
3357 Diag(Old->getLocation(), diag::note_previous_declaration);
3358 }
3359
3360 if (!Old->hasAttrs())
3361 return;
3362
3363 bool foundAny = New->hasAttrs();
3364
3365 // Ensure that any moving of objects within the allocated map is done before
3366 // we process them.
3367 if (!foundAny) New->setAttrs(AttrVec());
3368
3369 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3370 // Ignore deprecated/unavailable/availability attributes if requested.
3372 if (isa<DeprecatedAttr>(I) ||
3375 switch (AMK) {
3377 continue;
3378
3383 LocalAMK = AMK;
3384 break;
3385 }
3386 }
3387
3388 // Already handled.
3389 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3390 continue;
3391
3393 if (auto *FD = dyn_cast<FunctionDecl>(New);
3394 FD &&
3395 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3396 continue; // Don't propagate inferred noreturn attributes to explicit
3397 }
3398
3399 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3400 foundAny = true;
3401 }
3402
3403 if (mergeAlignedAttrs(*this, New, Old))
3404 foundAny = true;
3405
3406 if (!foundAny) New->dropAttrs();
3407}
3408
3410 for (const Attr *A : D->attrs())
3411 checkAttrIsTypeDependent(D, A);
3412}
3413
3414// Returns the number of added attributes.
3415template <class T>
3416static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3417 Sema &S) {
3418 unsigned found = 0;
3419 for (const auto *I : From->specific_attrs<T>()) {
3420 if (!DeclHasAttr(To, I)) {
3421 T *newAttr = cast<T>(I->clone(S.Context));
3422 newAttr->setInherited(true);
3423 To->addAttr(newAttr);
3424 ++found;
3425 }
3426 }
3427 return found;
3428}
3429
3430template <class F>
3431static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3432 F &&propagator) {
3433 if (!From->hasAttrs()) {
3434 return;
3435 }
3436
3437 bool foundAny = To->hasAttrs();
3438
3439 // Ensure that any moving of objects within the allocated map is
3440 // done before we process them.
3441 if (!foundAny)
3442 To->setAttrs(AttrVec());
3443
3444 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3445
3446 if (!foundAny)
3447 To->dropAttrs();
3448}
3449
3450/// mergeParamDeclAttributes - Copy attributes from the old parameter
3451/// to the new one.
3453 const ParmVarDecl *oldDecl,
3454 Sema &S) {
3455 // C++11 [dcl.attr.depend]p2:
3456 // The first declaration of a function shall specify the
3457 // carries_dependency attribute for its declarator-id if any declaration
3458 // of the function specifies the carries_dependency attribute.
3459 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3460 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3461 S.Diag(CDA->getLocation(),
3462 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3463 // Find the first declaration of the parameter.
3464 // FIXME: Should we build redeclaration chains for function parameters?
3465 const FunctionDecl *FirstFD =
3466 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3467 const ParmVarDecl *FirstVD =
3468 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3469 S.Diag(FirstVD->getLocation(),
3470 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3471 }
3472
3474 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3475 unsigned found = 0;
3476 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3477 // Propagate the lifetimebound attribute from parameters to the
3478 // most recent declaration. Note that this doesn't include the implicit
3479 // 'this' parameter, as the attribute is applied to the function type in
3480 // that case.
3481 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3482 return found;
3483 });
3484}
3485
3487 const ASTContext &Ctx) {
3488
3489 auto NoSizeInfo = [&Ctx](QualType Ty) {
3490 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3491 return true;
3492 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3493 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3494 return false;
3495 };
3496
3497 // `type[]` is equivalent to `type *` and `type[*]`.
3498 if (NoSizeInfo(Old) && NoSizeInfo(New))
3499 return true;
3500
3501 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3502 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3503 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3504 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3505 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3506 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3507 return false;
3508 return true;
3509 }
3510
3511 // Only compare size, ignore Size modifiers and CVR.
3512 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3513 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3515 }
3516
3517 // Don't try to compare dependent sized array
3518 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3519 return true;
3520 }
3521
3522 return Old == New;
3523}
3524
3525static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3526 const ParmVarDecl *OldParam,
3527 Sema &S) {
3528 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3529 if (auto Newnullability = NewParam->getType()->getNullability()) {
3530 if (*Oldnullability != *Newnullability) {
3531 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3533 *Newnullability,
3535 != 0))
3537 *Oldnullability,
3539 != 0));
3540 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3541 }
3542 } else {
3543 QualType NewT = NewParam->getType();
3544 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3545 NewParam->setType(NewT);
3546 }
3547 }
3548 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3549 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3550 if (OldParamDT && NewParamDT &&
3551 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3552 QualType OldParamOT = OldParamDT->getOriginalType();
3553 QualType NewParamOT = NewParamDT->getOriginalType();
3554 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3555 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3556 << NewParam << NewParamOT;
3557 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3558 << OldParamOT;
3559 }
3560 }
3561}
3562
3563namespace {
3564
3565/// Used in MergeFunctionDecl to keep track of function parameters in
3566/// C.
3567struct GNUCompatibleParamWarning {
3568 ParmVarDecl *OldParm;
3569 ParmVarDecl *NewParm;
3570 QualType PromotedType;
3571};
3572
3573} // end anonymous namespace
3574
3575// Determine whether the previous declaration was a definition, implicit
3576// declaration, or a declaration.
3577template <typename T>
3578static std::pair<diag::kind, SourceLocation>
3580 diag::kind PrevDiag;
3581 SourceLocation OldLocation = Old->getLocation();
3582 if (Old->isThisDeclarationADefinition())
3583 PrevDiag = diag::note_previous_definition;
3584 else if (Old->isImplicit()) {
3585 PrevDiag = diag::note_previous_implicit_declaration;
3586 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3587 if (FD->getBuiltinID())
3588 PrevDiag = diag::note_previous_builtin_declaration;
3589 }
3590 if (OldLocation.isInvalid())
3591 OldLocation = New->getLocation();
3592 } else
3593 PrevDiag = diag::note_previous_declaration;
3594 return std::make_pair(PrevDiag, OldLocation);
3595}
3596
3597/// canRedefineFunction - checks if a function can be redefined. Currently,
3598/// only extern inline functions can be redefined, and even then only in
3599/// GNU89 mode.
3600static bool canRedefineFunction(const FunctionDecl *FD,
3601 const LangOptions& LangOpts) {
3602 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3603 !LangOpts.CPlusPlus &&
3604 FD->isInlineSpecified() &&
3605 FD->getStorageClass() == SC_Extern);
3606}
3607
3608const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3609 const AttributedType *AT = T->getAs<AttributedType>();
3610 while (AT && !AT->isCallingConv())
3611 AT = AT->getModifiedType()->getAs<AttributedType>();
3612 return AT;
3613}
3614
3615template <typename T>
3616static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3617 const DeclContext *DC = Old->getDeclContext();
3618 if (DC->isRecord())
3619 return false;
3620
3621 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3622 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3623 return true;
3624 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3625 return true;
3626 return false;
3627}
3628
3629template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3630static bool isExternC(VarTemplateDecl *) { return false; }
3631static bool isExternC(FunctionTemplateDecl *) { return false; }
3632
3633/// Check whether a redeclaration of an entity introduced by a
3634/// using-declaration is valid, given that we know it's not an overload
3635/// (nor a hidden tag declaration).
3636template<typename ExpectedDecl>
3638 ExpectedDecl *New) {
3639 // C++11 [basic.scope.declarative]p4:
3640 // Given a set of declarations in a single declarative region, each of
3641 // which specifies the same unqualified name,
3642 // -- they shall all refer to the same entity, or all refer to functions
3643 // and function templates; or
3644 // -- exactly one declaration shall declare a class name or enumeration
3645 // name that is not a typedef name and the other declarations shall all
3646 // refer to the same variable or enumerator, or all refer to functions
3647 // and function templates; in this case the class name or enumeration
3648 // name is hidden (3.3.10).
3649
3650 // C++11 [namespace.udecl]p14:
3651 // If a function declaration in namespace scope or block scope has the
3652 // same name and the same parameter-type-list as a function introduced
3653 // by a using-declaration, and the declarations do not declare the same
3654 // function, the program is ill-formed.
3655
3656 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3657 if (Old &&
3658 !Old->getDeclContext()->getRedeclContext()->Equals(
3659 New->getDeclContext()->getRedeclContext()) &&
3660 !(isExternC(Old) && isExternC(New)))
3661 Old = nullptr;
3662
3663 if (!Old) {
3664 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3665 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3666 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3667 return true;
3668 }
3669 return false;
3670}
3671
3673 const FunctionDecl *B) {
3674 assert(A->getNumParams() == B->getNumParams());
3675
3676 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3677 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3678 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3679 if (AttrA == AttrB)
3680 return true;
3681 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3682 AttrA->isDynamic() == AttrB->isDynamic();
3683 };
3684
3685 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3686}
3687
3688/// If necessary, adjust the semantic declaration context for a qualified
3689/// declaration to name the correct inline namespace within the qualifier.
3691 DeclaratorDecl *OldD) {
3692 // The only case where we need to update the DeclContext is when
3693 // redeclaration lookup for a qualified name finds a declaration
3694 // in an inline namespace within the context named by the qualifier:
3695 //
3696 // inline namespace N { int f(); }
3697 // int ::f(); // Sema DC needs adjusting from :: to N::.
3698 //
3699 // For unqualified declarations, the semantic context *can* change
3700 // along the redeclaration chain (for local extern declarations,
3701 // extern "C" declarations, and friend declarations in particular).
3702 if (!NewD->getQualifier())
3703 return;
3704
3705 // NewD is probably already in the right context.
3706 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3707 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3708 if (NamedDC->Equals(SemaDC))
3709 return;
3710
3711 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3712 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3713 "unexpected context for redeclaration");
3714
3715 auto *LexDC = NewD->getLexicalDeclContext();
3716 auto FixSemaDC = [=](NamedDecl *D) {
3717 if (!D)
3718 return;
3719 D->setDeclContext(SemaDC);
3720 D->setLexicalDeclContext(LexDC);
3721 };
3722
3723 FixSemaDC(NewD);
3724 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3725 FixSemaDC(FD->getDescribedFunctionTemplate());
3726 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3727 FixSemaDC(VD->getDescribedVarTemplate());
3728}
3729
3731 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3732 // Verify the old decl was also a function.
3733 FunctionDecl *Old = OldD->getAsFunction();
3734 if (!Old) {
3735 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3736 // We don't need to check the using friend pattern from other module unit
3737 // since we should have diagnosed such cases in its unit already.
3738 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3739 Diag(New->getLocation(), diag::err_using_decl_friend);
3740 Diag(Shadow->getTargetDecl()->getLocation(),
3741 diag::note_using_decl_target);
3742 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3743 << 0;
3744 return true;
3745 }
3746
3747 // Check whether the two declarations might declare the same function or
3748 // function template.
3749 if (FunctionTemplateDecl *NewTemplate =
3750 New->getDescribedFunctionTemplate()) {
3752 NewTemplate))
3753 return true;
3754 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3755 ->getAsFunction();
3756 } else {
3757 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3758 return true;
3759 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3760 }
3761 } else {
3762 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3763 << New->getDeclName();
3764 notePreviousDefinition(OldD, New->getLocation());
3765 return true;
3766 }
3767 }
3768
3769 // If the old declaration was found in an inline namespace and the new
3770 // declaration was qualified, update the DeclContext to match.
3772
3773 // If the old declaration is invalid, just give up here.
3774 if (Old->isInvalidDecl())
3775 return true;
3776
3777 // Disallow redeclaration of some builtins.
3778 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3779 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3780 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3781 << Old << Old->getType();
3782 return true;
3783 }
3784
3785 diag::kind PrevDiag;
3786 SourceLocation OldLocation;
3787 std::tie(PrevDiag, OldLocation) =
3789
3790 // Don't complain about this if we're in GNU89 mode and the old function
3791 // is an extern inline function.
3792 // Don't complain about specializations. They are not supposed to have
3793 // storage classes.
3794 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3795 New->getStorageClass() == SC_Static &&
3796 Old->hasExternalFormalLinkage() &&
3797 !New->getTemplateSpecializationInfo() &&
3799 if (getLangOpts().MicrosoftExt) {
3800 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3801 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3802 } else {
3803 Diag(New->getLocation(), diag::err_static_non_static) << New;
3804 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3805 return true;
3806 }
3807 }
3808
3809 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3810 if (!Old->hasAttr<InternalLinkageAttr>()) {
3811 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3812 << ILA;
3813 Diag(Old->getLocation(), diag::note_previous_declaration);
3814 New->dropAttr<InternalLinkageAttr>();
3815 }
3816
3817 if (auto *EA = New->getAttr<ErrorAttr>()) {
3818 if (!Old->hasAttr<ErrorAttr>()) {
3819 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3820 Diag(Old->getLocation(), diag::note_previous_declaration);
3821 New->dropAttr<ErrorAttr>();
3822 }
3823 }
3824
3826 return true;
3827
3828 if (!getLangOpts().CPlusPlus) {
3829 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3830 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3831 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3832 << New << OldOvl;
3833
3834 // Try our best to find a decl that actually has the overloadable
3835 // attribute for the note. In most cases (e.g. programs with only one
3836 // broken declaration/definition), this won't matter.
3837 //
3838 // FIXME: We could do this if we juggled some extra state in
3839 // OverloadableAttr, rather than just removing it.
3840 const Decl *DiagOld = Old;
3841 if (OldOvl) {
3842 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3843 const auto *A = D->getAttr<OverloadableAttr>();
3844 return A && !A->isImplicit();
3845 });
3846 // If we've implicitly added *all* of the overloadable attrs to this
3847 // chain, emitting a "previous redecl" note is pointless.
3848 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3849 }
3850
3851 if (DiagOld)
3852 Diag(DiagOld->getLocation(),
3853 diag::note_attribute_overloadable_prev_overload)
3854 << OldOvl;
3855
3856 if (OldOvl)
3857 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3858 else
3859 New->dropAttr<OverloadableAttr>();
3860 }
3861 }
3862
3863 // It is not permitted to redeclare an SME function with different SME
3864 // attributes.
3865 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3866 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3867 << New->getType() << Old->getType();
3868 Diag(OldLocation, diag::note_previous_declaration);
3869 return true;
3870 }
3871
3872 // If a function is first declared with a calling convention, but is later
3873 // declared or defined without one, all following decls assume the calling
3874 // convention of the first.
3875 //
3876 // It's OK if a function is first declared without a calling convention,
3877 // but is later declared or defined with the default calling convention.
3878 //
3879 // To test if either decl has an explicit calling convention, we look for
3880 // AttributedType sugar nodes on the type as written. If they are missing or
3881 // were canonicalized away, we assume the calling convention was implicit.
3882 //
3883 // Note also that we DO NOT return at this point, because we still have
3884 // other tests to run.
3885 QualType OldQType = Context.getCanonicalType(Old->getType());
3886 QualType NewQType = Context.getCanonicalType(New->getType());
3887 const FunctionType *OldType = cast<FunctionType>(OldQType);
3888 const FunctionType *NewType = cast<FunctionType>(NewQType);
3889 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3890 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3891 bool RequiresAdjustment = false;
3892
3893 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3895 const FunctionType *FT =
3896 First->getType().getCanonicalType()->castAs<FunctionType>();
3898 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3899 if (!NewCCExplicit) {
3900 // Inherit the CC from the previous declaration if it was specified
3901 // there but not here.
3902 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3903 RequiresAdjustment = true;
3904 } else if (Old->getBuiltinID()) {
3905 // Builtin attribute isn't propagated to the new one yet at this point,
3906 // so we check if the old one is a builtin.
3907
3908 // Calling Conventions on a Builtin aren't really useful and setting a
3909 // default calling convention and cdecl'ing some builtin redeclarations is
3910 // common, so warn and ignore the calling convention on the redeclaration.
3911 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3912 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3914 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3915 RequiresAdjustment = true;
3916 } else {
3917 // Calling conventions aren't compatible, so complain.
3918 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3919 Diag(New->getLocation(), diag::err_cconv_change)
3920 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3921 << !FirstCCExplicit
3922 << (!FirstCCExplicit ? "" :
3924
3925 // Put the note on the first decl, since it is the one that matters.
3926 Diag(First->getLocation(), diag::note_previous_declaration);
3927 return true;
3928 }
3929 }
3930
3931 // FIXME: diagnose the other way around?
3932 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3933 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3934 RequiresAdjustment = true;
3935 }
3936
3937 // If the declaration is marked with cfi_unchecked_callee but the definition
3938 // isn't, the definition is also cfi_unchecked_callee.
3939 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3940 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3941 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3942 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3943
3944 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3945 EPI2.CFIUncheckedCallee = true;
3946 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3947 FPT2->getParamTypes(), EPI2);
3948 NewType = cast<FunctionType>(NewQType);
3949 New->setType(NewQType);
3950 }
3951 }
3952 }
3953
3954 // Merge regparm attribute.
3955 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3956 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3957 if (NewTypeInfo.getHasRegParm()) {
3958 Diag(New->getLocation(), diag::err_regparm_mismatch)
3959 << NewType->getRegParmType()
3960 << OldType->getRegParmType();
3961 Diag(OldLocation, diag::note_previous_declaration);
3962 return true;
3963 }
3964
3965 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3966 RequiresAdjustment = true;
3967 }
3968
3969 // Merge ns_returns_retained attribute.
3970 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3971 if (NewTypeInfo.getProducesResult()) {
3972 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3973 << "'ns_returns_retained'";
3974 Diag(OldLocation, diag::note_previous_declaration);
3975 return true;
3976 }
3977
3978 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3979 RequiresAdjustment = true;
3980 }
3981
3982 if (OldTypeInfo.getNoCallerSavedRegs() !=
3983 NewTypeInfo.getNoCallerSavedRegs()) {
3984 if (NewTypeInfo.getNoCallerSavedRegs()) {
3985 AnyX86NoCallerSavedRegistersAttr *Attr =
3986 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3987 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3988 Diag(OldLocation, diag::note_previous_declaration);
3989 return true;
3990 }
3991
3992 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3993 RequiresAdjustment = true;
3994 }
3995
3996 if (RequiresAdjustment) {
3997 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3998 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3999 New->setType(QualType(AdjustedType, 0));
4000 NewQType = Context.getCanonicalType(New->getType());
4001 }
4002
4003 // If this redeclaration makes the function inline, we may need to add it to
4004 // UndefinedButUsed.
4005 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4006 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
4007 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4008 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4009 SourceLocation()));
4010
4011 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4012 // about it.
4013 if (New->hasAttr<GNUInlineAttr>() &&
4014 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4015 UndefinedButUsed.erase(Old->getCanonicalDecl());
4016 }
4017
4018 // If pass_object_size params don't match up perfectly, this isn't a valid
4019 // redeclaration.
4020 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4022 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
4023 << New->getDeclName();
4024 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4025 return true;
4026 }
4027
4028 QualType OldQTypeForComparison = OldQType;
4029 if (Context.hasAnyFunctionEffects()) {
4030 const auto OldFX = Old->getFunctionEffects();
4031 const auto NewFX = New->getFunctionEffects();
4032 if (OldFX != NewFX) {
4033 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4034 for (const auto &Diff : Diffs) {
4035 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
4036 Diag(New->getLocation(),
4037 diag::warn_mismatched_func_effect_redeclaration)
4038 << Diff.effectName();
4039 Diag(Old->getLocation(), diag::note_previous_declaration);
4040 }
4041 }
4042 // Following a warning, we could skip merging effects from the previous
4043 // declaration, but that would trigger an additional "conflicting types"
4044 // error.
4045 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4047 FunctionEffectSet MergedFX =
4048 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4049 if (!MergeErrs.empty())
4050 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4051 Old->getLocation());
4052
4053 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4054 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4055 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4056 NewFPT->getParamTypes(), EPI);
4057
4058 New->setType(ModQT);
4059 NewQType = New->getType();
4060
4061 // Revise OldQTForComparison to include the merged effects,
4062 // so as not to fail due to differences later.
4063 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4064 EPI = OldFPT->getExtProtoInfo();
4065 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4066 OldQTypeForComparison = Context.getFunctionType(
4067 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4068 }
4069 if (OldFX.empty()) {
4070 // A redeclaration may add the attribute to a previously seen function
4071 // body which needs to be verified.
4072 maybeAddDeclWithEffects(Old, MergedFX);
4073 }
4074 }
4075 }
4076 }
4077
4078 if (getLangOpts().CPlusPlus) {
4079 OldQType = Context.getCanonicalType(Old->getType());
4080 NewQType = Context.getCanonicalType(New->getType());
4081
4082 // Go back to the type source info to compare the declared return types,
4083 // per C++1y [dcl.type.auto]p13:
4084 // Redeclarations or specializations of a function or function template
4085 // with a declared return type that uses a placeholder type shall also
4086 // use that placeholder, not a deduced type.
4087 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4088 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4089 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4090 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4091 OldDeclaredReturnType)) {
4092 QualType ResQT;
4093 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4094 OldDeclaredReturnType->isObjCObjectPointerType())
4095 // FIXME: This does the wrong thing for a deduced return type.
4096 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4097 if (ResQT.isNull()) {
4098 if (New->isCXXClassMember() && New->isOutOfLine())
4099 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4100 << New << New->getReturnTypeSourceRange();
4101 else if (Old->isExternC() && New->isExternC() &&
4102 !Old->hasAttr<OverloadableAttr>() &&
4103 !New->hasAttr<OverloadableAttr>())
4104 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4105 else
4106 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4107 << New->getReturnTypeSourceRange();
4108 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4109 << Old->getReturnTypeSourceRange();
4110 return true;
4111 }
4112 else
4113 NewQType = ResQT;
4114 }
4115
4116 QualType OldReturnType = OldType->getReturnType();
4117 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4118 if (OldReturnType != NewReturnType) {
4119 // If this function has a deduced return type and has already been
4120 // defined, copy the deduced value from the old declaration.
4121 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4122 if (OldAT && OldAT->isDeduced()) {
4123 QualType DT = OldAT->getDeducedType();
4124 if (DT.isNull()) {
4125 New->setType(SubstAutoTypeDependent(New->getType()));
4126 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4127 } else {
4128 New->setType(SubstAutoType(New->getType(), DT));
4129 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4130 }
4131 }
4132 }
4133
4134 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4135 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4136 if (OldMethod && NewMethod) {
4137 // Preserve triviality.
4138 NewMethod->setTrivial(OldMethod->isTrivial());
4139
4140 // MSVC allows explicit template specialization at class scope:
4141 // 2 CXXMethodDecls referring to the same function will be injected.
4142 // We don't want a redeclaration error.
4143 bool IsClassScopeExplicitSpecialization =
4144 OldMethod->isFunctionTemplateSpecialization() &&
4146 bool isFriend = NewMethod->getFriendObjectKind();
4147
4148 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4149 !IsClassScopeExplicitSpecialization) {
4150 // -- Member function declarations with the same name and the
4151 // same parameter types cannot be overloaded if any of them
4152 // is a static member function declaration.
4153 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4154 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4155 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4156 return true;
4157 }
4158
4159 // C++ [class.mem]p1:
4160 // [...] A member shall not be declared twice in the
4161 // member-specification, except that a nested class or member
4162 // class template can be declared and then later defined.
4163 if (!inTemplateInstantiation()) {
4164 unsigned NewDiag;
4165 if (isa<CXXConstructorDecl>(OldMethod))
4166 NewDiag = diag::err_constructor_redeclared;
4167 else if (isa<CXXDestructorDecl>(NewMethod))
4168 NewDiag = diag::err_destructor_redeclared;
4169 else if (isa<CXXConversionDecl>(NewMethod))
4170 NewDiag = diag::err_conv_function_redeclared;
4171 else
4172 NewDiag = diag::err_member_redeclared;
4173
4174 Diag(New->getLocation(), NewDiag);
4175 } else {
4176 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4177 << New << New->getType();
4178 }
4179 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4180 return true;
4181
4182 // Complain if this is an explicit declaration of a special
4183 // member that was initially declared implicitly.
4184 //
4185 // As an exception, it's okay to befriend such methods in order
4186 // to permit the implicit constructor/destructor/operator calls.
4187 } else if (OldMethod->isImplicit()) {
4188 if (isFriend) {
4189 NewMethod->setImplicit();
4190 } else {
4191 Diag(NewMethod->getLocation(),
4192 diag::err_definition_of_implicitly_declared_member)
4193 << New << getSpecialMember(OldMethod);
4194 return true;
4195 }
4196 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4197 Diag(NewMethod->getLocation(),
4198 diag::err_definition_of_explicitly_defaulted_member)
4199 << getSpecialMember(OldMethod);
4200 return true;
4201 }
4202 }
4203
4204 // C++1z [over.load]p2
4205 // Certain function declarations cannot be overloaded:
4206 // -- Function declarations that differ only in the return type,
4207 // the exception specification, or both cannot be overloaded.
4208
4209 // Check the exception specifications match. This may recompute the type of
4210 // both Old and New if it resolved exception specifications, so grab the
4211 // types again after this. Because this updates the type, we do this before
4212 // any of the other checks below, which may update the "de facto" NewQType
4213 // but do not necessarily update the type of New.
4215 return true;
4216
4217 // C++11 [dcl.attr.noreturn]p1:
4218 // The first declaration of a function shall specify the noreturn
4219 // attribute if any declaration of that function specifies the noreturn
4220 // attribute.
4221 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4222 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4223 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4224 << NRA;
4225 Diag(Old->getLocation(), diag::note_previous_declaration);
4226 }
4227
4228 // C++11 [dcl.attr.depend]p2:
4229 // The first declaration of a function shall specify the
4230 // carries_dependency attribute for its declarator-id if any declaration
4231 // of the function specifies the carries_dependency attribute.
4232 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4233 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4234 Diag(CDA->getLocation(),
4235 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4236 Diag(Old->getFirstDecl()->getLocation(),
4237 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4238 }
4239
4240 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4241 // When a function is declared with SYCL_EXTERNAL, that macro must be
4242 // used on the first declaration of that function in the translation unit.
4243 // Redeclarations of the function in the same translation unit may
4244 // optionally use SYCL_EXTERNAL, but this is not required.
4245 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4246 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4247 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4248 << SEA;
4249 Diag(Old->getLocation(), diag::note_previous_declaration);
4250 }
4251
4252 // (C++98 8.3.5p3):
4253 // All declarations for a function shall agree exactly in both the
4254 // return type and the parameter-type-list.
4255 // We also want to respect all the extended bits except noreturn.
4256
4257 // noreturn should now match unless the old type info didn't have it.
4258 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4259 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4260 const FunctionType *OldTypeForComparison
4261 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4262 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4263 assert(OldQTypeForComparison.isCanonical());
4264 }
4265
4267 // As a special case, retain the language linkage from previous
4268 // declarations of a friend function as an extension.
4269 //
4270 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4271 // and is useful because there's otherwise no way to specify language
4272 // linkage within class scope.
4273 //
4274 // Check cautiously as the friend object kind isn't yet complete.
4275 if (New->getFriendObjectKind() != Decl::FOK_None) {
4276 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4277 Diag(OldLocation, PrevDiag);
4278 } else {
4279 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4280 Diag(OldLocation, PrevDiag);
4281 return true;
4282 }
4283 }
4284
4285 // HLSL check parameters for matching ABI specifications.
4286 if (getLangOpts().HLSL) {
4287 if (HLSL().CheckCompatibleParameterABI(New, Old))
4288 return true;
4289
4290 // If no errors are generated when checking parameter ABIs we can check if
4291 // the two declarations have the same type ignoring the ABIs and if so,
4292 // the declarations can be merged. This case for merging is only valid in
4293 // HLSL because there are no valid cases of merging mismatched parameter
4294 // ABIs except the HLSL implicit in and explicit in.
4295 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4296 NewQType))
4297 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4298 // Fall through for conflicting redeclarations and redefinitions.
4299 }
4300
4301 // If the function types are compatible, merge the declarations. Ignore the
4302 // exception specifier because it was already checked above in
4303 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4304 // about incompatible types under -fms-compatibility.
4305 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4306 NewQType))
4307 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4308
4309 // If the types are imprecise (due to dependent constructs in friends or
4310 // local extern declarations), it's OK if they differ. We'll check again
4311 // during instantiation.
4312 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4313 return false;
4314
4315 // Fall through for conflicting redeclarations and redefinitions.
4316 }
4317
4318 // C: Function types need to be compatible, not identical. This handles
4319 // duplicate function decls like "void f(int); void f(enum X);" properly.
4320 if (!getLangOpts().CPlusPlus) {
4321 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4322 // type is specified by a function definition that contains a (possibly
4323 // empty) identifier list, both shall agree in the number of parameters
4324 // and the type of each parameter shall be compatible with the type that
4325 // results from the application of default argument promotions to the
4326 // type of the corresponding identifier. ...
4327 // This cannot be handled by ASTContext::typesAreCompatible() because that
4328 // doesn't know whether the function type is for a definition or not when
4329 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4330 // we need to cover here is that the number of arguments agree as the
4331 // default argument promotion rules were already checked by
4332 // ASTContext::typesAreCompatible().
4333 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4334 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4335 if (Old->hasInheritedPrototype())
4336 Old = Old->getCanonicalDecl();
4337 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4338 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4339 return true;
4340 }
4341
4342 // If we are merging two functions where only one of them has a prototype,
4343 // we may have enough information to decide to issue a diagnostic that the
4344 // function without a prototype will change behavior in C23. This handles
4345 // cases like:
4346 // void i(); void i(int j);
4347 // void i(int j); void i();
4348 // void i(); void i(int j) {}
4349 // See ActOnFinishFunctionBody() for other cases of the behavior change
4350 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4351 // type without a prototype.
4352 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4353 !New->isImplicit() && !Old->isImplicit()) {
4354 const FunctionDecl *WithProto, *WithoutProto;
4355 if (New->hasWrittenPrototype()) {
4356 WithProto = New;
4357 WithoutProto = Old;
4358 } else {
4359 WithProto = Old;
4360 WithoutProto = New;
4361 }
4362
4363 if (WithProto->getNumParams() != 0) {
4364 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4365 // The one without the prototype will be changing behavior in C23, so
4366 // warn about that one so long as it's a user-visible declaration.
4367 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4368 if (WithoutProto == New)
4369 IsWithoutProtoADef = NewDeclIsDefn;
4370 else
4371 IsWithProtoADef = NewDeclIsDefn;
4372 Diag(WithoutProto->getLocation(),
4373 diag::warn_non_prototype_changes_behavior)
4374 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4375 << (WithoutProto == Old) << IsWithProtoADef;
4376
4377 // The reason the one without the prototype will be changing behavior
4378 // is because of the one with the prototype, so note that so long as
4379 // it's a user-visible declaration. There is one exception to this:
4380 // when the new declaration is a definition without a prototype, the
4381 // old declaration with a prototype is not the cause of the issue,
4382 // and that does not need to be noted because the one with a
4383 // prototype will not change behavior in C23.
4384 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4385 !IsWithoutProtoADef)
4386 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4387 }
4388 }
4389 }
4390
4391 if (Context.typesAreCompatible(OldQType, NewQType)) {
4392 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4393 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4394 const FunctionProtoType *OldProto = nullptr;
4395 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4396 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4397 // The old declaration provided a function prototype, but the
4398 // new declaration does not. Merge in the prototype.
4399 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4400 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4401 OldProto->getParamTypes(),
4402 OldProto->getExtProtoInfo());
4403 New->setType(NewQType);
4404 New->setHasInheritedPrototype();
4405
4406 // Synthesize parameters with the same types.
4408 for (const auto &ParamType : OldProto->param_types()) {
4410 Context, New, SourceLocation(), SourceLocation(), nullptr,
4411 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4412 Param->setScopeInfo(0, Params.size());
4413 Param->setImplicit();
4414 Params.push_back(Param);
4415 }
4416
4417 New->setParams(Params);
4418 }
4419
4420 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4421 }
4422 }
4423
4424 // Check if the function types are compatible when pointer size address
4425 // spaces are ignored.
4426 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4427 return false;
4428
4429 // GNU C permits a K&R definition to follow a prototype declaration
4430 // if the declared types of the parameters in the K&R definition
4431 // match the types in the prototype declaration, even when the
4432 // promoted types of the parameters from the K&R definition differ
4433 // from the types in the prototype. GCC then keeps the types from
4434 // the prototype.
4435 //
4436 // If a variadic prototype is followed by a non-variadic K&R definition,
4437 // the K&R definition becomes variadic. This is sort of an edge case, but
4438 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4439 // C99 6.9.1p8.
4440 if (!getLangOpts().CPlusPlus &&
4441 Old->hasPrototype() && !New->hasPrototype() &&
4442 New->getType()->getAs<FunctionProtoType>() &&
4443 Old->getNumParams() == New->getNumParams()) {
4446 const FunctionProtoType *OldProto
4447 = Old->getType()->getAs<FunctionProtoType>();
4448 const FunctionProtoType *NewProto
4449 = New->getType()->getAs<FunctionProtoType>();
4450
4451 // Determine whether this is the GNU C extension.
4452 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4453 NewProto->getReturnType());
4454 bool LooseCompatible = !MergedReturn.isNull();
4455 for (unsigned Idx = 0, End = Old->getNumParams();
4456 LooseCompatible && Idx != End; ++Idx) {
4457 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4458 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4459 if (Context.typesAreCompatible(OldParm->getType(),
4460 NewProto->getParamType(Idx))) {
4461 ArgTypes.push_back(NewParm->getType());
4462 } else if (Context.typesAreCompatible(OldParm->getType(),
4463 NewParm->getType(),
4464 /*CompareUnqualified=*/true)) {
4465 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4466 NewProto->getParamType(Idx) };
4467 Warnings.push_back(Warn);
4468 ArgTypes.push_back(NewParm->getType());
4469 } else
4470 LooseCompatible = false;
4471 }
4472
4473 if (LooseCompatible) {
4474 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4475 Diag(Warnings[Warn].NewParm->getLocation(),
4476 diag::ext_param_promoted_not_compatible_with_prototype)
4477 << Warnings[Warn].PromotedType
4478 << Warnings[Warn].OldParm->getType();
4479 if (Warnings[Warn].OldParm->getLocation().isValid())
4480 Diag(Warnings[Warn].OldParm->getLocation(),
4481 diag::note_previous_declaration);
4482 }
4483
4484 if (MergeTypeWithOld)
4485 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4486 OldProto->getExtProtoInfo()));
4487 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4488 }
4489
4490 // Fall through to diagnose conflicting types.
4491 }
4492
4493 // A function that has already been declared has been redeclared or
4494 // defined with a different type; show an appropriate diagnostic.
4495
4496 // If the previous declaration was an implicitly-generated builtin
4497 // declaration, then at the very least we should use a specialized note.
4498 unsigned BuiltinID;
4499 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4500 // If it's actually a library-defined builtin function like 'malloc'
4501 // or 'printf', just warn about the incompatible redeclaration.
4502 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4503 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4504 Diag(OldLocation, diag::note_previous_builtin_declaration)
4505 << Old << Old->getType();
4506 return false;
4507 }
4508
4509 PrevDiag = diag::note_previous_builtin_declaration;
4510 }
4511
4512 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4513 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4514 return true;
4515}
4516
4518 Scope *S, bool MergeTypeWithOld) {
4519 // Merge the attributes
4521
4522 // Merge "pure" flag.
4523 if (Old->isPureVirtual())
4524 New->setIsPureVirtual();
4525
4526 // Merge "used" flag.
4527 if (Old->getMostRecentDecl()->isUsed(false))
4528 New->setIsUsed();
4529
4530 // Merge attributes from the parameters. These can mismatch with K&R
4531 // declarations.
4532 if (New->getNumParams() == Old->getNumParams())
4533 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4534 ParmVarDecl *NewParam = New->getParamDecl(i);
4535 ParmVarDecl *OldParam = Old->getParamDecl(i);
4536 mergeParamDeclAttributes(NewParam, OldParam, *this);
4537 mergeParamDeclTypes(NewParam, OldParam, *this);
4538 }
4539
4540 if (getLangOpts().CPlusPlus)
4541 return MergeCXXFunctionDecl(New, Old, S);
4542
4543 // Merge the function types so the we get the composite types for the return
4544 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4545 // was visible.
4546 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4547 if (!Merged.isNull() && MergeTypeWithOld)
4548 New->setType(Merged);
4549
4550 return false;
4551}
4552
4554 ObjCMethodDecl *oldMethod) {
4555 // Merge the attributes, including deprecated/unavailable
4556 AvailabilityMergeKind MergeKind =
4558 ? (oldMethod->isOptional()
4561 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4564
4565 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4566
4567 // Merge attributes from the parameters.
4569 oe = oldMethod->param_end();
4571 ni = newMethod->param_begin(), ne = newMethod->param_end();
4572 ni != ne && oi != oe; ++ni, ++oi)
4573 mergeParamDeclAttributes(*ni, *oi, *this);
4574
4575 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4576}
4577
4579 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4580
4581 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4582 ? diag::err_redefinition_different_type
4583 : diag::err_redeclaration_different_type)
4584 << New->getDeclName() << New->getType() << Old->getType();
4585
4586 diag::kind PrevDiag;
4587 SourceLocation OldLocation;
4588 std::tie(PrevDiag, OldLocation)
4590 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4591 New->setInvalidDecl();
4592}
4593
4595 bool MergeTypeWithOld) {
4596 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4597 return;
4598
4599 QualType MergedT;
4600 if (getLangOpts().CPlusPlus) {
4601 if (New->getType()->isUndeducedType()) {
4602 // We don't know what the new type is until the initializer is attached.
4603 return;
4604 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4605 // These could still be something that needs exception specs checked.
4606 return MergeVarDeclExceptionSpecs(New, Old);
4607 }
4608 // C++ [basic.link]p10:
4609 // [...] the types specified by all declarations referring to a given
4610 // object or function shall be identical, except that declarations for an
4611 // array object can specify array types that differ by the presence or
4612 // absence of a major array bound (8.3.4).
4613 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4614 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4615 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4616
4617 // We are merging a variable declaration New into Old. If it has an array
4618 // bound, and that bound differs from Old's bound, we should diagnose the
4619 // mismatch.
4620 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4621 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4622 PrevVD = PrevVD->getPreviousDecl()) {
4623 QualType PrevVDTy = PrevVD->getType();
4624 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4625 continue;
4626
4627 if (!Context.hasSameType(New->getType(), PrevVDTy))
4628 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4629 }
4630 }
4631
4632 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4633 if (Context.hasSameType(OldArray->getElementType(),
4634 NewArray->getElementType()))
4635 MergedT = New->getType();
4636 }
4637 // FIXME: Check visibility. New is hidden but has a complete type. If New
4638 // has no array bound, it should not inherit one from Old, if Old is not
4639 // visible.
4640 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4641 if (Context.hasSameType(OldArray->getElementType(),
4642 NewArray->getElementType()))
4643 MergedT = Old->getType();
4644 }
4645 }
4646 else if (New->getType()->isObjCObjectPointerType() &&
4647 Old->getType()->isObjCObjectPointerType()) {
4648 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4649 Old->getType());
4650 }
4651 } else {
4652 // C 6.2.7p2:
4653 // All declarations that refer to the same object or function shall have
4654 // compatible type.
4655 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4656 }
4657 if (MergedT.isNull()) {
4658 // It's OK if we couldn't merge types if either type is dependent, for a
4659 // block-scope variable. In other cases (static data members of class
4660 // templates, variable templates, ...), we require the types to be
4661 // equivalent.
4662 // FIXME: The C++ standard doesn't say anything about this.
4663 if ((New->getType()->isDependentType() ||
4664 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4665 // If the old type was dependent, we can't merge with it, so the new type
4666 // becomes dependent for now. We'll reproduce the original type when we
4667 // instantiate the TypeSourceInfo for the variable.
4668 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4669 New->setType(Context.DependentTy);
4670 return;
4671 }
4672 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4673 }
4674
4675 // Don't actually update the type on the new declaration if the old
4676 // declaration was an extern declaration in a different scope.
4677 if (MergeTypeWithOld)
4678 New->setType(MergedT);
4679}
4680
4681static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4683 // C11 6.2.7p4:
4684 // For an identifier with internal or external linkage declared
4685 // in a scope in which a prior declaration of that identifier is
4686 // visible, if the prior declaration specifies internal or
4687 // external linkage, the type of the identifier at the later
4688 // declaration becomes the composite type.
4689 //
4690 // If the variable isn't visible, we do not merge with its type.
4691 if (Previous.isShadowed())
4692 return false;
4693
4694 if (S.getLangOpts().CPlusPlus) {
4695 // C++11 [dcl.array]p3:
4696 // If there is a preceding declaration of the entity in the same
4697 // scope in which the bound was specified, an omitted array bound
4698 // is taken to be the same as in that earlier declaration.
4699 return NewVD->isPreviousDeclInSameBlockScope() ||
4700 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4702 } else {
4703 // If the old declaration was function-local, don't merge with its
4704 // type unless we're in the same function.
4705 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4706 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4707 }
4708}
4709
4711 // If the new decl is already invalid, don't do any other checking.
4712 if (New->isInvalidDecl())
4713 return;
4714
4715 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4716 return;
4717
4718 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4719
4720 // Verify the old decl was also a variable or variable template.
4721 VarDecl *Old = nullptr;
4722 VarTemplateDecl *OldTemplate = nullptr;
4723 if (Previous.isSingleResult()) {
4724 if (NewTemplate) {
4725 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4726 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4727
4728 if (auto *Shadow =
4729 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4730 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4731 return New->setInvalidDecl();
4732 } else {
4733 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4734
4735 if (auto *Shadow =
4736 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4737 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4738 return New->setInvalidDecl();
4739 }
4740 }
4741 if (!Old) {
4742 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4743 << New->getDeclName();
4744 notePreviousDefinition(Previous.getRepresentativeDecl(),
4745 New->getLocation());
4746 return New->setInvalidDecl();
4747 }
4748
4749 // If the old declaration was found in an inline namespace and the new
4750 // declaration was qualified, update the DeclContext to match.
4752
4753 // Ensure the template parameters are compatible.
4754 if (NewTemplate &&
4756 OldTemplate->getTemplateParameters(),
4757 /*Complain=*/true, TPL_TemplateMatch))
4758 return New->setInvalidDecl();
4759
4760 // C++ [class.mem]p1:
4761 // A member shall not be declared twice in the member-specification [...]
4762 //
4763 // Here, we need only consider static data members.
4764 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4765 Diag(New->getLocation(), diag::err_duplicate_member)
4766 << New->getIdentifier();
4767 Diag(Old->getLocation(), diag::note_previous_declaration);
4768 New->setInvalidDecl();
4769 }
4770
4772 // Warn if an already-defined variable is made a weak_import in a subsequent
4773 // declaration
4774 if (New->hasAttr<WeakImportAttr>())
4775 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4776 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4777 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4778 Diag(D->getLocation(), diag::note_previous_definition);
4779 // Remove weak_import attribute on new declaration.
4780 New->dropAttr<WeakImportAttr>();
4781 break;
4782 }
4783 }
4784
4785 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4786 if (!Old->hasAttr<InternalLinkageAttr>()) {
4787 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4788 << ILA;
4789 Diag(Old->getLocation(), diag::note_previous_declaration);
4790 New->dropAttr<InternalLinkageAttr>();
4791 }
4792
4793 // Merge the types.
4794 VarDecl *MostRecent = Old->getMostRecentDecl();
4795 if (MostRecent != Old) {
4796 MergeVarDeclTypes(New, MostRecent,
4797 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4798 if (New->isInvalidDecl())
4799 return;
4800 }
4801
4803 if (New->isInvalidDecl())
4804 return;
4805
4806 diag::kind PrevDiag;
4807 SourceLocation OldLocation;
4808 std::tie(PrevDiag, OldLocation) =
4810
4811 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4812 if (New->getStorageClass() == SC_Static &&
4813 !New->isStaticDataMember() &&
4814 Old->hasExternalFormalLinkage()) {
4815 if (getLangOpts().MicrosoftExt) {
4816 Diag(New->getLocation(), diag::ext_static_non_static)
4817 << New->getDeclName();
4818 Diag(OldLocation, PrevDiag);
4819 } else {
4820 Diag(New->getLocation(), diag::err_static_non_static)
4821 << New->getDeclName();
4822 Diag(OldLocation, PrevDiag);
4823 return New->setInvalidDecl();
4824 }
4825 }
4826 // C99 6.2.2p4:
4827 // For an identifier declared with the storage-class specifier
4828 // extern in a scope in which a prior declaration of that
4829 // identifier is visible,23) if the prior declaration specifies
4830 // internal or external linkage, the linkage of the identifier at
4831 // the later declaration is the same as the linkage specified at
4832 // the prior declaration. If no prior declaration is visible, or
4833 // if the prior declaration specifies no linkage, then the
4834 // identifier has external linkage.
4835 if (New->hasExternalStorage() && Old->hasLinkage())
4836 /* Okay */;
4837 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4838 !New->isStaticDataMember() &&
4840 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4841 Diag(OldLocation, PrevDiag);
4842 return New->setInvalidDecl();
4843 }
4844
4845 // Check if extern is followed by non-extern and vice-versa.
4846 if (New->hasExternalStorage() &&
4847 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4848 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4849 Diag(OldLocation, PrevDiag);
4850 return New->setInvalidDecl();
4851 }
4852 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4853 !New->hasExternalStorage()) {
4854 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4855 Diag(OldLocation, PrevDiag);
4856 return New->setInvalidDecl();
4857 }
4858
4860 return;
4861
4862 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4863
4864 // FIXME: The test for external storage here seems wrong? We still
4865 // need to check for mismatches.
4866 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4867 // Don't complain about out-of-line definitions of static members.
4868 !(Old->getLexicalDeclContext()->isRecord() &&
4869 !New->getLexicalDeclContext()->isRecord())) {
4870 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4871 Diag(OldLocation, PrevDiag);
4872 return New->setInvalidDecl();
4873 }
4874
4875 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4876 if (VarDecl *Def = Old->getDefinition()) {
4877 // C++1z [dcl.fcn.spec]p4:
4878 // If the definition of a variable appears in a translation unit before
4879 // its first declaration as inline, the program is ill-formed.
4880 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4881 Diag(Def->getLocation(), diag::note_previous_definition);
4882 }
4883 }
4884
4885 // If this redeclaration makes the variable inline, we may need to add it to
4886 // UndefinedButUsed.
4887 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4888 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4889 !Old->isInAnotherModuleUnit())
4890 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4891 SourceLocation()));
4892
4893 if (New->getTLSKind() != Old->getTLSKind()) {
4894 if (!Old->getTLSKind()) {
4895 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4896 Diag(OldLocation, PrevDiag);
4897 } else if (!New->getTLSKind()) {
4898 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4899 Diag(OldLocation, PrevDiag);
4900 } else {
4901 // Do not allow redeclaration to change the variable between requiring
4902 // static and dynamic initialization.
4903 // FIXME: GCC allows this, but uses the TLS keyword on the first
4904 // declaration to determine the kind. Do we need to be compatible here?
4905 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4906 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4907 Diag(OldLocation, PrevDiag);
4908 }
4909 }
4910
4911 // C++ doesn't have tentative definitions, so go right ahead and check here.
4912 if (getLangOpts().CPlusPlus) {
4913 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4914 Old->getCanonicalDecl()->isConstexpr()) {
4915 // This definition won't be a definition any more once it's been merged.
4916 Diag(New->getLocation(),
4917 diag::warn_deprecated_redundant_constexpr_static_def);
4918 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4919 VarDecl *Def = Old->getDefinition();
4920 if (Def && checkVarDeclRedefinition(Def, New))
4921 return;
4922 if (Old->isInvalidDecl())
4923 New->setInvalidDecl();
4924 }
4925 } else {
4926 // C++ may not have a tentative definition rule, but it has a different
4927 // rule about what constitutes a definition in the first place. See
4928 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4929 // contains the extern specifier and doesn't have an initializer, it's fine
4930 // in C++.
4931 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4932 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4933 << New;
4934 Diag(Old->getLocation(), diag::note_previous_declaration);
4935 }
4936 }
4937
4939 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4940 Diag(OldLocation, PrevDiag);
4941 New->setInvalidDecl();
4942 return;
4943 }
4944
4945 // Merge "used" flag.
4946 if (Old->getMostRecentDecl()->isUsed(false))
4947 New->setIsUsed();
4948
4949 // Keep a chain of previous declarations.
4950 New->setPreviousDecl(Old);
4951 if (NewTemplate)
4952 NewTemplate->setPreviousDecl(OldTemplate);
4953
4954 // Inherit access appropriately.
4955 New->setAccess(Old->getAccess());
4956 if (NewTemplate)
4957 NewTemplate->setAccess(New->getAccess());
4958
4959 if (Old->isInline())
4960 New->setImplicitlyInline();
4961}
4962
4965 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4966 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4967 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4968 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4969 auto &HSI = PP.getHeaderSearchInfo();
4970 StringRef HdrFilename =
4971 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4972
4973 auto noteFromModuleOrInclude = [&](Module *Mod,
4974 SourceLocation IncLoc) -> bool {
4975 // Redefinition errors with modules are common with non modular mapped
4976 // headers, example: a non-modular header H in module A that also gets
4977 // included directly in a TU. Pointing twice to the same header/definition
4978 // is confusing, try to get better diagnostics when modules is on.
4979 if (IncLoc.isValid()) {
4980 if (Mod) {
4981 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4982 << HdrFilename.str() << Mod->getFullModuleName();
4983 if (!Mod->DefinitionLoc.isInvalid())
4984 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4985 << Mod->getFullModuleName();
4986 } else {
4987 Diag(IncLoc, diag::note_redefinition_include_same_file)
4988 << HdrFilename.str();
4989 }
4990 return true;
4991 }
4992
4993 return false;
4994 };
4995
4996 // Is it the same file and same offset? Provide more information on why
4997 // this leads to a redefinition error.
4998 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4999 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
5000 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
5001 bool EmittedDiag =
5002 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5003 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5004
5005 // If the header has no guards, emit a note suggesting one.
5006 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
5007 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
5008
5009 if (EmittedDiag)
5010 return;
5011 }
5012
5013 // Redefinition coming from different files or couldn't do better above.
5014 if (Old->getLocation().isValid())
5015 Diag(Old->getLocation(), diag::note_previous_definition);
5016}
5017
5019 if (!hasVisibleDefinition(Old) &&
5020 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5022 New->getDescribedVarTemplate() ||
5023 !New->getTemplateParameterLists().empty() ||
5024 New->getDeclContext()->isDependentContext() ||
5025 New->hasAttr<SelectAnyAttr>())) {
5026 // The previous definition is hidden, and multiple definitions are
5027 // permitted (in separate TUs). Demote this to a declaration.
5028 New->demoteThisDefinitionToDeclaration();
5029
5030 // Make the canonical definition visible.
5031 if (auto *OldTD = Old->getDescribedVarTemplate())
5034 return false;
5035 } else {
5036 Diag(New->getLocation(), diag::err_redefinition) << New;
5037 notePreviousDefinition(Old, New->getLocation());
5038 New->setInvalidDecl();
5039 return true;
5040 }
5041}
5042
5044 DeclSpec &DS,
5045 const ParsedAttributesView &DeclAttrs,
5046 RecordDecl *&AnonRecord) {
5048 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5049}
5050
5051// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5052// disambiguate entities defined in different scopes.
5053// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5054// compatibility.
5055// We will pick our mangling number depending on which version of MSVC is being
5056// targeted.
5057static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5061}
5062
5063void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5064 if (!Context.getLangOpts().CPlusPlus)
5065 return;
5066
5067 if (isa<CXXRecordDecl>(Tag->getParent())) {
5068 // If this tag is the direct child of a class, number it if
5069 // it is anonymous.
5070 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5071 return;
5073 Context.getManglingNumberContext(Tag->getParent());
5074 Context.setManglingNumber(
5075 Tag, MCtx.getManglingNumber(
5076 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5077 return;
5078 }
5079
5080 // If this tag isn't a direct child of a class, number it if it is local.
5082 Decl *ManglingContextDecl;
5083 std::tie(MCtx, ManglingContextDecl) =
5084 getCurrentMangleNumberContext(Tag->getDeclContext());
5085 if (MCtx) {
5086 Context.setManglingNumber(
5087 Tag, MCtx->getManglingNumber(
5088 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5089 }
5090}
5091
5092namespace {
5093struct NonCLikeKind {
5094 enum {
5095 None,
5096 BaseClass,
5097 DefaultMemberInit,
5098 Lambda,
5099 Friend,
5100 OtherMember,
5101 Invalid,
5102 } Kind = None;
5103 SourceRange Range;
5104
5105 explicit operator bool() { return Kind != None; }
5106};
5107}
5108
5109/// Determine whether a class is C-like, according to the rules of C++
5110/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5111static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5112 if (RD->isInvalidDecl())
5113 return {NonCLikeKind::Invalid, {}};
5114
5115 // C++ [dcl.typedef]p9: [P1766R1]
5116 // An unnamed class with a typedef name for linkage purposes shall not
5117 //
5118 // -- have any base classes
5119 if (RD->getNumBases())
5120 return {NonCLikeKind::BaseClass,
5122 RD->bases_end()[-1].getEndLoc())};
5123 bool Invalid = false;
5124 for (Decl *D : RD->decls()) {
5125 // Don't complain about things we already diagnosed.
5126 if (D->isInvalidDecl()) {
5127 Invalid = true;
5128 continue;
5129 }
5130
5131 // -- have any [...] default member initializers
5132 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5133 if (FD->hasInClassInitializer()) {
5134 auto *Init = FD->getInClassInitializer();
5135 return {NonCLikeKind::DefaultMemberInit,
5136 Init ? Init->getSourceRange() : D->getSourceRange()};
5137 }
5138 continue;
5139 }
5140
5141 // FIXME: We don't allow friend declarations. This violates the wording of
5142 // P1766, but not the intent.
5143 if (isa<FriendDecl>(D))
5144 return {NonCLikeKind::Friend, D->getSourceRange()};
5145
5146 // -- declare any members other than non-static data members, member
5147 // enumerations, or member classes,
5149 isa<EnumDecl>(D))
5150 continue;
5151 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5152 if (!MemberRD) {
5153 if (D->isImplicit())
5154 continue;
5155 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5156 }
5157
5158 // -- contain a lambda-expression,
5159 if (MemberRD->isLambda())
5160 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5161
5162 // and all member classes shall also satisfy these requirements
5163 // (recursively).
5164 if (MemberRD->isThisDeclarationADefinition()) {
5165 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5166 return Kind;
5167 }
5168 }
5169
5170 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5171}
5172
5174 TypedefNameDecl *NewTD) {
5175 if (TagFromDeclSpec->isInvalidDecl())
5176 return;
5177
5178 // Do nothing if the tag already has a name for linkage purposes.
5179 if (TagFromDeclSpec->hasNameForLinkage())
5180 return;
5181
5182 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5183 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5184
5185 // The type must match the tag exactly; no qualifiers allowed.
5186 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5187 Context.getCanonicalTagType(TagFromDeclSpec))) {
5188 if (getLangOpts().CPlusPlus)
5189 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5190 return;
5191 }
5192
5193 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5194 // An unnamed class with a typedef name for linkage purposes shall [be
5195 // C-like].
5196 //
5197 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5198 // shouldn't happen, but there are constructs that the language rule doesn't
5199 // disallow for which we can't reasonably avoid computing linkage early.
5200 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5201 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5202 : NonCLikeKind();
5203 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5204 if (NonCLike || ChangesLinkage) {
5205 if (NonCLike.Kind == NonCLikeKind::Invalid)
5206 return;
5207
5208 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5209 if (ChangesLinkage) {
5210 // If the linkage changes, we can't accept this as an extension.
5211 if (NonCLike.Kind == NonCLikeKind::None)
5212 DiagID = diag::err_typedef_changes_linkage;
5213 else
5214 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5215 }
5216
5217 SourceLocation FixitLoc =
5218 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5219 llvm::SmallString<40> TextToInsert;
5220 TextToInsert += ' ';
5221 TextToInsert += NewTD->getIdentifier()->getName();
5222
5223 Diag(FixitLoc, DiagID)
5224 << isa<TypeAliasDecl>(NewTD)
5225 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5226 if (NonCLike.Kind != NonCLikeKind::None) {
5227 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5228 << NonCLike.Kind - 1 << NonCLike.Range;
5229 }
5230 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5231 << NewTD << isa<TypeAliasDecl>(NewTD);
5232
5233 if (ChangesLinkage)
5234 return;
5235 }
5236
5237 // Otherwise, set this as the anon-decl typedef for the tag.
5238 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5239
5240 // Now that we have a name for the tag, process API notes again.
5241 ProcessAPINotes(TagFromDeclSpec);
5242}
5243
5244static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5246 switch (T) {
5248 return 0;
5250 return 1;
5252 return 2;
5254 return 3;
5255 case DeclSpec::TST_enum:
5256 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5257 if (ED->isScopedUsingClassTag())
5258 return 5;
5259 if (ED->isScoped())
5260 return 6;
5261 }
5262 return 4;
5263 default:
5264 llvm_unreachable("unexpected type specifier");
5265 }
5266}
5267
5269 DeclSpec &DS,
5270 const ParsedAttributesView &DeclAttrs,
5271 MultiTemplateParamsArg TemplateParams,
5272 bool IsExplicitInstantiation,
5273 RecordDecl *&AnonRecord,
5274 SourceLocation EllipsisLoc) {
5275 Decl *TagD = nullptr;
5276 TagDecl *Tag = nullptr;
5282 TagD = DS.getRepAsDecl();
5283
5284 if (!TagD) // We probably had an error
5285 return nullptr;
5286
5287 // Note that the above type specs guarantee that the
5288 // type rep is a Decl, whereas in many of the others
5289 // it's a Type.
5290 if (isa<TagDecl>(TagD))
5291 Tag = cast<TagDecl>(TagD);
5292 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5293 Tag = CTD->getTemplatedDecl();
5294 }
5295
5296 if (Tag) {
5297 handleTagNumbering(Tag, S);
5298 Tag->setFreeStanding();
5299 if (Tag->isInvalidDecl())
5300 return Tag;
5301 }
5302
5303 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5304 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5305 // or incomplete types shall not be restrict-qualified."
5306 if (TypeQuals & DeclSpec::TQ_restrict)
5308 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5309 << DS.getSourceRange();
5310 }
5311
5312 if (DS.isInlineSpecified())
5313 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5314 << getLangOpts().CPlusPlus17;
5315
5316 if (DS.hasConstexprSpecifier()) {
5317 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5318 // and definitions of functions and variables.
5319 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5320 // the declaration of a function or function template
5321 if (Tag)
5322 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5324 << static_cast<int>(DS.getConstexprSpecifier());
5325 else if (getLangOpts().C23)
5326 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5327 else
5328 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5329 << static_cast<int>(DS.getConstexprSpecifier());
5330 // Don't emit warnings after this error.
5331 return TagD;
5332 }
5333
5335
5336 if (DS.isFriendSpecified()) {
5337 // If we're dealing with a decl but not a TagDecl, assume that
5338 // whatever routines created it handled the friendship aspect.
5339 if (TagD && !Tag)
5340 return nullptr;
5341 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5342 }
5343
5344 assert(EllipsisLoc.isInvalid() &&
5345 "Friend ellipsis but not friend-specified?");
5346
5347 // Track whether this decl-specifier declares anything.
5348 bool DeclaresAnything = true;
5349
5350 // Handle anonymous struct definitions.
5351 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5352 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5354 if (getLangOpts().CPlusPlus ||
5355 Record->getDeclContext()->isRecord()) {
5356 // If CurContext is a DeclContext that can contain statements,
5357 // RecursiveASTVisitor won't visit the decls that
5358 // BuildAnonymousStructOrUnion() will put into CurContext.
5359 // Also store them here so that they can be part of the
5360 // DeclStmt that gets created in this case.
5361 // FIXME: Also return the IndirectFieldDecls created by
5362 // BuildAnonymousStructOr union, for the same reason?
5363 if (CurContext->isFunctionOrMethod())
5364 AnonRecord = Record;
5365 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5366 Context.getPrintingPolicy());
5367 }
5368
5369 DeclaresAnything = false;
5370 }
5371 }
5372
5373 // C11 6.7.2.1p2:
5374 // A struct-declaration that does not declare an anonymous structure or
5375 // anonymous union shall contain a struct-declarator-list.
5376 //
5377 // This rule also existed in C89 and C99; the grammar for struct-declaration
5378 // did not permit a struct-declaration without a struct-declarator-list.
5379 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5381 // Check for Microsoft C extension: anonymous struct/union member.
5382 // Handle 2 kinds of anonymous struct/union:
5383 // struct STRUCT;
5384 // union UNION;
5385 // and
5386 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5387 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5388 if ((Tag && Tag->getDeclName()) ||
5390 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5391 : DS.getRepAsType().get()->getAsRecordDecl();
5392 if (Record && getLangOpts().MSAnonymousStructs) {
5393 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5394 << Record->isUnion() << DS.getSourceRange();
5396 }
5397
5398 DeclaresAnything = false;
5399 }
5400 }
5401
5402 // Skip all the checks below if we have a type error.
5404 (TagD && TagD->isInvalidDecl()))
5405 return TagD;
5406
5407 if (getLangOpts().CPlusPlus &&
5409 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5410 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5411 !Enum->isInvalidDecl())
5412 DeclaresAnything = false;
5413
5414 if (!DS.isMissingDeclaratorOk()) {
5415 // Customize diagnostic for a typedef missing a name.
5417 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5418 << DS.getSourceRange();
5419 else
5420 DeclaresAnything = false;
5421 }
5422
5423 if (DS.isModulePrivateSpecified() &&
5424 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5425 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5426 << Tag->getTagKind()
5428
5430
5431 // C 6.7/2:
5432 // A declaration [...] shall declare at least a declarator [...], a tag,
5433 // or the members of an enumeration.
5434 // C++ [dcl.dcl]p3:
5435 // [If there are no declarators], and except for the declaration of an
5436 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5437 // names into the program, or shall redeclare a name introduced by a
5438 // previous declaration.
5439 if (!DeclaresAnything) {
5440 // In C, we allow this as a (popular) extension / bug. Don't bother
5441 // producing further diagnostics for redundant qualifiers after this.
5442 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5443 ? diag::err_no_declarators
5444 : diag::ext_no_declarators)
5445 << DS.getSourceRange();
5446 return TagD;
5447 }
5448
5449 // C++ [dcl.stc]p1:
5450 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5451 // init-declarator-list of the declaration shall not be empty.
5452 // C++ [dcl.fct.spec]p1:
5453 // If a cv-qualifier appears in a decl-specifier-seq, the
5454 // init-declarator-list of the declaration shall not be empty.
5455 //
5456 // Spurious qualifiers here appear to be valid in C.
5457 unsigned DiagID = diag::warn_standalone_specifier;
5458 if (getLangOpts().CPlusPlus)
5459 DiagID = diag::ext_standalone_specifier;
5460
5461 // Note that a linkage-specification sets a storage class, but
5462 // 'extern "C" struct foo;' is actually valid and not theoretically
5463 // useless.
5464 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5465 if (SCS == DeclSpec::SCS_mutable)
5466 // Since mutable is not a viable storage class specifier in C, there is
5467 // no reason to treat it as an extension. Instead, diagnose as an error.
5468 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5469 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5470 Diag(DS.getStorageClassSpecLoc(), DiagID)
5472 }
5473
5477 if (DS.getTypeQualifiers()) {
5479 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5481 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5482 // Restrict is covered above.
5484 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5486 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5487 }
5488
5489 // Warn about ignored type attributes, for example:
5490 // __attribute__((aligned)) struct A;
5491 // Attributes should be placed after tag to apply to type declaration.
5492 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5493 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5494 if (TypeSpecType == DeclSpec::TST_class ||
5495 TypeSpecType == DeclSpec::TST_struct ||
5496 TypeSpecType == DeclSpec::TST_interface ||
5497 TypeSpecType == DeclSpec::TST_union ||
5498 TypeSpecType == DeclSpec::TST_enum) {
5499
5500 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5501 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5502 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5503 DiagnosticId = diag::warn_attribute_ignored;
5504 else if (AL.isRegularKeywordAttribute())
5505 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5506 else
5507 DiagnosticId = diag::warn_declspec_attribute_ignored;
5508 Diag(AL.getLoc(), DiagnosticId)
5509 << AL << GetDiagnosticTypeSpecifierID(DS);
5510 };
5511
5512 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5513 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5514 }
5515 }
5516
5517 return TagD;
5518}
5519
5520/// We are trying to inject an anonymous member into the given scope;
5521/// check if there's an existing declaration that can't be overloaded.
5522///
5523/// \return true if this is a forbidden redeclaration
5524static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5525 DeclContext *Owner,
5526 DeclarationName Name,
5527 SourceLocation NameLoc, bool IsUnion,
5528 StorageClass SC) {
5529 LookupResult R(SemaRef, Name, NameLoc,
5533 if (!SemaRef.LookupName(R, S)) return false;
5534
5535 // Pick a representative declaration.
5536 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5537 assert(PrevDecl && "Expected a non-null Decl");
5538
5539 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5540 return false;
5541
5542 if (SC == StorageClass::SC_None &&
5543 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5544 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5545 if (!Owner->isRecord())
5546 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5547 return false;
5548 }
5549
5550 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5551 << IsUnion << Name;
5552 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5553
5554 return true;
5555}
5556
5558 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5560}
5561
5563 if (!getLangOpts().CPlusPlus)
5564 return;
5565
5566 // This function can be parsed before we have validated the
5567 // structure as an anonymous struct
5568 if (Record->isAnonymousStructOrUnion())
5569 return;
5570
5571 const NamedDecl *First = 0;
5572 for (const Decl *D : Record->decls()) {
5573 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5574 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5575 continue;
5576 if (!First)
5577 First = ND;
5578 else
5580 }
5581}
5582
5583/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5584/// anonymous struct or union AnonRecord into the owning context Owner
5585/// and scope S. This routine will be invoked just after we realize
5586/// that an unnamed union or struct is actually an anonymous union or
5587/// struct, e.g.,
5588///
5589/// @code
5590/// union {
5591/// int i;
5592/// float f;
5593/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5594/// // f into the surrounding scope.x
5595/// @endcode
5596///
5597/// This routine is recursive, injecting the names of nested anonymous
5598/// structs/unions into the owning context and scope as well.
5599static bool
5601 RecordDecl *AnonRecord, AccessSpecifier AS,
5602 StorageClass SC,
5603 SmallVectorImpl<NamedDecl *> &Chaining) {
5604 bool Invalid = false;
5605
5606 // Look every FieldDecl and IndirectFieldDecl with a name.
5607 for (auto *D : AnonRecord->decls()) {
5608 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5609 cast<NamedDecl>(D)->getDeclName()) {
5610 ValueDecl *VD = cast<ValueDecl>(D);
5611 // C++ [class.union]p2:
5612 // The names of the members of an anonymous union shall be
5613 // distinct from the names of any other entity in the
5614 // scope in which the anonymous union is declared.
5615
5616 bool FieldInvalid = CheckAnonMemberRedeclaration(
5617 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5618 AnonRecord->isUnion(), SC);
5619 if (FieldInvalid)
5620 Invalid = true;
5621
5622 // Inject the IndirectFieldDecl even if invalid, because later
5623 // diagnostics may depend on it being present, see findDefaultInitializer.
5624
5625 // C++ [class.union]p2:
5626 // For the purpose of name lookup, after the anonymous union
5627 // definition, the members of the anonymous union are
5628 // considered to have been defined in the scope in which the
5629 // anonymous union is declared.
5630 unsigned OldChainingSize = Chaining.size();
5631 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5632 Chaining.append(IF->chain_begin(), IF->chain_end());
5633 else
5634 Chaining.push_back(VD);
5635
5636 assert(Chaining.size() >= 2);
5637 NamedDecl **NamedChain =
5638 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5639 for (unsigned i = 0; i < Chaining.size(); i++)
5640 NamedChain[i] = Chaining[i];
5641
5643 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5644 VD->getType(), {NamedChain, Chaining.size()});
5645
5646 for (const auto *Attr : VD->attrs())
5647 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5648
5649 IndirectField->setAccess(AS);
5650 IndirectField->setImplicit();
5651 IndirectField->setInvalidDecl(FieldInvalid);
5652 SemaRef.PushOnScopeChains(IndirectField, S);
5653
5654 // That includes picking up the appropriate access specifier.
5655 if (AS != AS_none)
5656 IndirectField->setAccess(AS);
5657
5658 Chaining.resize(OldChainingSize);
5659 }
5660 }
5661
5662 return Invalid;
5663}
5664
5665/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5666/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5667/// illegal input values are mapped to SC_None.
5668static StorageClass
5670 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5671 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5672 "Parser allowed 'typedef' as storage class VarDecl.");
5673 switch (StorageClassSpec) {
5676 if (DS.isExternInLinkageSpec())
5677 return SC_None;
5678 return SC_Extern;
5679 case DeclSpec::SCS_static: return SC_Static;
5680 case DeclSpec::SCS_auto: return SC_Auto;
5683 // Illegal SCSs map to None: error reporting is up to the caller.
5684 case DeclSpec::SCS_mutable: // Fall through.
5685 case DeclSpec::SCS_typedef: return SC_None;
5686 }
5687 llvm_unreachable("unknown storage class specifier");
5688}
5689
5691 assert(Record->hasInClassInitializer());
5692
5693 for (const auto *I : Record->decls()) {
5694 const auto *FD = dyn_cast<FieldDecl>(I);
5695 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5696 FD = IFD->getAnonField();
5697 if (FD && FD->hasInClassInitializer())
5698 return FD->getLocation();
5699 }
5700
5701 llvm_unreachable("couldn't find in-class initializer");
5702}
5703
5705 SourceLocation DefaultInitLoc) {
5706 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5707 return;
5708
5709 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5710 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5711}
5712
5714 CXXRecordDecl *AnonUnion) {
5715 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5716 return;
5717
5719}
5720
5722 AccessSpecifier AS,
5724 const PrintingPolicy &Policy) {
5725 DeclContext *Owner = Record->getDeclContext();
5726
5727 // Diagnose whether this anonymous struct/union is an extension.
5728 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5729 Diag(Record->getLocation(), diag::ext_anonymous_union);
5730 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5731 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5732 else if (!Record->isUnion() && !getLangOpts().C11)
5733 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5734
5735 // C and C++ require different kinds of checks for anonymous
5736 // structs/unions.
5737 bool Invalid = false;
5738 if (getLangOpts().CPlusPlus) {
5739 const char *PrevSpec = nullptr;
5740 if (Record->isUnion()) {
5741 // C++ [class.union]p6:
5742 // C++17 [class.union.anon]p2:
5743 // Anonymous unions declared in a named namespace or in the
5744 // global namespace shall be declared static.
5745 unsigned DiagID;
5746 DeclContext *OwnerScope = Owner->getRedeclContext();
5748 (OwnerScope->isTranslationUnit() ||
5749 (OwnerScope->isNamespace() &&
5750 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5751 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5752 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5753
5754 // Recover by adding 'static'.
5756 PrevSpec, DiagID, Policy);
5757 }
5758 // C++ [class.union]p6:
5759 // A storage class is not allowed in a declaration of an
5760 // anonymous union in a class scope.
5762 isa<RecordDecl>(Owner)) {
5764 diag::err_anonymous_union_with_storage_spec)
5766
5767 // Recover by removing the storage specifier.
5770 PrevSpec, DiagID, Context.getPrintingPolicy());
5771 }
5772 }
5773
5774 // Ignore const/volatile/restrict qualifiers.
5775 if (DS.getTypeQualifiers()) {
5777 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5778 << Record->isUnion() << "const"
5782 diag::ext_anonymous_struct_union_qualified)
5783 << Record->isUnion() << "volatile"
5787 diag::ext_anonymous_struct_union_qualified)
5788 << Record->isUnion() << "restrict"
5792 diag::ext_anonymous_struct_union_qualified)
5793 << Record->isUnion() << "_Atomic"
5797 diag::ext_anonymous_struct_union_qualified)
5798 << Record->isUnion() << "__unaligned"
5800
5802 }
5803
5804 // C++ [class.union]p2:
5805 // The member-specification of an anonymous union shall only
5806 // define non-static data members. [Note: nested types and
5807 // functions cannot be declared within an anonymous union. ]
5808 for (auto *Mem : Record->decls()) {
5809 // Ignore invalid declarations; we already diagnosed them.
5810 if (Mem->isInvalidDecl())
5811 continue;
5812
5813 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5814 // C++ [class.union]p3:
5815 // An anonymous union shall not have private or protected
5816 // members (clause 11).
5817 assert(FD->getAccess() != AS_none);
5818 if (FD->getAccess() != AS_public) {
5819 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5820 << Record->isUnion() << (FD->getAccess() == AS_protected);
5821 Invalid = true;
5822 }
5823
5824 // C++ [class.union]p1
5825 // An object of a class with a non-trivial constructor, a non-trivial
5826 // copy constructor, a non-trivial destructor, or a non-trivial copy
5827 // assignment operator cannot be a member of a union, nor can an
5828 // array of such objects.
5829 if (CheckNontrivialField(FD))
5830 Invalid = true;
5831 } else if (Mem->isImplicit()) {
5832 // Any implicit members are fine.
5833 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5834 // This is a type that showed up in an
5835 // elaborated-type-specifier inside the anonymous struct or
5836 // union, but which actually declares a type outside of the
5837 // anonymous struct or union. It's okay.
5838 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5839 if (!MemRecord->isAnonymousStructOrUnion() &&
5840 MemRecord->getDeclName()) {
5841 // Visual C++ allows type definition in anonymous struct or union.
5842 if (getLangOpts().MicrosoftExt)
5843 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5844 << Record->isUnion();
5845 else {
5846 // This is a nested type declaration.
5847 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5848 << Record->isUnion();
5849 Invalid = true;
5850 }
5851 } else {
5852 // This is an anonymous type definition within another anonymous type.
5853 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5854 // not part of standard C++.
5855 Diag(MemRecord->getLocation(),
5856 diag::ext_anonymous_record_with_anonymous_type)
5857 << Record->isUnion();
5858 }
5859 } else if (isa<AccessSpecDecl>(Mem)) {
5860 // Any access specifier is fine.
5861 } else if (isa<StaticAssertDecl>(Mem)) {
5862 // In C++1z, static_assert declarations are also fine.
5863 } else {
5864 // We have something that isn't a non-static data
5865 // member. Complain about it.
5866 unsigned DK = diag::err_anonymous_record_bad_member;
5867 if (isa<TypeDecl>(Mem))
5868 DK = diag::err_anonymous_record_with_type;
5869 else if (isa<FunctionDecl>(Mem))
5870 DK = diag::err_anonymous_record_with_function;
5871 else if (isa<VarDecl>(Mem))
5872 DK = diag::err_anonymous_record_with_static;
5873
5874 // Visual C++ allows type definition in anonymous struct or union.
5875 if (getLangOpts().MicrosoftExt &&
5876 DK == diag::err_anonymous_record_with_type)
5877 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5878 << Record->isUnion();
5879 else {
5880 Diag(Mem->getLocation(), DK) << Record->isUnion();
5881 Invalid = true;
5882 }
5883 }
5884 }
5885
5886 // C++11 [class.union]p8 (DR1460):
5887 // At most one variant member of a union may have a
5888 // brace-or-equal-initializer.
5889 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5890 Owner->isRecord())
5893 }
5894
5895 if (!Record->isUnion() && !Owner->isRecord()) {
5896 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5897 << getLangOpts().CPlusPlus;
5898 Invalid = true;
5899 }
5900
5901 // C++ [dcl.dcl]p3:
5902 // [If there are no declarators], and except for the declaration of an
5903 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5904 // names into the program
5905 // C++ [class.mem]p2:
5906 // each such member-declaration shall either declare at least one member
5907 // name of the class or declare at least one unnamed bit-field
5908 //
5909 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5910 if (getLangOpts().CPlusPlus && Record->field_empty())
5911 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5912
5913 // Mock up a declarator.
5917 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5918
5919 // Create a declaration for this anonymous struct/union.
5920 NamedDecl *Anon = nullptr;
5921 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5922 Anon = FieldDecl::Create(
5923 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5924 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5925 /*BitWidth=*/nullptr, /*Mutable=*/false,
5926 /*InitStyle=*/ICIS_NoInit);
5927 Anon->setAccess(AS);
5928 ProcessDeclAttributes(S, Anon, Dc);
5929
5930 if (getLangOpts().CPlusPlus)
5931 FieldCollector->Add(cast<FieldDecl>(Anon));
5932 } else {
5933 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5934 if (SCSpec == DeclSpec::SCS_mutable) {
5935 // mutable can only appear on non-static class members, so it's always
5936 // an error here
5937 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5938 Invalid = true;
5939 SC = SC_None;
5940 }
5941
5942 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5943 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5944 Context.getCanonicalTagType(Record), TInfo, SC);
5945 if (Invalid)
5946 Anon->setInvalidDecl();
5947
5948 ProcessDeclAttributes(S, Anon, Dc);
5949
5950 // Default-initialize the implicit variable. This initialization will be
5951 // trivial in almost all cases, except if a union member has an in-class
5952 // initializer:
5953 // union { int n = 0; };
5955 }
5956 Anon->setImplicit();
5957
5958 // Mark this as an anonymous struct/union type.
5959 Record->setAnonymousStructOrUnion(true);
5960
5961 // Add the anonymous struct/union object to the current
5962 // context. We'll be referencing this object when we refer to one of
5963 // its members.
5964 Owner->addDecl(Anon);
5965
5966 // Inject the members of the anonymous struct/union into the owning
5967 // context and into the identifier resolver chain for name lookup
5968 // purposes.
5970 Chain.push_back(Anon);
5971
5972 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5973 Chain))
5974 Invalid = true;
5975
5976 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5977 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5979 Decl *ManglingContextDecl;
5980 std::tie(MCtx, ManglingContextDecl) =
5981 getCurrentMangleNumberContext(NewVD->getDeclContext());
5982 if (MCtx) {
5983 Context.setManglingNumber(
5984 NewVD, MCtx->getManglingNumber(
5985 NewVD, getMSManglingNumber(getLangOpts(), S)));
5986 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5987 }
5988 }
5989 }
5990
5991 if (Invalid)
5992 Anon->setInvalidDecl();
5993
5994 return Anon;
5995}
5996
5998 RecordDecl *Record) {
5999 assert(Record && "expected a record!");
6000
6001 // Mock up a declarator.
6004 assert(TInfo && "couldn't build declarator info for anonymous struct");
6005
6006 auto *ParentDecl = cast<RecordDecl>(CurContext);
6007 CanQualType RecTy = Context.getCanonicalTagType(Record);
6008
6009 // Create a declaration for this anonymous struct.
6010 NamedDecl *Anon =
6011 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
6012 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
6013 /*BitWidth=*/nullptr, /*Mutable=*/false,
6014 /*InitStyle=*/ICIS_NoInit);
6015 Anon->setImplicit();
6016
6017 // Add the anonymous struct object to the current context.
6018 CurContext->addDecl(Anon);
6019
6020 // Inject the members of the anonymous struct into the current
6021 // context and into the identifier resolver chain for name lookup
6022 // purposes.
6024 Chain.push_back(Anon);
6025
6026 RecordDecl *RecordDef = Record->getDefinition();
6027 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
6028 diag::err_field_incomplete_or_sizeless) ||
6030 *this, S, CurContext, RecordDef, AS_none,
6032 Anon->setInvalidDecl();
6033 ParentDecl->setInvalidDecl();
6034 }
6035
6036 return Anon;
6037}
6038
6042
6045 DeclarationNameInfo NameInfo;
6046 NameInfo.setLoc(Name.StartLocation);
6047
6048 switch (Name.getKind()) {
6049
6052 NameInfo.setName(Name.Identifier);
6053 return NameInfo;
6054
6056 // C++ [temp.deduct.guide]p3:
6057 // The simple-template-id shall name a class template specialization.
6058 // The template-name shall be the same identifier as the template-name
6059 // of the simple-template-id.
6060 // These together intend to imply that the template-name shall name a
6061 // class template.
6062 // FIXME: template<typename T> struct X {};
6063 // template<typename T> using Y = X<T>;
6064 // Y(int) -> Y<int>;
6065 // satisfies these rules but does not name a class template.
6066 TemplateName TN = Name.TemplateName.get().get();
6067 auto *Template = TN.getAsTemplateDecl();
6069 Diag(Name.StartLocation,
6070 diag::err_deduction_guide_name_not_class_template)
6071 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6072 if (Template)
6074 return DeclarationNameInfo();
6075 }
6076
6077 NameInfo.setName(
6078 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6079 return NameInfo;
6080 }
6081
6083 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6087 return NameInfo;
6088
6090 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6091 Name.Identifier));
6093 return NameInfo;
6094
6096 TypeSourceInfo *TInfo;
6098 if (Ty.isNull())
6099 return DeclarationNameInfo();
6100 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6101 Context.getCanonicalType(Ty)));
6102 NameInfo.setNamedTypeInfo(TInfo);
6103 return NameInfo;
6104 }
6105
6107 TypeSourceInfo *TInfo;
6108 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6109 if (Ty.isNull())
6110 return DeclarationNameInfo();
6111 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6112 Context.getCanonicalType(Ty)));
6113 NameInfo.setNamedTypeInfo(TInfo);
6114 return NameInfo;
6115 }
6116
6118 // In well-formed code, we can only have a constructor
6119 // template-id that refers to the current context, so go there
6120 // to find the actual type being constructed.
6121 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6122 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6123 return DeclarationNameInfo();
6124
6125 // Determine the type of the class being constructed.
6126 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6127
6128 // FIXME: Check two things: that the template-id names the same type as
6129 // CurClassType, and that the template-id does not occur when the name
6130 // was qualified.
6131
6132 NameInfo.setName(
6133 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6134 // FIXME: should we retrieve TypeSourceInfo?
6135 NameInfo.setNamedTypeInfo(nullptr);
6136 return NameInfo;
6137 }
6138
6140 TypeSourceInfo *TInfo;
6141 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6142 if (Ty.isNull())
6143 return DeclarationNameInfo();
6144 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6145 Context.getCanonicalType(Ty)));
6146 NameInfo.setNamedTypeInfo(TInfo);
6147 return NameInfo;
6148 }
6149
6151 TemplateName TName = Name.TemplateId->Template.get();
6152 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6153 return Context.getNameForTemplate(TName, TNameLoc);
6154 }
6155
6156 } // switch (Name.getKind())
6157
6158 llvm_unreachable("Unknown name kind");
6159}
6160
6162 do {
6163 if (Ty->isPointerOrReferenceType())
6164 Ty = Ty->getPointeeType();
6165 else if (Ty->isArrayType())
6167 else
6168 return Ty.withoutLocalFastQualifiers();
6169 } while (true);
6170}
6171
6172/// hasSimilarParameters - Determine whether the C++ functions Declaration
6173/// and Definition have "nearly" matching parameters. This heuristic is
6174/// used to improve diagnostics in the case where an out-of-line function
6175/// definition doesn't match any declaration within the class or namespace.
6176/// Also sets Params to the list of indices to the parameters that differ
6177/// between the declaration and the definition. If hasSimilarParameters
6178/// returns true and Params is empty, then all of the parameters match.
6182 SmallVectorImpl<unsigned> &Params) {
6183 Params.clear();
6184 if (Declaration->param_size() != Definition->param_size())
6185 return false;
6186 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6187 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6188 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6189
6190 // The parameter types are identical
6191 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6192 continue;
6193
6194 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6195 QualType DefParamBaseTy = getCoreType(DefParamTy);
6196 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6197 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6198
6199 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6200 (DeclTyName && DeclTyName == DefTyName))
6201 Params.push_back(Idx);
6202 else // The two parameters aren't even close
6203 return false;
6204 }
6205
6206 return true;
6207}
6208
6209/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6210/// declarator needs to be rebuilt in the current instantiation.
6211/// Any bits of declarator which appear before the name are valid for
6212/// consideration here. That's specifically the type in the decl spec
6213/// and the base type in any member-pointer chunks.
6215 DeclarationName Name) {
6216 // The types we specifically need to rebuild are:
6217 // - typenames, typeofs, and decltypes
6218 // - types which will become injected class names
6219 // Of course, we also need to rebuild any type referencing such a
6220 // type. It's safest to just say "dependent", but we call out a
6221 // few cases here.
6222
6223 DeclSpec &DS = D.getMutableDeclSpec();
6224 switch (DS.getTypeSpecType()) {
6228#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6229#include "clang/Basic/TransformTypeTraits.def"
6230 case DeclSpec::TST_atomic: {
6231 // Grab the type from the parser.
6232 TypeSourceInfo *TSI = nullptr;
6233 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6234 if (T.isNull() || !T->isInstantiationDependentType()) break;
6235
6236 // Make sure there's a type source info. This isn't really much
6237 // of a waste; most dependent types should have type source info
6238 // attached already.
6239 if (!TSI)
6241
6242 // Rebuild the type in the current instantiation.
6244 if (!TSI) return true;
6245
6246 // Store the new type back in the decl spec.
6247 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6248 DS.UpdateTypeRep(LocType);
6249 break;
6250 }
6251
6255 Expr *E = DS.getRepAsExpr();
6257 if (Result.isInvalid()) return true;
6258 DS.UpdateExprRep(Result.get());
6259 break;
6260 }
6261
6262 default:
6263 // Nothing to do for these decl specs.
6264 break;
6265 }
6266
6267 // It doesn't matter what order we do this in.
6268 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6269 DeclaratorChunk &Chunk = D.getTypeObject(I);
6270
6271 // The only type information in the declarator which can come
6272 // before the declaration name is the base type of a member
6273 // pointer.
6275 continue;
6276
6277 // Rebuild the scope specifier in-place.
6278 CXXScopeSpec &SS = Chunk.Mem.Scope();
6280 return true;
6281 }
6282
6283 return false;
6284}
6285
6286/// Returns true if the declaration is declared in a system header or from a
6287/// system macro.
6288static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6289 return SM.isInSystemHeader(D->getLocation()) ||
6290 SM.isInSystemMacro(D->getLocation());
6291}
6292
6294 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6295 // of system decl.
6296 if (D->getPreviousDecl() || D->isImplicit())
6297 return;
6300 !isFromSystemHeader(Context.getSourceManager(), D)) {
6301 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6302 << D << static_cast<int>(Status);
6303 }
6304}
6305
6308
6309 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6310 // declaration only if the `bind_to_declaration` extension is set.
6312 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6313 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6314 llvm::omp::TraitProperty::
6315 implementation_extension_bind_to_declaration))
6317 S, D, MultiTemplateParamsArg(), Bases);
6318
6320
6321 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6322 Dcl && Dcl->getDeclContext()->isFileContext())
6324
6325 if (!Bases.empty())
6327 Bases);
6328
6329 return Dcl;
6330}
6331
6333 DeclarationNameInfo NameInfo) {
6334 DeclarationName Name = NameInfo.getName();
6335
6336 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6337 while (Record && Record->isAnonymousStructOrUnion())
6338 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6339 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6340 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6341 return true;
6342 }
6343
6344 return false;
6345}
6346
6348 DeclarationName Name,
6349 SourceLocation Loc,
6350 TemplateIdAnnotation *TemplateId,
6351 bool IsMemberSpecialization) {
6352 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6353 "without nested-name-specifier");
6354 DeclContext *Cur = CurContext;
6355 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6356 Cur = Cur->getParent();
6357
6358 // If the user provided a superfluous scope specifier that refers back to the
6359 // class in which the entity is already declared, diagnose and ignore it.
6360 //
6361 // class X {
6362 // void X::f();
6363 // };
6364 //
6365 // Note, it was once ill-formed to give redundant qualification in all
6366 // contexts, but that rule was removed by DR482.
6367 if (Cur->Equals(DC)) {
6368 if (Cur->isRecord()) {
6369 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6370 : diag::err_member_extra_qualification)
6371 << Name << FixItHint::CreateRemoval(SS.getRange());
6372 SS.clear();
6373 } else {
6374 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6375 }
6376 return false;
6377 }
6378
6379 // Check whether the qualifying scope encloses the scope of the original
6380 // declaration. For a template-id, we perform the checks in
6381 // CheckTemplateSpecializationScope.
6382 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6383 if (Cur->isRecord())
6384 Diag(Loc, diag::err_member_qualification)
6385 << Name << SS.getRange();
6386 else if (isa<TranslationUnitDecl>(DC))
6387 Diag(Loc, diag::err_invalid_declarator_global_scope)
6388 << Name << SS.getRange();
6389 else if (isa<FunctionDecl>(Cur))
6390 Diag(Loc, diag::err_invalid_declarator_in_function)
6391 << Name << SS.getRange();
6392 else if (isa<BlockDecl>(Cur))
6393 Diag(Loc, diag::err_invalid_declarator_in_block)
6394 << Name << SS.getRange();
6395 else if (isa<ExportDecl>(Cur)) {
6396 if (!isa<NamespaceDecl>(DC))
6397 Diag(Loc, diag::err_export_non_namespace_scope_name)
6398 << Name << SS.getRange();
6399 else
6400 // The cases that DC is not NamespaceDecl should be handled in
6401 // CheckRedeclarationExported.
6402 return false;
6403 } else
6404 Diag(Loc, diag::err_invalid_declarator_scope)
6405 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6406
6407 return true;
6408 }
6409
6410 if (Cur->isRecord()) {
6411 // C++26 [temp.expl.spec]p3 (Adopted as a DR in CWG727):
6412 // An explicit specialization may be declared in any scope in which the
6413 // corresponding primary template may be defined.
6414 if (IsMemberSpecialization)
6415 return false;
6416
6417 // Cannot qualify members within a class.
6418 Diag(Loc, diag::err_member_qualification)
6419 << Name << SS.getRange();
6420 SS.clear();
6421
6422 // C++ constructors and destructors with incorrect scopes can break
6423 // our AST invariants by having the wrong underlying types. If
6424 // that's the case, then drop this declaration entirely.
6427 !Context.hasSameType(
6428 Name.getCXXNameType(),
6429 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6430 return true;
6431
6432 return false;
6433 }
6434
6435 // C++23 [temp.names]p5:
6436 // The keyword template shall not appear immediately after a declarative
6437 // nested-name-specifier.
6438 //
6439 // First check the template-id (if any), and then check each component of the
6440 // nested-name-specifier in reverse order.
6441 //
6442 // FIXME: nested-name-specifiers in friend declarations are declarative,
6443 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6444 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6445 Diag(Loc, diag::ext_template_after_declarative_nns)
6447
6449 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6450 TL = std::exchange(NextTL, TypeLoc())) {
6451 SourceLocation TemplateKeywordLoc;
6452 switch (TL.getTypeLocClass()) {
6453 case TypeLoc::TemplateSpecialization: {
6454 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6455 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6456 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6457 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6458 << TST.getLocalSourceRange();
6459 break;
6460 }
6461 case TypeLoc::Decltype:
6462 case TypeLoc::PackIndexing: {
6463 const Type *T = TL.getTypePtr();
6464 // C++23 [expr.prim.id.qual]p2:
6465 // [...] A declarative nested-name-specifier shall not have a
6466 // computed-type-specifier.
6467 //
6468 // CWG2858 changed this from 'decltype-specifier' to
6469 // 'computed-type-specifier'.
6470 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6471 << T->isDecltypeType() << TL.getSourceRange();
6472 break;
6473 }
6474 case TypeLoc::DependentName:
6475 NextTL =
6476 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6477 break;
6478 default:
6479 break;
6480 }
6481 if (TemplateKeywordLoc.isValid())
6482 Diag(Loc, diag::ext_template_after_declarative_nns)
6483 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6484 }
6485
6486 return false;
6487}
6488
6490 MultiTemplateParamsArg TemplateParamLists) {
6491 // TODO: consider using NameInfo for diagnostic.
6493 DeclarationName Name = NameInfo.getName();
6494
6495 // All of these full declarators require an identifier. If it doesn't have
6496 // one, the ParsedFreeStandingDeclSpec action should be used.
6497 if (D.isDecompositionDeclarator()) {
6498 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6499 } else if (!Name) {
6500 if (!D.isInvalidType()) // Reject this if we think it is valid.
6501 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6503 return nullptr;
6505 return nullptr;
6506
6507 DeclContext *DC = CurContext;
6508 if (D.getCXXScopeSpec().isInvalid())
6509 D.setInvalidType();
6510 else if (D.getCXXScopeSpec().isSet()) {
6513 return nullptr;
6514
6515 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6516 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6517 if (!DC || isa<EnumDecl>(DC)) {
6518 // If we could not compute the declaration context, it's because the
6519 // declaration context is dependent but does not refer to a class,
6520 // class template, or class template partial specialization. Complain
6521 // and return early, to avoid the coming semantic disaster.
6523 diag::err_template_qualified_declarator_no_match)
6525 << D.getCXXScopeSpec().getRange();
6526 return nullptr;
6527 }
6528 bool IsDependentContext = DC->isDependentContext();
6529
6530 if (!IsDependentContext &&
6532 return nullptr;
6533
6534 // If a class is incomplete, do not parse entities inside it.
6537 diag::err_member_def_undefined_record)
6538 << Name << DC << D.getCXXScopeSpec().getRange();
6539 return nullptr;
6540 }
6541 if (!D.getDeclSpec().isFriendSpecified()) {
6542 TemplateIdAnnotation *TemplateId =
6544 ? D.getName().TemplateId
6545 : nullptr;
6547 D.getIdentifierLoc(), TemplateId,
6548 /*IsMemberSpecialization=*/false)) {
6549 if (DC->isRecord())
6550 return nullptr;
6551
6552 D.setInvalidType();
6553 }
6554 }
6555
6556 // Check whether we need to rebuild the type of the given
6557 // declaration in the current instantiation.
6558 if (EnteringContext && IsDependentContext &&
6559 TemplateParamLists.size() != 0) {
6560 ContextRAII SavedContext(*this, DC);
6561 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6562 D.setInvalidType();
6563 }
6564 }
6565
6567 QualType R = TInfo->getType();
6568
6571 D.setInvalidType();
6572
6573 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6575
6576 // See if this is a redefinition of a variable in the same scope.
6577 if (!D.getCXXScopeSpec().isSet()) {
6578 bool IsLinkageLookup = false;
6579 bool CreateBuiltins = false;
6580
6581 // If the declaration we're planning to build will be a function
6582 // or object with linkage, then look for another declaration with
6583 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6584 //
6585 // If the declaration we're planning to build will be declared with
6586 // external linkage in the translation unit, create any builtin with
6587 // the same name.
6589 /* Do nothing*/;
6590 else if (CurContext->isFunctionOrMethod() &&
6592 R->isFunctionType())) {
6593 IsLinkageLookup = true;
6594 CreateBuiltins =
6595 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6596 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6598 CreateBuiltins = true;
6599
6600 if (IsLinkageLookup) {
6602 Previous.setRedeclarationKind(
6604 }
6605
6606 LookupName(Previous, S, CreateBuiltins);
6607 } else { // Something like "int foo::x;"
6609
6610 // C++ [dcl.meaning]p1:
6611 // When the declarator-id is qualified, the declaration shall refer to a
6612 // previously declared member of the class or namespace to which the
6613 // qualifier refers (or, in the case of a namespace, of an element of the
6614 // inline namespace set of that namespace (7.3.1)) or to a specialization
6615 // thereof; [...]
6616 //
6617 // Note that we already checked the context above, and that we do not have
6618 // enough information to make sure that Previous contains the declaration
6619 // we want to match. For example, given:
6620 //
6621 // class X {
6622 // void f();
6623 // void f(float);
6624 // };
6625 //
6626 // void X::f(int) { } // ill-formed
6627 //
6628 // In this case, Previous will point to the overload set
6629 // containing the two f's declared in X, but neither of them
6630 // matches.
6631
6633 }
6634
6635 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6636 TPD && TPD->isTemplateParameter()) {
6637 // Older versions of clang allowed the names of function/variable templates
6638 // to shadow the names of their template parameters. For the compatibility
6639 // purposes we detect such cases and issue a default-to-error warning that
6640 // can be disabled with -Wno-strict-primary-template-shadow.
6641 if (!D.isInvalidType()) {
6642 bool AllowForCompatibility = false;
6643 if (Scope *DeclParent = S->getDeclParent();
6644 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6645 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6646 TemplateParamParent->isDeclScope(TPD);
6647 }
6649 AllowForCompatibility);
6650 }
6651
6652 // Just pretend that we didn't see the previous declaration.
6653 Previous.clear();
6654 }
6655
6656 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6657 // Forget that the previous declaration is the injected-class-name.
6658 Previous.clear();
6659
6660 // In C++, the previous declaration we find might be a tag type
6661 // (class or enum). In this case, the new declaration will hide the
6662 // tag type. Note that this applies to functions, function templates, and
6663 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6664 if (Previous.isSingleTagDecl() &&
6666 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6667 Previous.clear();
6668
6669 // Check that there are no default arguments other than in the parameters
6670 // of a function declaration (C++ only).
6671 if (getLangOpts().CPlusPlus)
6673
6674 /// Get the innermost enclosing declaration scope.
6675 S = S->getDeclParent();
6676
6677 NamedDecl *New;
6678
6679 bool AddToScope = true;
6681 if (TemplateParamLists.size()) {
6682 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6683 return nullptr;
6684 }
6685
6686 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6687 } else if (R->isFunctionType()) {
6688 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6689 TemplateParamLists,
6690 AddToScope);
6691 } else {
6692 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6693 AddToScope);
6694 }
6695
6696 if (!New)
6697 return nullptr;
6698
6700
6701 // If this has an identifier and is not a function template specialization,
6702 // add it to the scope stack.
6703 if (New->getDeclName() && AddToScope)
6705
6706 if (OpenMP().isInOpenMPDeclareTargetContext())
6708
6709 return New;
6710}
6711
6712/// Helper method to turn variable array types into constant array
6713/// types in certain situations which would otherwise be errors (for
6714/// GCC compatibility).
6716 ASTContext &Context,
6717 bool &SizeIsNegative,
6718 llvm::APSInt &Oversized) {
6719 // This method tries to turn a variable array into a constant
6720 // array even when the size isn't an ICE. This is necessary
6721 // for compatibility with code that depends on gcc's buggy
6722 // constant expression folding, like struct {char x[(int)(char*)2];}
6723 SizeIsNegative = false;
6724 Oversized = 0;
6725
6726 if (T->isDependentType())
6727 return QualType();
6728
6730 const Type *Ty = Qs.strip(T);
6731
6732 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6733 QualType Pointee = PTy->getPointeeType();
6734 QualType FixedType =
6735 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6736 Oversized);
6737 if (FixedType.isNull()) return FixedType;
6738 FixedType = Context.getPointerType(FixedType);
6739 return Qs.apply(Context, FixedType);
6740 }
6741 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6742 QualType Inner = PTy->getInnerType();
6743 QualType FixedType =
6744 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6745 Oversized);
6746 if (FixedType.isNull()) return FixedType;
6747 FixedType = Context.getParenType(FixedType);
6748 return Qs.apply(Context, FixedType);
6749 }
6750
6751 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6752 if (!VLATy)
6753 return QualType();
6754
6755 QualType ElemTy = VLATy->getElementType();
6756 if (ElemTy->isVariablyModifiedType()) {
6757 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6758 SizeIsNegative, Oversized);
6759 if (ElemTy.isNull())
6760 return QualType();
6761 }
6762
6764 if (!VLATy->getSizeExpr() ||
6765 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6766 return QualType();
6767
6768 llvm::APSInt Res = Result.Val.getInt();
6769
6770 // Check whether the array size is negative.
6771 if (Res.isSigned() && Res.isNegative()) {
6772 SizeIsNegative = true;
6773 return QualType();
6774 }
6775
6776 // Check whether the array is too large to be addressed.
6777 unsigned ActiveSizeBits =
6778 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6779 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6780 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6781 : Res.getActiveBits();
6782 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6783 Oversized = std::move(Res);
6784 return QualType();
6785 }
6786
6787 QualType FoldedArrayType = Context.getConstantArrayType(
6788 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6789 return Qs.apply(Context, FoldedArrayType);
6790}
6791
6792static void
6794 SrcTL = SrcTL.getUnqualifiedLoc();
6795 DstTL = DstTL.getUnqualifiedLoc();
6796 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6797 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6798 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6799 DstPTL.getPointeeLoc());
6800 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6801 return;
6802 }
6803 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6804 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6805 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6806 DstPTL.getInnerLoc());
6807 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6808 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6809 return;
6810 }
6811 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6812 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6813 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6814 TypeLoc DstElemTL = DstATL.getElementLoc();
6815 if (VariableArrayTypeLoc SrcElemATL =
6816 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6817 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6818 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6819 } else {
6820 DstElemTL.initializeFullCopy(SrcElemTL);
6821 }
6822 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6823 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6824 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6825}
6826
6827/// Helper method to turn variable array types into constant array
6828/// types in certain situations which would otherwise be errors (for
6829/// GCC compatibility).
6830static TypeSourceInfo*
6832 ASTContext &Context,
6833 bool &SizeIsNegative,
6834 llvm::APSInt &Oversized) {
6835 QualType FixedTy
6836 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6837 SizeIsNegative, Oversized);
6838 if (FixedTy.isNull())
6839 return nullptr;
6840 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6842 FixedTInfo->getTypeLoc());
6843 return FixedTInfo;
6844}
6845
6847 QualType &T, SourceLocation Loc,
6848 unsigned FailedFoldDiagID) {
6849 bool SizeIsNegative;
6850 llvm::APSInt Oversized;
6852 TInfo, Context, SizeIsNegative, Oversized);
6853 if (FixedTInfo) {
6854 Diag(Loc, diag::ext_vla_folded_to_constant);
6855 TInfo = FixedTInfo;
6856 T = FixedTInfo->getType();
6857 return true;
6858 }
6859
6860 if (SizeIsNegative)
6861 Diag(Loc, diag::err_typecheck_negative_array_size);
6862 else if (Oversized.getBoolValue())
6863 Diag(Loc, diag::err_array_too_large) << toString(
6864 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6865 /*UpperCase=*/false, /*InsertSeparators=*/true);
6866 else if (FailedFoldDiagID)
6867 Diag(Loc, FailedFoldDiagID);
6868 return false;
6869}
6870
6871void
6873 if (!getLangOpts().CPlusPlus &&
6875 // Don't need to track declarations in the TU in C.
6876 return;
6877
6878 // Note that we have a locally-scoped external with this name.
6879 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6880}
6881
6883 // FIXME: We can have multiple results via __attribute__((overloadable)).
6884 auto Result = Context.getExternCContextDecl()->lookup(Name);
6885 return Result.empty() ? nullptr : *Result.begin();
6886}
6887
6889 // FIXME: We should probably indicate the identifier in question to avoid
6890 // confusion for constructs like "virtual int a(), b;"
6891 if (DS.isVirtualSpecified())
6893 diag::err_virtual_non_function);
6894
6895 if (DS.hasExplicitSpecifier())
6897 diag::err_explicit_non_function);
6898
6899 if (DS.isNoreturnSpecified())
6901 diag::err_noreturn_non_function);
6902}
6903
6904NamedDecl*
6907 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6908 if (D.getCXXScopeSpec().isSet()) {
6909 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6910 << D.getCXXScopeSpec().getRange();
6911 D.setInvalidType();
6912 // Pretend we didn't see the scope specifier.
6913 DC = CurContext;
6914 Previous.clear();
6915 }
6916
6918
6921 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6922 ? diag::warn_ms_inline_non_function
6923 : diag::err_inline_non_function)
6924 << getLangOpts().CPlusPlus17;
6926 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6927 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6928
6932 diag::err_deduction_guide_invalid_specifier)
6933 << "typedef";
6934 else
6935 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6936 << D.getName().getSourceRange();
6937 return nullptr;
6938 }
6939
6940 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6941 if (!NewTD) return nullptr;
6942
6943 // Handle attributes prior to checking for duplicates in MergeVarDecl
6944 ProcessDeclAttributes(S, NewTD, D);
6945
6947
6948 bool Redeclaration = D.isRedeclaration();
6951 return ND;
6952}
6953
6954void
6956 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6957 // then it shall have block scope.
6958 // Note that variably modified types must be fixed before merging the decl so
6959 // that redeclarations will match.
6960 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6961 QualType T = TInfo->getType();
6962 if (T->isVariablyModifiedType()) {
6964
6965 if (S->getFnParent() == nullptr) {
6966 bool SizeIsNegative;
6967 llvm::APSInt Oversized;
6968 TypeSourceInfo *FixedTInfo =
6970 SizeIsNegative,
6971 Oversized);
6972 if (FixedTInfo) {
6973 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6974 NewTD->setTypeSourceInfo(FixedTInfo);
6975 } else {
6976 if (SizeIsNegative)
6977 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6978 else if (T->isVariableArrayType())
6979 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6980 else if (Oversized.getBoolValue())
6981 Diag(NewTD->getLocation(), diag::err_array_too_large)
6982 << toString(Oversized, 10);
6983 else
6984 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6985 NewTD->setInvalidDecl();
6986 }
6987 }
6988 }
6989}
6990
6991NamedDecl*
6994
6995 // Find the shadowed declaration before filtering for scope.
6996 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6997
6998 // Merge the decl with the existing one if appropriate. If the decl is
6999 // in an outer scope, it isn't the same thing.
7000 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
7001 /*AllowInlineNamespace*/false);
7003 if (!Previous.empty()) {
7004 Redeclaration = true;
7005 MergeTypedefNameDecl(S, NewTD, Previous);
7006 } else {
7008 }
7009
7010 if (ShadowedDecl && !Redeclaration)
7011 CheckShadow(NewTD, ShadowedDecl, Previous);
7012
7013 // If this is the C FILE type, notify the AST context.
7014 if (IdentifierInfo *II = NewTD->getIdentifier())
7015 if (!NewTD->isInvalidDecl() &&
7017 switch (II->getNotableIdentifierID()) {
7018 case tok::NotableIdentifierKind::FILE:
7019 Context.setFILEDecl(NewTD);
7020 break;
7021 case tok::NotableIdentifierKind::jmp_buf:
7022 Context.setjmp_bufDecl(NewTD);
7023 break;
7024 case tok::NotableIdentifierKind::sigjmp_buf:
7025 Context.setsigjmp_bufDecl(NewTD);
7026 break;
7027 case tok::NotableIdentifierKind::ucontext_t:
7028 Context.setucontext_tDecl(NewTD);
7029 break;
7030 case tok::NotableIdentifierKind::float_t:
7031 case tok::NotableIdentifierKind::double_t:
7032 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
7033 break;
7034 default:
7035 break;
7036 }
7037 }
7038
7039 return NewTD;
7040}
7041
7042/// Determines whether the given declaration is an out-of-scope
7043/// previous declaration.
7044///
7045/// This routine should be invoked when name lookup has found a
7046/// previous declaration (PrevDecl) that is not in the scope where a
7047/// new declaration by the same name is being introduced. If the new
7048/// declaration occurs in a local scope, previous declarations with
7049/// linkage may still be considered previous declarations (C99
7050/// 6.2.2p4-5, C++ [basic.link]p6).
7051///
7052/// \param PrevDecl the previous declaration found by name
7053/// lookup
7054///
7055/// \param DC the context in which the new declaration is being
7056/// declared.
7057///
7058/// \returns true if PrevDecl is an out-of-scope previous declaration
7059/// for a new delcaration with the same name.
7060static bool
7062 ASTContext &Context) {
7063 if (!PrevDecl)
7064 return false;
7065
7066 if (!PrevDecl->hasLinkage())
7067 return false;
7068
7069 if (Context.getLangOpts().CPlusPlus) {
7070 // C++ [basic.link]p6:
7071 // If there is a visible declaration of an entity with linkage
7072 // having the same name and type, ignoring entities declared
7073 // outside the innermost enclosing namespace scope, the block
7074 // scope declaration declares that same entity and receives the
7075 // linkage of the previous declaration.
7076 DeclContext *OuterContext = DC->getRedeclContext();
7077 if (!OuterContext->isFunctionOrMethod())
7078 // This rule only applies to block-scope declarations.
7079 return false;
7080
7081 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7082 if (PrevOuterContext->isRecord())
7083 // We found a member function: ignore it.
7084 return false;
7085
7086 // Find the innermost enclosing namespace for the new and
7087 // previous declarations.
7088 OuterContext = OuterContext->getEnclosingNamespaceContext();
7089 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7090
7091 // The previous declaration is in a different namespace, so it
7092 // isn't the same function.
7093 if (!OuterContext->Equals(PrevOuterContext))
7094 return false;
7095 }
7096
7097 return true;
7098}
7099
7101 CXXScopeSpec &SS = D.getCXXScopeSpec();
7102 if (!SS.isSet()) return;
7104}
7105
7108 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7109 // __opencl_c_program_scope_global_variables feature, the address space
7110 // for a variable at program scope or a static or extern variable inside
7111 // a function are inferred to be __global.
7112 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7113 Var->hasGlobalStorage())
7114 ImplAS = LangAS::opencl_global;
7115 Var->assignAddressSpace(Context, ImplAS);
7116}
7117
7118static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7119 // 'weak' only applies to declarations with external linkage.
7120 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7121 if (!ND.isExternallyVisible()) {
7122 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7123 ND.dropAttr<WeakAttr>();
7124 }
7125 }
7126}
7127
7128static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7129 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7130 if (ND.isExternallyVisible()) {
7131 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7132 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7133 }
7134 }
7135}
7136
7137static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7138 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7139 if (VD->hasInit()) {
7140 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7141 assert(VD->isThisDeclarationADefinition() &&
7142 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7143 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7144 VD->dropAttr<AliasAttr>();
7145 }
7146 }
7147 }
7148}
7149
7150static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7151 // 'selectany' only applies to externally visible variable declarations.
7152 // It does not apply to functions.
7153 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7154 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7155 S.Diag(Attr->getLocation(),
7156 diag::err_attribute_selectany_non_extern_data);
7157 ND.dropAttr<SelectAnyAttr>();
7158 }
7159 }
7160}
7161
7163 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7164 if (!ND.isExternallyVisible())
7165 S.Diag(Attr->getLocation(),
7166 diag::warn_attribute_hybrid_patchable_non_extern);
7167 }
7168}
7169
7171 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7172 auto *VD = dyn_cast<VarDecl>(&ND);
7173 bool IsAnonymousNS = false;
7174 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7175 if (VD) {
7176 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7177 while (NS && !IsAnonymousNS) {
7178 IsAnonymousNS = NS->isAnonymousNamespace();
7179 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7180 }
7181 }
7182 // dll attributes require external linkage. Static locals may have external
7183 // linkage but still cannot be explicitly imported or exported.
7184 // In Microsoft mode, a variable defined in anonymous namespace must have
7185 // external linkage in order to be exported.
7186 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7187 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7188 (!AnonNSInMicrosoftMode &&
7189 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7190 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7191 << &ND << Attr;
7192 ND.setInvalidDecl();
7193 }
7194 }
7195}
7196
7198 // Check the attributes on the function type and function params, if any.
7199 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7200 FD = FD->getMostRecentDecl();
7201 // Don't declare this variable in the second operand of the for-statement;
7202 // GCC miscompiles that by ending its lifetime before evaluating the
7203 // third operand. See gcc.gnu.org/PR86769.
7205 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7206 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7207 TL = ATL.getModifiedLoc()) {
7208 // The [[lifetimebound]] attribute can be applied to the implicit object
7209 // parameter of a non-static member function (other than a ctor or dtor)
7210 // by applying it to the function type.
7211 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7212 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7213 int NoImplicitObjectError = -1;
7214 if (!MD)
7215 NoImplicitObjectError = 0;
7216 else if (MD->isStatic())
7217 NoImplicitObjectError = 1;
7218 else if (MD->isExplicitObjectMemberFunction())
7219 NoImplicitObjectError = 2;
7220 if (NoImplicitObjectError != -1) {
7221 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7222 << NoImplicitObjectError << A->getRange();
7223 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7224 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7225 << isa<CXXDestructorDecl>(MD) << A->getRange();
7226 } else if (MD->getReturnType()->isVoidType()) {
7227 S.Diag(
7228 MD->getLocation(),
7229 diag::
7230 err_lifetimebound_implicit_object_parameter_void_return_type);
7231 }
7232 }
7233 }
7234
7235 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7236 const ParmVarDecl *P = FD->getParamDecl(I);
7237
7238 // The [[lifetimebound]] attribute can be applied to a function parameter
7239 // only if the function returns a value.
7240 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7241 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7242 S.Diag(A->getLocation(),
7243 diag::err_lifetimebound_parameter_void_return_type);
7244 }
7245 }
7246 }
7247 }
7248}
7249
7251 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7252 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7253}
7254
7256 // Ensure that an auto decl is deduced otherwise the checks below might cache
7257 // the wrong linkage.
7258 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7259
7260 checkWeakAttr(S, ND);
7261 checkWeakRefAttr(S, ND);
7262 checkAliasAttr(S, ND);
7263 checkSelectAnyAttr(S, ND);
7265 checkInheritableAttr(S, ND);
7267}
7268
7270 NamedDecl *NewDecl,
7271 bool IsSpecialization,
7272 bool IsDefinition) {
7273 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7274 return;
7275
7276 bool IsTemplate = false;
7277 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7278 OldDecl = OldTD->getTemplatedDecl();
7279 IsTemplate = true;
7280 if (!IsSpecialization)
7281 IsDefinition = false;
7282 }
7283 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7284 NewDecl = NewTD->getTemplatedDecl();
7285 IsTemplate = true;
7286 }
7287
7288 if (!OldDecl || !NewDecl)
7289 return;
7290
7291 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7292 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7293 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7294 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7295
7296 // dllimport and dllexport are inheritable attributes so we have to exclude
7297 // inherited attribute instances.
7298 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7299 (NewExportAttr && !NewExportAttr->isInherited());
7300
7301 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7302 // the only exception being explicit specializations.
7303 // Implicitly generated declarations are also excluded for now because there
7304 // is no other way to switch these to use dllimport or dllexport.
7305 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7306
7307 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7308 // Allow with a warning for free functions and global variables.
7309 bool JustWarn = false;
7310 if (!OldDecl->isCXXClassMember()) {
7311 auto *VD = dyn_cast<VarDecl>(OldDecl);
7312 if (VD && !VD->getDescribedVarTemplate())
7313 JustWarn = true;
7314 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7315 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7316 JustWarn = true;
7317 }
7318
7319 // We cannot change a declaration that's been used because IR has already
7320 // been emitted. Dllimported functions will still work though (modulo
7321 // address equality) as they can use the thunk.
7322 if (OldDecl->isUsed())
7323 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7324 JustWarn = false;
7325
7326 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7327 : diag::err_attribute_dll_redeclaration;
7328 S.Diag(NewDecl->getLocation(), DiagID)
7329 << NewDecl
7330 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7331 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7332 if (!JustWarn) {
7333 NewDecl->setInvalidDecl();
7334 return;
7335 }
7336 }
7337
7338 // A redeclaration is not allowed to drop a dllimport attribute, the only
7339 // exceptions being inline function definitions (except for function
7340 // templates), local extern declarations, qualified friend declarations or
7341 // special MSVC extension: in the last case, the declaration is treated as if
7342 // it were marked dllexport.
7343 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7344 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7345 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7346 // Ignore static data because out-of-line definitions are diagnosed
7347 // separately.
7348 IsStaticDataMember = VD->isStaticDataMember();
7349 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7351 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7352 IsInline = FD->isInlined();
7353 IsQualifiedFriend = FD->getQualifier() &&
7354 FD->getFriendObjectKind() == Decl::FOK_Declared;
7355 }
7356
7357 if (OldImportAttr && !HasNewAttr &&
7358 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7359 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7360 if (IsMicrosoftABI && IsDefinition) {
7361 if (IsSpecialization) {
7362 S.Diag(
7363 NewDecl->getLocation(),
7364 diag::err_attribute_dllimport_function_specialization_definition);
7365 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7366 NewDecl->dropAttr<DLLImportAttr>();
7367 } else {
7368 S.Diag(NewDecl->getLocation(),
7369 diag::warn_redeclaration_without_import_attribute)
7370 << NewDecl;
7371 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7372 NewDecl->dropAttr<DLLImportAttr>();
7373 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7374 S.Context, NewImportAttr->getRange()));
7375 }
7376 } else if (IsMicrosoftABI && IsSpecialization) {
7377 assert(!IsDefinition);
7378 // MSVC allows this. Keep the inherited attribute.
7379 } else {
7380 S.Diag(NewDecl->getLocation(),
7381 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7382 << NewDecl << OldImportAttr;
7383 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7384 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7385 OldDecl->dropAttr<DLLImportAttr>();
7386 NewDecl->dropAttr<DLLImportAttr>();
7387 }
7388 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7389 // In MinGW, seeing a function declared inline drops the dllimport
7390 // attribute.
7391 OldDecl->dropAttr<DLLImportAttr>();
7392 NewDecl->dropAttr<DLLImportAttr>();
7393 S.Diag(NewDecl->getLocation(),
7394 diag::warn_dllimport_dropped_from_inline_function)
7395 << NewDecl << OldImportAttr;
7396 }
7397
7398 // A specialization of a class template member function is processed here
7399 // since it's a redeclaration. If the parent class is dllexport, the
7400 // specialization inherits that attribute. This doesn't happen automatically
7401 // since the parent class isn't instantiated until later.
7402 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7403 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7404 !NewImportAttr && !NewExportAttr) {
7405 if (const DLLExportAttr *ParentExportAttr =
7406 MD->getParent()->getAttr<DLLExportAttr>()) {
7407 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7408 NewAttr->setInherited(true);
7409 NewDecl->addAttr(NewAttr);
7410 }
7411 }
7412 }
7413}
7414
7415/// Given that we are within the definition of the given function,
7416/// will that definition behave like C99's 'inline', where the
7417/// definition is discarded except for optimization purposes?
7419 // Try to avoid calling GetGVALinkageForFunction.
7420
7421 // All cases of this require the 'inline' keyword.
7422 if (!FD->isInlined()) return false;
7423
7424 // This is only possible in C++ with the gnu_inline attribute.
7425 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7426 return false;
7427
7428 // Okay, go ahead and call the relatively-more-expensive function.
7430}
7431
7432/// Determine whether a variable is extern "C" prior to attaching
7433/// an initializer. We can't just call isExternC() here, because that
7434/// will also compute and cache whether the declaration is externally
7435/// visible, which might change when we attach the initializer.
7436///
7437/// This can only be used if the declaration is known to not be a
7438/// redeclaration of an internal linkage declaration.
7439///
7440/// For instance:
7441///
7442/// auto x = []{};
7443///
7444/// Attaching the initializer here makes this declaration not externally
7445/// visible, because its type has internal linkage.
7446///
7447/// FIXME: This is a hack.
7448template<typename T>
7449static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7450 if (S.getLangOpts().CPlusPlus) {
7451 // In C++, the overloadable attribute negates the effects of extern "C".
7452 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7453 return false;
7454
7455 // So do CUDA's host/device attributes.
7456 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7457 D->template hasAttr<CUDAHostAttr>()))
7458 return false;
7459 }
7460 return D->isExternC();
7461}
7462
7463static bool shouldConsiderLinkage(const VarDecl *VD) {
7464 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7467 return VD->hasExternalStorage();
7468 if (DC->isFileContext())
7469 return true;
7470 if (DC->isRecord())
7471 return false;
7472 if (DC->getDeclKind() == Decl::HLSLBuffer)
7473 return false;
7474
7476 return false;
7477 llvm_unreachable("Unexpected context");
7478}
7479
7480static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7481 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7482 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7484 return true;
7485 if (DC->isRecord() || isa<CXXExpansionStmtDecl>(DC))
7486 return false;
7487 llvm_unreachable("Unexpected context");
7488}
7489
7490static bool hasParsedAttr(Scope *S, const Declarator &PD,
7491 ParsedAttr::Kind Kind) {
7492 // Check decl attributes on the DeclSpec.
7493 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7494 return true;
7495
7496 // Walk the declarator structure, checking decl attributes that were in a type
7497 // position to the decl itself.
7498 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7499 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7500 return true;
7501 }
7502
7503 // Finally, check attributes on the decl itself.
7504 return PD.getAttributes().hasAttribute(Kind) ||
7506}
7507
7509 if (!DC->isFunctionOrMethod())
7510 return false;
7511
7512 // If this is a local extern function or variable declared within a function
7513 // template, don't add it into the enclosing namespace scope until it is
7514 // instantiated; it might have a dependent type right now.
7515 if (DC->isDependentContext())
7516 return true;
7517
7518 // C++11 [basic.link]p7:
7519 // When a block scope declaration of an entity with linkage is not found to
7520 // refer to some other declaration, then that entity is a member of the
7521 // innermost enclosing namespace.
7522 //
7523 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7524 // semantically-enclosing namespace, not a lexically-enclosing one.
7525 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7526 DC = DC->getParent();
7527 return true;
7528}
7529
7530/// Returns true if given declaration has external C language linkage.
7531static bool isDeclExternC(const Decl *D) {
7532 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7533 return FD->isExternC();
7534 if (const auto *VD = dyn_cast<VarDecl>(D))
7535 return VD->isExternC();
7536
7537 llvm_unreachable("Unknown type of decl!");
7538}
7539
7540/// Returns true if there hasn't been any invalid type diagnosed.
7541static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7542 DeclContext *DC = NewVD->getDeclContext();
7543 QualType R = NewVD->getType();
7544
7545 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7546 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7547 // argument.
7548 if (R->isImageType() || R->isPipeType()) {
7549 Se.Diag(NewVD->getLocation(),
7550 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7551 << R;
7552 NewVD->setInvalidDecl();
7553 return false;
7554 }
7555
7556 // OpenCL v1.2 s6.9.r:
7557 // The event type cannot be used to declare a program scope variable.
7558 // OpenCL v2.0 s6.9.q:
7559 // The clk_event_t and reserve_id_t types cannot be declared in program
7560 // scope.
7561 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7562 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7563 Se.Diag(NewVD->getLocation(),
7564 diag::err_invalid_type_for_program_scope_var)
7565 << R;
7566 NewVD->setInvalidDecl();
7567 return false;
7568 }
7569 }
7570
7571 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7572 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7573 Se.getLangOpts())) {
7574 QualType NR = R.getCanonicalType();
7575 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7576 NR->isReferenceType()) {
7579 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7580 << NR->isReferenceType();
7581 NewVD->setInvalidDecl();
7582 return false;
7583 }
7584 NR = NR->getPointeeType();
7585 }
7586 }
7587
7588 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7589 Se.getLangOpts())) {
7590 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7591 // half array type (unless the cl_khr_fp16 extension is enabled).
7592 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7593 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7594 NewVD->setInvalidDecl();
7595 return false;
7596 }
7597 }
7598
7599 // OpenCL v1.2 s6.9.r:
7600 // The event type cannot be used with the __local, __constant and __global
7601 // address space qualifiers.
7602 if (R->isEventT()) {
7603 if (R.getAddressSpace() != LangAS::opencl_private) {
7604 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7605 NewVD->setInvalidDecl();
7606 return false;
7607 }
7608 }
7609
7610 if (R->isSamplerT()) {
7611 // OpenCL v1.2 s6.9.b p4:
7612 // The sampler type cannot be used with the __local and __global address
7613 // space qualifiers.
7614 if (R.getAddressSpace() == LangAS::opencl_local ||
7615 R.getAddressSpace() == LangAS::opencl_global) {
7616 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7617 NewVD->setInvalidDecl();
7618 }
7619
7620 // OpenCL v1.2 s6.12.14.1:
7621 // A global sampler must be declared with either the constant address
7622 // space qualifier or with the const qualifier.
7623 if (DC->isTranslationUnit() &&
7624 !(R.getAddressSpace() == LangAS::opencl_constant ||
7625 R.isConstQualified())) {
7626 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7627 NewVD->setInvalidDecl();
7628 }
7629 if (NewVD->isInvalidDecl())
7630 return false;
7631 }
7632
7633 return true;
7634}
7635
7636template <typename AttrTy>
7637static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7638 const TypedefNameDecl *TND = TT->getDecl();
7639 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7640 AttrTy *Clone = Attribute->clone(S.Context);
7641 Clone->setInherited(true);
7642 D->addAttr(Clone);
7643 }
7644}
7645
7646// This function emits warning and a corresponding note based on the
7647// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7648// declarations of an annotated type must be const qualified.
7650 QualType VarType = VD->getType().getCanonicalType();
7651
7652 // Ignore local declarations (for now) and those with const qualification.
7653 // TODO: Local variables should not be allowed if their type declaration has
7654 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7655 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7656 return;
7657
7658 if (VarType->isArrayType()) {
7659 // Retrieve element type for array declarations.
7660 VarType = S.getASTContext().getBaseElementType(VarType);
7661 }
7662
7663 const RecordDecl *RD = VarType->getAsRecordDecl();
7664
7665 // Check if the record declaration is present and if it has any attributes.
7666 if (RD == nullptr)
7667 return;
7668
7669 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7670 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7671 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7672 return;
7673 }
7674}
7675
7677 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7678 "NewD is not a function or variable");
7679
7680 if (PendingExportedNames.empty())
7681 return;
7682 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(NewD)) {
7683 if (getLangOpts().CPlusPlus && !FD->isExternC())
7684 return;
7685 }
7686 IdentifierInfo *IdentName = NewD->getIdentifier();
7687 if (IdentName == nullptr)
7688 return;
7689 auto PendingName = PendingExportedNames.find(IdentName);
7690 if (PendingName != PendingExportedNames.end()) {
7691 auto &Label = PendingName->second;
7692 if (!Label.Used) {
7693 Label.Used = true;
7694 if (NewD->hasExternalFormalLinkage())
7695 mergeVisibilityType(NewD, Label.NameLoc, VisibilityAttr::Default);
7696 else
7697 Diag(Label.NameLoc, diag::warn_pragma_not_applied) << "export" << NewD;
7698 }
7699 }
7700}
7701
7702// Checks if VD is declared at global scope or with C language linkage.
7703static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7704 return Name.getAsIdentifierInfo() &&
7705 Name.getAsIdentifierInfo()->isStr("main") &&
7706 !VD->getDescribedVarTemplate() &&
7707 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7708 VD->isExternC());
7709}
7710
7711void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7712 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7713
7714 // Quickly return if the function does not have an `asm` attribute.
7715 if (E == nullptr)
7716 return;
7717
7718 // The parser guarantees this is a string.
7719 StringLiteral *SE = cast<StringLiteral>(E);
7720 StringRef Label = SE->getString();
7721 QualType R = TInfo->getType();
7722 if (S->getFnParent() != nullptr) {
7723 switch (SC) {
7724 case SC_None:
7725 case SC_Auto:
7726 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7727 break;
7728 case SC_Register:
7729 // Local Named register
7730 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7732 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7733 break;
7734 case SC_Static:
7735 case SC_Extern:
7736 case SC_PrivateExtern:
7737 break;
7738 }
7739 } else if (SC == SC_Register) {
7740 // Global Named register
7741 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7742 const auto &TI = Context.getTargetInfo();
7743 bool HasSizeMismatch;
7744
7745 if (!TI.isValidGCCRegisterName(Label))
7746 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7747 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7748 HasSizeMismatch))
7749 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7750 else if (HasSizeMismatch)
7751 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7752 }
7753
7754 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7755 Diag(TInfo->getTypeLoc().getBeginLoc(),
7756 diag::err_asm_unsupported_register_type)
7757 << TInfo->getTypeLoc().getSourceRange();
7758 NewVD->setInvalidDecl(true);
7759 }
7760 }
7761}
7762
7764 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7765 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7766 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7767 QualType R = TInfo->getType();
7769
7771 bool IsPlaceholderVariable = false;
7772
7773 if (D.isDecompositionDeclarator()) {
7774 // Take the name of the first declarator as our name for diagnostic
7775 // purposes.
7776 auto &Decomp = D.getDecompositionDeclarator();
7777 if (!Decomp.bindings().empty()) {
7778 II = Decomp.bindings()[0].Name;
7779 Name = II;
7780 }
7781 } else if (!II) {
7782 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7783 return nullptr;
7784 }
7785
7786
7789 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7790 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7791
7792 IsPlaceholderVariable = true;
7793
7794 if (!Previous.empty()) {
7795 NamedDecl *PrevDecl = *Previous.begin();
7796 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7797 DC->getRedeclContext());
7798 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7799 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7800 if (IsPlaceholderVariable)
7802 }
7803 }
7804 }
7805
7806 // dllimport globals without explicit storage class are treated as extern. We
7807 // have to change the storage class this early to get the right DeclContext.
7808 if (SC == SC_None && !DC->isRecord() &&
7809 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7810 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7811 SC = SC_Extern;
7812
7813 DeclContext *OriginalDC = DC;
7814 bool IsLocalExternDecl = SC == SC_Extern &&
7816
7817 if (SCSpec == DeclSpec::SCS_mutable) {
7818 // mutable can only appear on non-static class members, so it's always
7819 // an error here
7820 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7821 D.setInvalidType();
7822 SC = SC_None;
7823 }
7824
7825 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7826 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7828 // In C++11, the 'register' storage class specifier is deprecated.
7829 // Suppress the warning in system macros, it's used in macros in some
7830 // popular C system headers, such as in glibc's htonl() macro.
7832 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7833 : diag::warn_deprecated_register)
7835 }
7836
7838
7839 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7840 // C99 6.9p2: The storage-class specifiers auto and register shall not
7841 // appear in the declaration specifiers in an external declaration.
7842 // Global Register+Asm is a GNU extension we support.
7843 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7844 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7845 D.setInvalidType();
7846 }
7847 }
7848
7849 // If this variable has a VLA type and an initializer, try to
7850 // fold to a constant-sized type. This is otherwise invalid.
7851 if (D.hasInitializer() && R->isVariableArrayType())
7853 /*DiagID=*/0);
7854
7855 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7856 const AutoType *AT = TL.getTypePtr();
7857 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7858 }
7859
7860 bool IsMemberSpecialization = false;
7861 bool IsVariableTemplateSpecialization = false;
7862 bool IsPartialSpecialization = false;
7863 bool IsVariableTemplate = false;
7864 VarDecl *NewVD = nullptr;
7865 VarTemplateDecl *NewTemplate = nullptr;
7866 TemplateParameterList *TemplateParams = nullptr;
7867 if (!getLangOpts().CPlusPlus) {
7869 II, R, TInfo, SC);
7870
7871 if (R->getContainedDeducedType())
7872 ParsingInitForAutoVars.insert(NewVD);
7873
7874 if (D.isInvalidType())
7875 NewVD->setInvalidDecl();
7876
7878 NewVD->hasLocalStorage())
7879 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7881 } else {
7882 bool Invalid = false;
7883 // Match up the template parameter lists with the scope specifier, then
7884 // determine whether we have a template or a template specialization.
7887 D.getCXXScopeSpec(),
7889 ? D.getName().TemplateId
7890 : nullptr,
7891 TemplateParamLists,
7892 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7893
7894 if (TemplateParams) {
7895 if (DC->isDependentContext()) {
7896 ContextRAII SavedContext(*this, DC);
7898 Invalid = true;
7899 }
7900
7901 if (!TemplateParams->size() &&
7903 // There is an extraneous 'template<>' for this variable. Complain
7904 // about it, but allow the declaration of the variable.
7905 Diag(TemplateParams->getTemplateLoc(),
7906 diag::err_template_variable_noparams)
7907 << II
7908 << SourceRange(TemplateParams->getTemplateLoc(),
7909 TemplateParams->getRAngleLoc());
7910 TemplateParams = nullptr;
7911 } else {
7912 // Check that we can declare a template here.
7913 if (CheckTemplateDeclScope(S, TemplateParams))
7914 return nullptr;
7915
7917 // This is an explicit specialization or a partial specialization.
7918 IsVariableTemplateSpecialization = true;
7919 IsPartialSpecialization = TemplateParams->size() > 0;
7920 } else { // if (TemplateParams->size() > 0)
7921 // This is a template declaration.
7922 IsVariableTemplate = true;
7923
7924 // Only C++1y supports variable templates (N3651).
7925 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7926 }
7927 }
7928 } else {
7929 // Check that we can declare a member specialization here.
7930 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7931 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7932 return nullptr;
7933 assert((Invalid ||
7935 "should have a 'template<>' for this decl");
7936 }
7937
7938 bool IsExplicitSpecialization =
7939 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7940
7941 // C++ [temp.expl.spec]p2:
7942 // The declaration in an explicit-specialization shall not be an
7943 // export-declaration. An explicit specialization shall not use a
7944 // storage-class-specifier other than thread_local.
7945 //
7946 // We use the storage-class-specifier from DeclSpec because we may have
7947 // added implicit 'extern' for declarations with __declspec(dllimport)!
7948 if (SCSpec != DeclSpec::SCS_unspecified &&
7949 (IsExplicitSpecialization || IsMemberSpecialization)) {
7951 diag::ext_explicit_specialization_storage_class)
7953 }
7954
7955 if (CurContext->isRecord()) {
7956 if (SC == SC_Static) {
7957 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7958 // Walk up the enclosing DeclContexts to check for any that are
7959 // incompatible with static data members.
7960 const DeclContext *FunctionOrMethod = nullptr;
7961 const CXXRecordDecl *AnonStruct = nullptr;
7962 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7963 if (Ctxt->isFunctionOrMethod()) {
7964 FunctionOrMethod = Ctxt;
7965 break;
7966 }
7967 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7968 if (ParentDecl && !ParentDecl->getDeclName()) {
7969 AnonStruct = ParentDecl;
7970 break;
7971 }
7972 }
7973 if (FunctionOrMethod) {
7974 // C++ [class.static.data]p5: A local class shall not have static
7975 // data members.
7977 diag::err_static_data_member_not_allowed_in_local_class)
7978 << Name << RD->getDeclName() << RD->getTagKind();
7979 Invalid = true;
7980 } else if (AnonStruct) {
7981 // C++ [class.static.data]p4: Unnamed classes and classes contained
7982 // directly or indirectly within unnamed classes shall not contain
7983 // static data members.
7985 diag::err_static_data_member_not_allowed_in_anon_struct)
7986 << Name << AnonStruct->getTagKind();
7987 Invalid = true;
7988 } else if (RD->isUnion()) {
7989 // C++98 [class.union]p1: If a union contains a static data member,
7990 // the program is ill-formed. C++11 drops this restriction.
7992 diag_compat::static_data_member_in_union)
7993 << Name;
7994 }
7995 }
7996 } else if (IsVariableTemplate || IsPartialSpecialization) {
7997 // There is no such thing as a member field template.
7998 Diag(D.getIdentifierLoc(), diag::err_template_member)
7999 << II << TemplateParams->getSourceRange();
8000 // Recover by pretending this is a static data member template.
8001 SC = SC_Static;
8002 }
8003 } else if (DC->isRecord()) {
8004 // This is an out-of-line definition of a static data member.
8005 switch (SC) {
8006 case SC_None:
8007 break;
8008 case SC_Static:
8010 diag::err_static_out_of_line)
8013 break;
8014 case SC_Auto:
8015 case SC_Register:
8016 case SC_Extern:
8017 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8018 // to names of variables declared in a block or to function parameters.
8019 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8020 // of class members
8021
8023 diag::err_storage_class_for_static_member)
8026 break;
8027 case SC_PrivateExtern:
8028 llvm_unreachable("C storage class in c++!");
8029 }
8030 }
8031
8032 if (IsVariableTemplateSpecialization) {
8033 SourceLocation TemplateKWLoc =
8034 TemplateParamLists.size() > 0
8035 ? TemplateParamLists[0]->getTemplateLoc()
8036 : SourceLocation();
8038 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8040 if (Res.isInvalid())
8041 return nullptr;
8042 NewVD = cast<VarDecl>(Res.get());
8043 AddToScope = false;
8044 } else if (D.isDecompositionDeclarator()) {
8046 D.getIdentifierLoc(), D.getEndLoc(), R,
8047 TInfo, SC, Bindings);
8048 } else
8049 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
8050 D.getIdentifierLoc(), II, R, TInfo, SC);
8051
8052 // If this is supposed to be a variable template, create it as such.
8053 if (IsVariableTemplate) {
8054 NewTemplate =
8056 TemplateParams, NewVD);
8057 NewVD->setDescribedVarTemplate(NewTemplate);
8058 }
8059
8060 // If this decl has an auto type in need of deduction, make a note of the
8061 // Decl so we can diagnose uses of it in its own initializer.
8062 if (R->getContainedDeducedType())
8063 ParsingInitForAutoVars.insert(NewVD);
8064
8065 if (D.isInvalidType() || Invalid) {
8066 NewVD->setInvalidDecl();
8067 if (NewTemplate)
8068 NewTemplate->setInvalidDecl();
8069 }
8070
8071 SetNestedNameSpecifier(*this, NewVD, D);
8072
8073 // If we have any template parameter lists that don't directly belong to
8074 // the variable (matching the scope specifier), store them.
8075 // An explicit variable template specialization does not own any template
8076 // parameter lists.
8077 unsigned VDTemplateParamLists =
8078 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8079 if (TemplateParamLists.size() > VDTemplateParamLists)
8081 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8082 }
8083
8084 if (D.getDeclSpec().isInlineSpecified()) {
8085 if (!getLangOpts().CPlusPlus) {
8086 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8087 << 0;
8088 } else if (CurContext->isFunctionOrMethod()) {
8089 // 'inline' is not allowed on block scope variable declaration.
8091 diag::err_inline_declaration_block_scope) << Name
8093 } else {
8095 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8096 : diag::compat_pre_cxx17_inline_variable);
8097 NewVD->setInlineSpecified();
8098 }
8099 }
8100
8101 // Set the lexical context. If the declarator has a C++ scope specifier, the
8102 // lexical context will be different from the semantic context.
8104 if (NewTemplate)
8105 NewTemplate->setLexicalDeclContext(CurContext);
8106
8107 if (IsLocalExternDecl) {
8109 for (auto *B : Bindings)
8110 B->setLocalExternDecl();
8111 else
8112 NewVD->setLocalExternDecl();
8113 }
8114
8115 bool EmitTLSUnsupportedError = false;
8117 // C++11 [dcl.stc]p4:
8118 // When thread_local is applied to a variable of block scope the
8119 // storage-class-specifier static is implied if it does not appear
8120 // explicitly.
8121 // Core issue: 'static' is not implied if the variable is declared
8122 // 'extern'.
8123 if (NewVD->hasLocalStorage() &&
8124 (SCSpec != DeclSpec::SCS_unspecified ||
8126 !DC->isFunctionOrMethod()))
8128 diag::err_thread_non_global)
8130 else if (!Context.getTargetInfo().isTLSSupported()) {
8131 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8132 // Postpone error emission until we've collected attributes required to
8133 // figure out whether it's a host or device variable and whether the
8134 // error should be ignored.
8135 EmitTLSUnsupportedError = true;
8136 // We still need to mark the variable as TLS so it shows up in AST with
8137 // proper storage class for other tools to use even if we're not going
8138 // to emit any code for it.
8139 NewVD->setTSCSpec(TSCS);
8140 } else
8142 diag::err_thread_unsupported);
8143 } else
8144 NewVD->setTSCSpec(TSCS);
8145 }
8146
8147 switch (D.getDeclSpec().getConstexprSpecifier()) {
8149 break;
8150
8153 diag::err_constexpr_wrong_decl_kind)
8154 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8155 [[fallthrough]];
8156
8158 NewVD->setConstexpr(true);
8159 // C++1z [dcl.spec.constexpr]p1:
8160 // A static data member declared with the constexpr specifier is
8161 // implicitly an inline variable.
8162 if (NewVD->isStaticDataMember() &&
8164 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8165 NewVD->setImplicitlyInline();
8166 break;
8167
8169 if (!NewVD->hasGlobalStorage())
8171 diag::err_constinit_local_variable);
8172 else
8173 NewVD->addAttr(
8174 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8175 ConstInitAttr::Keyword_constinit));
8176 break;
8177 }
8178
8179 // C99 6.7.4p3
8180 // An inline definition of a function with external linkage shall
8181 // not contain a definition of a modifiable object with static or
8182 // thread storage duration...
8183 // We only apply this when the function is required to be defined
8184 // elsewhere, i.e. when the function is not 'extern inline'. Note
8185 // that a local variable with thread storage duration still has to
8186 // be marked 'static'. Also note that it's possible to get these
8187 // semantics in C++ using __attribute__((gnu_inline)).
8188 if (SC == SC_Static && S->getFnParent() != nullptr &&
8189 !NewVD->getType().isConstQualified()) {
8191 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8193 diag::warn_static_local_in_extern_inline);
8195 }
8196 }
8197
8199 if (IsVariableTemplateSpecialization)
8200 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8201 << (IsPartialSpecialization ? 1 : 0)
8204 else if (IsMemberSpecialization)
8205 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8206 << 2
8208 else if (NewVD->hasLocalStorage())
8209 Diag(NewVD->getLocation(), diag::err_module_private_local)
8210 << 0 << NewVD
8214 else {
8215 NewVD->setModulePrivate();
8216 if (NewTemplate)
8217 NewTemplate->setModulePrivate();
8218 for (auto *B : Bindings)
8219 B->setModulePrivate();
8220 }
8221 }
8222
8223 if (getLangOpts().OpenCL) {
8225
8227 if (TSC != TSCS_unspecified) {
8229 diag::err_opencl_unknown_type_specifier)
8231 << DeclSpec::getSpecifierName(TSC) << 1;
8232 NewVD->setInvalidDecl();
8233 }
8234 }
8235
8236 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8237 // address space if the table has local storage (semantic checks elsewhere
8238 // will produce an error anyway).
8239 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8240 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8241 !NewVD->hasLocalStorage()) {
8242 QualType Type = Context.getAddrSpaceQualType(
8243 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8244 NewVD->setType(Type);
8245 }
8246 }
8247
8249
8250 if (Expr *E = D.getAsmLabel()) {
8251 // The parser guarantees this is a string.
8253 StringRef Label = SE->getString();
8254
8255 // Insert the asm attribute.
8256 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8257 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8258 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8260 if (I != ExtnameUndeclaredIdentifiers.end()) {
8261 if (isDeclExternC(NewVD)) {
8262 NewVD->addAttr(I->second);
8264 } else if (NewVD->getDeclContext()
8267 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8268 << /*Variable*/ 1 << NewVD;
8269 }
8270 }
8271
8272 // Handle attributes prior to checking for duplicates in MergeVarDecl
8273 ProcessDeclAttributes(S, NewVD, D);
8274
8275 if (getLangOpts().HLSL)
8277
8278 if (getLangOpts().OpenACC)
8280
8281 // FIXME: This is probably the wrong location to be doing this and we should
8282 // probably be doing this for more attributes (especially for function
8283 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8284 // the code to copy attributes would be generated by TableGen.
8285 if (R->isFunctionPointerType())
8286 if (const auto *TT = R->getAs<TypedefType>())
8288
8289 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8290 if (EmitTLSUnsupportedError &&
8292 (getLangOpts().OpenMPIsTargetDevice &&
8293 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8295 diag::err_thread_unsupported);
8296
8297 if (EmitTLSUnsupportedError &&
8298 (LangOpts.SYCLIsDevice ||
8299 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8300 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8301 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8302 // storage [duration]."
8303 if (SC == SC_None && S->getFnParent() != nullptr &&
8304 (NewVD->hasAttr<CUDASharedAttr>() ||
8305 NewVD->hasAttr<CUDAConstantAttr>())) {
8306 NewVD->setStorageClass(SC_Static);
8307 }
8308 }
8309
8310 // Ensure that dllimport globals without explicit storage class are treated as
8311 // extern. The storage class is set above using parsed attributes. Now we can
8312 // check the VarDecl itself.
8313 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8314 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8315 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8316
8317 // In auto-retain/release, infer strong retension for variables of
8318 // retainable type.
8319 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8320 NewVD->setInvalidDecl();
8321
8322 // Check the ASM label here, as we need to know all other attributes of the
8323 // Decl first. Otherwise, we can't know if the asm label refers to the
8324 // host or device in a CUDA context. The device has other registers than
8325 // host and we must know where the function will be placed.
8326 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8327
8328 // Find the shadowed declaration before filtering for scope.
8329 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8331 : nullptr;
8332
8333 // Don't consider existing declarations that are in a different
8334 // scope and are out-of-semantic-context declarations (if the new
8335 // declaration has linkage).
8338 IsMemberSpecialization ||
8339 IsVariableTemplateSpecialization);
8340
8341 // Check whether the previous declaration is in the same block scope. This
8342 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8343 if (getLangOpts().CPlusPlus &&
8344 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8346 Previous.isSingleResult() && !Previous.isShadowed() &&
8347 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8348
8349 if (!getLangOpts().CPlusPlus) {
8351 } else {
8352 // If this is an explicit specialization of a static data member, check it.
8353 if (IsMemberSpecialization && !IsVariableTemplate &&
8354 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8356 NewVD->setInvalidDecl();
8357
8358 // Merge the decl with the existing one if appropriate.
8359 if (!Previous.empty()) {
8360 if (Previous.isSingleResult() &&
8361 isa<FieldDecl>(Previous.getFoundDecl()) &&
8362 D.getCXXScopeSpec().isSet()) {
8363 // The user tried to define a non-static data member
8364 // out-of-line (C++ [dcl.meaning]p1).
8365 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8366 << D.getCXXScopeSpec().getRange();
8367 Previous.clear();
8368 NewVD->setInvalidDecl();
8369 }
8370 } else if (D.getCXXScopeSpec().isSet() &&
8371 !IsVariableTemplateSpecialization) {
8372 // No previous declaration in the qualifying scope.
8373 Diag(D.getIdentifierLoc(), diag::err_no_member)
8374 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8375 << D.getCXXScopeSpec().getRange();
8376 NewVD->setInvalidDecl();
8377
8378 // if this is a member specialization, we don't have any primary template
8379 // to be instantiated from. We set ourselves to a 'fake' clone of this so
8380 // that anything that attempts to refer to this invalid declaration can
8381 // act as if there IS a primary instantiation.
8382 if (NewTemplate && IsMemberSpecialization) {
8383 VarDecl *FakeVD =
8385 II, R, TInfo, SC);
8386 FakeVD->setInvalidDecl();
8387 VarTemplateDecl *FakeInstantiatedFrom = VarTemplateDecl::Create(
8388 Context, DC, D.getIdentifierLoc(), Name, TemplateParams, FakeVD);
8389 FakeInstantiatedFrom->setInvalidDecl();
8390 NewTemplate->setInstantiatedFromMemberTemplate(FakeInstantiatedFrom);
8391 }
8392 }
8393
8394 if (!IsPlaceholderVariable)
8396
8397 // CheckVariableDeclaration will set NewVD as invalid if something is in
8398 // error like WebAssembly tables being declared as arrays with a non-zero
8399 // size, but then parsing continues and emits further errors on that line.
8400 // To avoid that we check here if it happened and return nullptr.
8401 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8402 return nullptr;
8403
8404 if (NewTemplate) {
8405 VarTemplateDecl *PrevVarTemplate =
8406 NewVD->getPreviousDecl()
8408 : nullptr;
8409
8410 // Check the template parameter list of this declaration, possibly
8411 // merging in the template parameter list from the previous variable
8412 // template declaration.
8414 TemplateParams,
8415 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8416 : nullptr,
8417 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8418 DC->isDependentContext())
8420 : TPC_Other))
8421 NewVD->setInvalidDecl();
8422 }
8423 }
8424
8425 if (IsMemberSpecialization) {
8426 if (NewTemplate && NewVD->getPreviousDecl()) {
8427 NewTemplate->setMemberSpecialization();
8428 } else if (IsPartialSpecialization) {
8430 ->setMemberSpecialization();
8431 }
8432 }
8433
8434 // Diagnose shadowed variables iff this isn't a redeclaration.
8435 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8436 CheckShadow(NewVD, ShadowedDecl, Previous);
8437
8438 ProcessPragmaWeak(S, NewVD);
8439 ProcessPragmaExport(NewVD);
8440
8441 // If this is the first declaration of an extern C variable, update
8442 // the map of such variables.
8443 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8444 isIncompleteDeclExternC(*this, NewVD))
8446
8447 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8449 Decl *ManglingContextDecl;
8450 std::tie(MCtx, ManglingContextDecl) =
8452 if (MCtx) {
8453 Context.setManglingNumber(
8454 NewVD, MCtx->getManglingNumber(
8455 NewVD, getMSManglingNumber(getLangOpts(), S)));
8456 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8457 }
8458 }
8459
8460 // Special handling of variable named 'main'.
8461 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8462 // C++ [basic.start.main]p3:
8463 // A program that declares
8464 // - a variable main at global scope, or
8465 // - an entity named main with C language linkage (in any namespace)
8466 // is ill-formed
8467 if (getLangOpts().CPlusPlus)
8468 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8469 << NewVD->isExternC();
8470
8471 // In C, and external-linkage variable named main results in undefined
8472 // behavior.
8473 else if (NewVD->hasExternalFormalLinkage())
8474 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8475 }
8476
8477 if (D.isRedeclaration() && !Previous.empty()) {
8478 NamedDecl *Prev = Previous.getRepresentativeDecl();
8479 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8481 }
8482
8483 if (NewTemplate) {
8484 if (NewVD->isInvalidDecl())
8485 NewTemplate->setInvalidDecl();
8486 ActOnDocumentableDecl(NewTemplate);
8487 return NewTemplate;
8488 }
8489
8490 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8492
8494
8495 return NewVD;
8496}
8497
8498/// Enum describing the %select options in diag::warn_decl_shadow.
8508
8509/// Determine what kind of declaration we're shadowing.
8511 const DeclContext *OldDC) {
8512 if (isa<TypeAliasDecl>(ShadowedDecl))
8513 return SDK_Using;
8514 else if (isa<TypedefDecl>(ShadowedDecl))
8515 return SDK_Typedef;
8516 else if (isa<BindingDecl>(ShadowedDecl))
8517 return SDK_StructuredBinding;
8518 else if (isa<RecordDecl>(OldDC))
8519 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8520
8521 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8522}
8523
8524/// Return the location of the capture if the given lambda captures the given
8525/// variable \p VD, or an invalid source location otherwise.
8527 const ValueDecl *VD) {
8528 for (const Capture &Capture : LSI->Captures) {
8530 return Capture.getLocation();
8531 }
8532 return SourceLocation();
8533}
8534
8536 const LookupResult &R) {
8537 // Only diagnose if we're shadowing an unambiguous field or variable.
8538 if (R.getResultKind() != LookupResultKind::Found)
8539 return false;
8540
8541 // Return false if warning is ignored.
8542 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8543}
8544
8546 const LookupResult &R) {
8548 return nullptr;
8549
8550 // Don't diagnose declarations at file scope.
8551 if (D->hasGlobalStorage() && !D->isStaticLocal())
8552 return nullptr;
8553
8554 NamedDecl *ShadowedDecl = R.getFoundDecl();
8555 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8556 : nullptr;
8557}
8558
8560 const LookupResult &R) {
8561 // Don't warn if typedef declaration is part of a class
8562 if (D->getDeclContext()->isRecord())
8563 return nullptr;
8564
8566 return nullptr;
8567
8568 NamedDecl *ShadowedDecl = R.getFoundDecl();
8569 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8570}
8571
8573 const LookupResult &R) {
8575 return nullptr;
8576
8577 NamedDecl *ShadowedDecl = R.getFoundDecl();
8578 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8579 : nullptr;
8580}
8581
8583 const LookupResult &R) {
8584 DeclContext *NewDC = D->getDeclContext();
8585
8586 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8587 if (const auto *MD =
8588 dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) {
8589 // Fields aren't shadowed in C++ static members or in member functions
8590 // with an explicit object parameter.
8591 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8592 return;
8593 }
8594 // Fields shadowed by constructor parameters are a special case. Usually
8595 // the constructor initializes the field with the parameter.
8596 if (isa<CXXConstructorDecl>(NewDC))
8597 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8598 // Remember that this was shadowed so we can either warn about its
8599 // modification or its existence depending on warning settings.
8600 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8601 return;
8602 }
8603 }
8604
8605 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8606 if (shadowedVar->isExternC()) {
8607 // For shadowing external vars, make sure that we point to the global
8608 // declaration, not a locally scoped extern declaration.
8609 for (auto *I : shadowedVar->redecls())
8610 if (I->isFileVarDecl()) {
8611 ShadowedDecl = I;
8612 break;
8613 }
8614 }
8615
8616 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8617
8618 unsigned WarningDiag = diag::warn_decl_shadow;
8619 SourceLocation CaptureLoc;
8620 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8621 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8622 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8623 // Handle both VarDecl and BindingDecl in lambda contexts
8624 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8625 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8626 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8627 if (RD->getLambdaCaptureDefault() == LCD_None) {
8628 // Try to avoid warnings for lambdas with an explicit capture
8629 // list. Warn only when the lambda captures the shadowed decl
8630 // explicitly.
8631 CaptureLoc = getCaptureLocation(LSI, VD);
8632 if (CaptureLoc.isInvalid())
8633 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8634 } else {
8635 // Remember that this was shadowed so we can avoid the warning if
8636 // the shadowed decl isn't captured and the warning settings allow
8637 // it.
8639 ->ShadowingDecls.push_back({D, VD});
8640 return;
8641 }
8642 }
8643 if (isa<FieldDecl>(ShadowedDecl)) {
8644 // If lambda can capture this, then emit default shadowing warning,
8645 // Otherwise it is not really a shadowing case since field is not
8646 // available in lambda's body.
8647 // At this point we don't know that lambda can capture this, so
8648 // remember that this was shadowed and delay until we know.
8650 ->ShadowingDecls.push_back({D, ShadowedDecl});
8651 return;
8652 }
8653 }
8654 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8655 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8656 bool HasLocalStorage = false;
8657 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8658 HasLocalStorage = VD->hasLocalStorage();
8659 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8660 HasLocalStorage =
8661 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8662
8663 if (HasLocalStorage) {
8664 // A variable can't shadow a local variable or binding in an enclosing
8665 // scope, if they are separated by a non-capturing declaration
8666 // context.
8667 for (DeclContext *ParentDC = NewDC;
8668 ParentDC && !ParentDC->Equals(OldDC);
8669 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8670 // Only block literals, captured statements, and lambda expressions
8671 // can capture; other scopes don't.
8672 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8673 !isLambdaCallOperator(ParentDC))
8674 return;
8675 }
8676 }
8677 }
8678 }
8679 }
8680
8681 // Never warn about shadowing a placeholder variable.
8682 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8683 return;
8684
8685 // Only warn about certain kinds of shadowing for class members.
8686 if (NewDC) {
8687 // In particular, don't warn about shadowing non-class members.
8688 if (NewDC->isRecord() && !OldDC->isRecord())
8689 return;
8690
8691 // Skip shadowing check if we're in a class scope, dealing with an enum
8692 // constant in a different context.
8693 DeclContext *ReDC = NewDC->getRedeclContext();
8694 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8695 return;
8696
8697 // TODO: should we warn about static data members shadowing
8698 // static data members from base classes?
8699
8700 // TODO: don't diagnose for inaccessible shadowed members.
8701 // This is hard to do perfectly because we might friend the
8702 // shadowing context, but that's just a false negative.
8703 }
8704
8705 DeclarationName Name = R.getLookupName();
8706
8707 // Emit warning and note.
8708 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8709 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8710 if (!CaptureLoc.isInvalid())
8711 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8712 << Name << /*explicitly*/ 1;
8713 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8714}
8715
8717 for (const auto &Shadow : LSI->ShadowingDecls) {
8718 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8719 // Try to avoid the warning when the shadowed decl isn't captured.
8720 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8721 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8722 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8723 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8724 Diag(Shadow.VD->getLocation(),
8725 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8726 : diag::warn_decl_shadow)
8727 << Shadow.VD->getDeclName()
8728 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8729 if (CaptureLoc.isValid())
8730 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8731 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8732 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8733 } else if (isa<FieldDecl>(ShadowedDecl)) {
8734 Diag(Shadow.VD->getLocation(),
8735 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8736 : diag::warn_decl_shadow_uncaptured_local)
8737 << Shadow.VD->getDeclName()
8738 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8739 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8740 }
8741 }
8742}
8743
8745 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8746 return;
8747
8748 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8751 LookupName(R, S);
8752 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8753 CheckShadow(D, ShadowedDecl, R);
8754}
8755
8756/// Check if 'E', which is an expression that is about to be modified, refers
8757/// to a constructor parameter that shadows a field.
8759 // Quickly ignore expressions that can't be shadowing ctor parameters.
8760 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8761 return;
8762 E = E->IgnoreParenImpCasts();
8763 auto *DRE = dyn_cast<DeclRefExpr>(E);
8764 if (!DRE)
8765 return;
8766 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8767 auto I = ShadowingDecls.find(D);
8768 if (I == ShadowingDecls.end())
8769 return;
8770 const NamedDecl *ShadowedDecl = I->second;
8771 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8772 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8773 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8774 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8775
8776 // Avoid issuing multiple warnings about the same decl.
8777 ShadowingDecls.erase(I);
8778}
8779
8780/// Check for conflict between this global or extern "C" declaration and
8781/// previous global or extern "C" declarations. This is only used in C++.
8782template<typename T>
8784 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8785 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8786 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8787
8788 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8789 // The common case: this global doesn't conflict with any extern "C"
8790 // declaration.
8791 return false;
8792 }
8793
8794 if (Prev) {
8795 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8796 // Both the old and new declarations have C language linkage. This is a
8797 // redeclaration.
8798 Previous.clear();
8799 Previous.addDecl(Prev);
8800 return true;
8801 }
8802
8803 // This is a global, non-extern "C" declaration, and there is a previous
8804 // non-global extern "C" declaration. Diagnose if this is a variable
8805 // declaration.
8806 if (!isa<VarDecl>(ND))
8807 return false;
8808 } else {
8809 // The declaration is extern "C". Check for any declaration in the
8810 // translation unit which might conflict.
8811 if (IsGlobal) {
8812 // We have already performed the lookup into the translation unit.
8813 IsGlobal = false;
8814 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8815 I != E; ++I) {
8816 if (isa<VarDecl>(*I)) {
8817 Prev = *I;
8818 break;
8819 }
8820 }
8821 } else {
8823 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8824 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8825 I != E; ++I) {
8826 if (isa<VarDecl>(*I)) {
8827 Prev = *I;
8828 break;
8829 }
8830 // FIXME: If we have any other entity with this name in global scope,
8831 // the declaration is ill-formed, but that is a defect: it breaks the
8832 // 'stat' hack, for instance. Only variables can have mangled name
8833 // clashes with extern "C" declarations, so only they deserve a
8834 // diagnostic.
8835 }
8836 }
8837
8838 if (!Prev)
8839 return false;
8840 }
8841
8842 // Use the first declaration's location to ensure we point at something which
8843 // is lexically inside an extern "C" linkage-spec.
8844 assert(Prev && "should have found a previous declaration to diagnose");
8845 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8846 Prev = FD->getFirstDecl();
8847 else
8848 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8849
8850 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8851 << IsGlobal << ND;
8852 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8853 << IsGlobal;
8854 return false;
8855}
8856
8857/// Apply special rules for handling extern "C" declarations. Returns \c true
8858/// if we have found that this is a redeclaration of some prior entity.
8859///
8860/// Per C++ [dcl.link]p6:
8861/// Two declarations [for a function or variable] with C language linkage
8862/// with the same name that appear in different scopes refer to the same
8863/// [entity]. An entity with C language linkage shall not be declared with
8864/// the same name as an entity in global scope.
8865template<typename T>
8868 if (!S.getLangOpts().CPlusPlus) {
8869 // In C, when declaring a global variable, look for a corresponding 'extern'
8870 // variable declared in function scope. We don't need this in C++, because
8871 // we find local extern decls in the surrounding file-scope DeclContext.
8872 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8873 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8874 Previous.clear();
8875 Previous.addDecl(Prev);
8876 return true;
8877 }
8878 }
8879 return false;
8880 }
8881
8882 // A declaration in the translation unit can conflict with an extern "C"
8883 // declaration.
8884 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8885 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8886
8887 // An extern "C" declaration can conflict with a declaration in the
8888 // translation unit or can be a redeclaration of an extern "C" declaration
8889 // in another scope.
8890 if (isIncompleteDeclExternC(S,ND))
8891 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8892
8893 // Neither global nor extern "C": nothing to do.
8894 return false;
8895}
8896
8897static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8898 QualType T) {
8899 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8900 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8901 // any of its members, even recursively, shall not have an atomic type, or a
8902 // variably modified type, or a type that is volatile or restrict qualified.
8903 if (CanonT->isVariablyModifiedType()) {
8904 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8905 return true;
8906 }
8907
8908 // Arrays are qualified by their element type, so get the base type (this
8909 // works on non-arrays as well).
8910 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8911
8912 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8913 CanonT.isRestrictQualified()) {
8914 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8915 return true;
8916 }
8917
8918 if (CanonT->isRecordType()) {
8919 const RecordDecl *RD = CanonT->getAsRecordDecl();
8920 if (!RD->isInvalidDecl() &&
8921 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8922 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8923 }))
8924 return true;
8925 }
8926
8927 return false;
8928}
8929
8931 // If the decl is already known invalid, don't check it.
8932 if (NewVD->isInvalidDecl())
8933 return;
8934
8935 QualType T = NewVD->getType();
8936
8937 // Defer checking an 'auto' type until its initializer is attached.
8938 if (T->isUndeducedType())
8939 return;
8940
8941 if (NewVD->hasAttrs())
8943
8944 if (T->isObjCObjectType()) {
8945 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8946 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8947 T = Context.getObjCObjectPointerType(T);
8948 NewVD->setType(T);
8949 }
8950
8951 // Emit an error if an address space was applied to decl with local storage.
8952 // This includes arrays of objects with address space qualifiers, but not
8953 // automatic variables that point to other address spaces.
8954 // ISO/IEC TR 18037 S5.1.2
8955 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8956 T.getAddressSpace() != LangAS::Default) {
8957 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8958 NewVD->setInvalidDecl();
8959 return;
8960 }
8961
8962 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8963 // scope.
8964 if (getLangOpts().OpenCLVersion == 120 &&
8965 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8966 getLangOpts()) &&
8967 NewVD->isStaticLocal()) {
8968 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8969 NewVD->setInvalidDecl();
8970 return;
8971 }
8972
8973 if (getLangOpts().OpenCL) {
8974 if (!diagnoseOpenCLTypes(*this, NewVD))
8975 return;
8976
8977 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8978 if (NewVD->hasAttr<BlocksAttr>()) {
8979 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8980 return;
8981 }
8982
8983 if (T->isBlockPointerType()) {
8984 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8985 // can't use 'extern' storage class.
8986 if (!T.isConstQualified()) {
8987 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8988 << 0 /*const*/;
8989 NewVD->setInvalidDecl();
8990 return;
8991 }
8992 if (NewVD->hasExternalStorage()) {
8993 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8994 NewVD->setInvalidDecl();
8995 return;
8996 }
8997 }
8998
8999 // FIXME: Adding local AS in C++ for OpenCL might make sense.
9000 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
9001 NewVD->hasExternalStorage()) {
9002 if (!T->isSamplerT() && !T->isDependentType() &&
9003 !(T.getAddressSpace() == LangAS::opencl_constant ||
9004 (T.getAddressSpace() == LangAS::opencl_global &&
9005 getOpenCLOptions().areProgramScopeVariablesSupported(
9006 getLangOpts())))) {
9007 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
9008 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
9009 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
9010 << Scope << "global or constant";
9011 else
9012 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
9013 << Scope << "constant";
9014 NewVD->setInvalidDecl();
9015 return;
9016 }
9017 } else {
9018 if (T.getAddressSpace() == LangAS::opencl_global) {
9019 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9020 << 1 /*is any function*/ << "global";
9021 NewVD->setInvalidDecl();
9022 return;
9023 }
9024 // When this extension is enabled, 'local' variables are permitted in
9025 // non-kernel functions and within nested scopes of kernel functions,
9026 // bypassing standard OpenCL address space restrictions.
9027 bool AllowFunctionScopeLocalVariables =
9028 T.getAddressSpace() == LangAS::opencl_local &&
9030 "__cl_clang_function_scope_local_variables", getLangOpts());
9031 if (AllowFunctionScopeLocalVariables) {
9032 // Direct pass: No further diagnostics needed for this specific case.
9033 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9034 T.getAddressSpace() == LangAS::opencl_local) {
9036 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9037 // in functions.
9038 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9039 if (T.getAddressSpace() == LangAS::opencl_constant)
9040 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9041 << 0 /*non-kernel only*/ << "constant";
9042 else
9043 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9044 << 0 /*non-kernel only*/ << "local";
9045 NewVD->setInvalidDecl();
9046 return;
9047 }
9048 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9049 // in the outermost scope of a kernel function.
9050 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9051 if (!getCurScope()->isFunctionScope()) {
9052 if (T.getAddressSpace() == LangAS::opencl_constant)
9053 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9054 << "constant";
9055 else
9056 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9057 << "local";
9058 NewVD->setInvalidDecl();
9059 return;
9060 }
9061 }
9062 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9063 // If we are parsing a template we didn't deduce an addr
9064 // space yet.
9065 T.getAddressSpace() != LangAS::Default) {
9066 // Do not allow other address spaces on automatic variable.
9067 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
9068 NewVD->setInvalidDecl();
9069 return;
9070 }
9071 }
9072 }
9073
9074 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9075 && !NewVD->hasAttr<BlocksAttr>()) {
9076 if (getLangOpts().getGC() != LangOptions::NonGC)
9077 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
9078 else {
9079 assert(!getLangOpts().ObjCAutoRefCount);
9080 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
9081 }
9082 }
9083
9084 // WebAssembly tables must be static with a zero length and can't be
9085 // declared within functions.
9086 if (T->isWebAssemblyTableType()) {
9087 if (getCurScope()->getParent()) { // Parent is null at top-level
9088 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9089 NewVD->setInvalidDecl();
9090 return;
9091 }
9092 if (NewVD->getStorageClass() != SC_Static) {
9093 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9094 NewVD->setInvalidDecl();
9095 return;
9096 }
9097 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9098 if (!ATy || ATy->getZExtSize() != 0) {
9099 Diag(NewVD->getLocation(),
9100 diag::err_typecheck_wasm_table_must_have_zero_length);
9101 NewVD->setInvalidDecl();
9102 return;
9103 }
9104 }
9105
9106 // zero sized static arrays are not allowed in HIP device functions
9107 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9108 if (FunctionDecl *FD = getCurFunctionDecl();
9109 FD &&
9110 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9111 if (const ConstantArrayType *ArrayT =
9112 getASTContext().getAsConstantArrayType(T);
9113 ArrayT && ArrayT->isZeroSize()) {
9114 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9115 }
9116 }
9117 }
9118
9119 bool isVM = T->isVariablyModifiedType();
9120 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9121 NewVD->hasAttr<BlocksAttr>())
9123
9124 if ((isVM && NewVD->hasLinkage()) ||
9125 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9126 bool SizeIsNegative;
9127 llvm::APSInt Oversized;
9129 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9130 QualType FixedT;
9131 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9132 FixedT = FixedTInfo->getType();
9133 else if (FixedTInfo) {
9134 // Type and type-as-written are canonically different. We need to fix up
9135 // both types separately.
9136 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9137 Oversized);
9138 }
9139 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9140 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9141 // FIXME: This won't give the correct result for
9142 // int a[10][n];
9143 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9144
9145 if (NewVD->isFileVarDecl())
9146 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9147 << SizeRange;
9148 else if (NewVD->isStaticLocal())
9149 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9150 << SizeRange;
9151 else
9152 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9153 << SizeRange;
9154 NewVD->setInvalidDecl();
9155 return;
9156 }
9157
9158 if (!FixedTInfo) {
9159 if (NewVD->isFileVarDecl())
9160 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9161 else
9162 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9163 NewVD->setInvalidDecl();
9164 return;
9165 }
9166
9167 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9168 NewVD->setType(FixedT);
9169 NewVD->setTypeSourceInfo(FixedTInfo);
9170 }
9171
9172 if (T->isVoidType()) {
9173 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9174 // of objects and functions.
9176 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9177 << T;
9178 NewVD->setInvalidDecl();
9179 return;
9180 }
9181 }
9182
9183 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9184 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9185 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9186 NewVD->setInvalidDecl();
9187 return;
9188 }
9189
9190 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9191 Diag(NewVD->getLocation(), diag::err_block_not_allowed_on)
9192 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9193 NewVD->setInvalidDecl();
9194 return;
9195 }
9196
9197 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9198 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9199 NewVD->setInvalidDecl();
9200 return;
9201 }
9202
9203 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9204 !T->isDependentType() &&
9205 RequireLiteralType(NewVD->getLocation(), T,
9206 diag::err_constexpr_var_non_literal)) {
9207 NewVD->setInvalidDecl();
9208 return;
9209 }
9210
9211 // PPC MMA non-pointer types are not allowed as non-local variable types.
9212 if (Context.getTargetInfo().getTriple().isPPC64() &&
9213 !NewVD->isLocalVarDecl() &&
9214 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9215 NewVD->setInvalidDecl();
9216 return;
9217 }
9218
9219 // Check that SVE types are only used in functions with SVE available.
9220 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9222 llvm::StringMap<bool> CallerFeatureMap;
9223 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9224 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9225 CallerFeatureMap)) {
9226 NewVD->setInvalidDecl();
9227 return;
9228 }
9229 }
9230
9231 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9233 llvm::StringMap<bool> CallerFeatureMap;
9234 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9236 CallerFeatureMap);
9237 }
9238
9239 if (T.hasAddressSpace() &&
9240 !CheckVarDeclSizeAddressSpace(NewVD, T.getAddressSpace())) {
9241 NewVD->setInvalidDecl();
9242 return;
9243 }
9244}
9245
9248
9249 // If the decl is already known invalid, don't check it.
9250 if (NewVD->isInvalidDecl())
9251 return false;
9252
9253 // If we did not find anything by this name, look for a non-visible
9254 // extern "C" declaration with the same name.
9255 if (Previous.empty() &&
9257 Previous.setShadowed();
9258
9259 if (!Previous.empty()) {
9260 MergeVarDecl(NewVD, Previous);
9261 return true;
9262 }
9263 return false;
9264}
9265
9268
9269 // Look for methods in base classes that this method might override.
9270 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9271 /*DetectVirtual=*/false);
9272 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9273 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9274 DeclarationName Name = MD->getDeclName();
9275
9277 // We really want to find the base class destructor here.
9278 Name = Context.DeclarationNames.getCXXDestructorName(
9279 Context.getCanonicalTagType(BaseRecord));
9280 }
9281
9282 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9283 CXXMethodDecl *BaseMD =
9284 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9285 if (!BaseMD || !BaseMD->isVirtual() ||
9286 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9287 /*ConsiderCudaAttrs=*/true))
9288 continue;
9289 if (!CheckExplicitObjectOverride(MD, BaseMD))
9290 continue;
9291 if (Overridden.insert(BaseMD).second) {
9292 MD->addOverriddenMethod(BaseMD);
9297 }
9298
9299 // A method can only override one function from each base class. We
9300 // don't track indirectly overridden methods from bases of bases.
9301 return true;
9302 }
9303
9304 return false;
9305 };
9306
9307 DC->lookupInBases(VisitBase, Paths);
9308 return !Overridden.empty();
9309}
9310
9311namespace {
9312 // Struct for holding all of the extra arguments needed by
9313 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9314 struct ActOnFDArgs {
9315 Scope *S;
9316 Declarator &D;
9317 MultiTemplateParamsArg TemplateParamLists;
9318 bool AddToScope;
9319 };
9320} // end anonymous namespace
9321
9322namespace {
9323
9324// Callback to only accept typo corrections that have a non-zero edit distance.
9325// Also only accept corrections that have the same parent decl.
9326class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9327 public:
9328 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9329 CXXRecordDecl *Parent)
9330 : Context(Context), OriginalFD(TypoFD),
9331 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9332
9333 bool ValidateCandidate(const TypoCorrection &candidate) override {
9334 if (candidate.getEditDistance() == 0)
9335 return false;
9336
9337 SmallVector<unsigned, 1> MismatchedParams;
9338 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9339 CDeclEnd = candidate.end();
9340 CDecl != CDeclEnd; ++CDecl) {
9341 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9342
9343 if (FD && !FD->hasBody() &&
9344 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9345 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9346 CXXRecordDecl *Parent = MD->getParent();
9347 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9348 return true;
9349 } else if (!ExpectedParent) {
9350 return true;
9351 }
9352 }
9353 }
9354
9355 return false;
9356 }
9357
9358 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9359 return std::make_unique<DifferentNameValidatorCCC>(*this);
9360 }
9361
9362 private:
9363 ASTContext &Context;
9364 FunctionDecl *OriginalFD;
9365 CXXRecordDecl *ExpectedParent;
9366};
9367
9368} // end anonymous namespace
9369
9373
9374/// Generate diagnostics for an invalid function redeclaration.
9375///
9376/// This routine handles generating the diagnostic messages for an invalid
9377/// function redeclaration, including finding possible similar declarations
9378/// or performing typo correction if there are no previous declarations with
9379/// the same name.
9380///
9381/// Returns a NamedDecl iff typo correction was performed and substituting in
9382/// the new declaration name does not cause new errors.
9384 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9385 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9386 DeclarationName Name = NewFD->getDeclName();
9387 DeclContext *NewDC = NewFD->getDeclContext();
9388 SmallVector<unsigned, 1> MismatchedParams;
9390 TypoCorrection Correction;
9391 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9392 unsigned DiagMsg =
9393 IsLocalFriend ? diag::err_no_matching_local_friend :
9394 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9395 diag::err_member_decl_does_not_match;
9396 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9397 IsLocalFriend ? Sema::LookupLocalFriendName
9400
9401 NewFD->setInvalidDecl();
9402 if (IsLocalFriend)
9403 SemaRef.LookupName(Prev, S);
9404 else
9405 SemaRef.LookupQualifiedName(Prev, NewDC);
9406 assert(!Prev.isAmbiguous() &&
9407 "Cannot have an ambiguity in previous-declaration lookup");
9408 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9409 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9410 MD ? MD->getParent() : nullptr);
9411 if (!Prev.empty()) {
9412 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9413 Func != FuncEnd; ++Func) {
9414 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9415 if (FD &&
9416 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9417 // Add 1 to the index so that 0 can mean the mismatch didn't
9418 // involve a parameter
9419 unsigned ParamNum =
9420 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9421 NearMatches.push_back(std::make_pair(FD, ParamNum));
9422 }
9423 }
9424 // If the qualified name lookup yielded nothing, try typo correction
9425 } else if ((Correction = SemaRef.CorrectTypo(
9426 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9427 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9429 IsLocalFriend ? nullptr : NewDC))) {
9430 // Set up everything for the call to ActOnFunctionDeclarator
9431 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9432 ExtraArgs.D.getIdentifierLoc());
9433 Previous.clear();
9434 Previous.setLookupName(Correction.getCorrection());
9435 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9436 CDeclEnd = Correction.end();
9437 CDecl != CDeclEnd; ++CDecl) {
9438 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9439 if (FD && !FD->hasBody() &&
9440 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9441 Previous.addDecl(FD);
9442 }
9443 }
9444 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9445
9447 // Retry building the function declaration with the new previous
9448 // declarations, and with errors suppressed.
9449 {
9450 // Trap errors.
9451 Sema::SFINAETrap Trap(SemaRef);
9452
9453 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9454 // pieces need to verify the typo-corrected C++ declaration and hopefully
9455 // eliminate the need for the parameter pack ExtraArgs.
9457 ExtraArgs.S, ExtraArgs.D,
9458 Correction.getCorrectionDecl()->getDeclContext(),
9459 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9460 ExtraArgs.AddToScope);
9461
9462 if (Trap.hasErrorOccurred())
9463 Result = nullptr;
9464 }
9465
9466 if (Result) {
9467 // Determine which correction we picked.
9468 Decl *Canonical = Result->getCanonicalDecl();
9469 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9470 I != E; ++I)
9471 if ((*I)->getCanonicalDecl() == Canonical)
9472 Correction.setCorrectionDecl(*I);
9473
9474 // Let Sema know about the correction.
9476 SemaRef.diagnoseTypo(
9477 Correction,
9478 SemaRef.PDiag(IsLocalFriend
9479 ? diag::err_no_matching_local_friend_suggest
9480 : diag::err_member_decl_does_not_match_suggest)
9481 << Name << NewDC << IsDefinition);
9482 return Result;
9483 }
9484
9485 // Pretend the typo correction never occurred
9486 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9487 ExtraArgs.D.getIdentifierLoc());
9488 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9489 Previous.clear();
9490 Previous.setLookupName(Name);
9491 }
9492
9493 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9494 << Name << NewDC << IsDefinition << NewFD->getLocation();
9495
9496 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9497 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9498 CXXRecordDecl *RD = NewMD->getParent();
9499 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9500 << RD->getName() << RD->getLocation();
9501 }
9502
9503 bool NewFDisConst = NewMD && NewMD->isConst();
9504
9505 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9506 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9507 NearMatch != NearMatchEnd; ++NearMatch) {
9508 FunctionDecl *FD = NearMatch->first;
9509 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9510 bool FDisConst = MD && MD->isConst();
9511 bool IsMember = MD || !IsLocalFriend;
9512
9513 // FIXME: These notes are poorly worded for the local friend case.
9514 if (unsigned Idx = NearMatch->second) {
9515 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9516 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9517 if (Loc.isInvalid()) Loc = FD->getLocation();
9518 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9519 : diag::note_local_decl_close_param_match)
9520 << Idx << FDParam->getType()
9521 << NewFD->getParamDecl(Idx - 1)->getType();
9522 } else if (FDisConst != NewFDisConst) {
9523 auto DB = SemaRef.Diag(FD->getLocation(),
9524 diag::note_member_def_close_const_match)
9525 << NewFDisConst << FD->getSourceRange().getEnd();
9526 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9527 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9528 " const");
9529 else if (FTI.hasMethodTypeQualifiers() &&
9530 FTI.getConstQualifierLoc().isValid())
9531 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9532 } else {
9533 SemaRef.Diag(FD->getLocation(),
9534 IsMember ? diag::note_member_def_close_match
9535 : diag::note_local_decl_close_match);
9536 }
9537 }
9538 return nullptr;
9539}
9540
9542 switch (D.getDeclSpec().getStorageClassSpec()) {
9543 default: llvm_unreachable("Unknown storage class!");
9544 case DeclSpec::SCS_auto:
9548 diag::err_typecheck_sclass_func);
9550 D.setInvalidType();
9551 break;
9552 case DeclSpec::SCS_unspecified: break;
9555 return SC_None;
9556 return SC_Extern;
9557 case DeclSpec::SCS_static: {
9559 // C99 6.7.1p5:
9560 // The declaration of an identifier for a function that has
9561 // block scope shall have no explicit storage-class specifier
9562 // other than extern
9563 // See also (C++ [dcl.stc]p4).
9565 diag::err_static_block_func);
9566 break;
9567 } else
9568 return SC_Static;
9569 }
9571 }
9572
9573 // No explicit storage class has already been returned
9574 return SC_None;
9575}
9576
9578 DeclContext *DC, QualType &R,
9579 TypeSourceInfo *TInfo,
9580 StorageClass SC,
9581 bool &IsVirtualOkay) {
9582 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9583 DeclarationName Name = NameInfo.getName();
9584
9585 FunctionDecl *NewFD = nullptr;
9586 bool isInline = D.getDeclSpec().isInlineSpecified();
9587
9589 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9590 (SemaRef.getLangOpts().C23 &&
9591 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9592
9593 if (SemaRef.getLangOpts().C23)
9594 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9595 diag::err_c23_constexpr_not_variable);
9596 else
9597 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9598 diag::err_constexpr_wrong_decl_kind)
9599 << static_cast<int>(ConstexprKind);
9600 ConstexprKind = ConstexprSpecKind::Unspecified;
9602 }
9603
9604 if (!SemaRef.getLangOpts().CPlusPlus) {
9605 // Determine whether the function was written with a prototype. This is
9606 // true when:
9607 // - there is a prototype in the declarator, or
9608 // - the type R of the function is some kind of typedef or other non-
9609 // attributed reference to a type name (which eventually refers to a
9610 // function type). Note, we can't always look at the adjusted type to
9611 // check this case because attributes may cause a non-function
9612 // declarator to still have a function type. e.g.,
9613 // typedef void func(int a);
9614 // __attribute__((noreturn)) func other_func; // This has a prototype
9615 bool HasPrototype =
9617 (D.getDeclSpec().isTypeRep() &&
9618 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9619 ->isFunctionProtoType()) ||
9620 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9621 assert(
9622 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9623 "Strict prototypes are required");
9624
9625 NewFD = FunctionDecl::Create(
9626 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9627 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9629 /*TrailingRequiresClause=*/{});
9630 if (D.isInvalidType())
9631 NewFD->setInvalidDecl();
9632
9633 return NewFD;
9634 }
9635
9637 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9638
9639 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9640
9642 // This is a C++ constructor declaration.
9643 assert(DC->isRecord() &&
9644 "Constructors can only be declared in a member context");
9645
9646 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9648 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9650 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9651 InheritedConstructor(), TrailingRequiresClause);
9652
9653 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9654 // This is a C++ destructor declaration.
9655 if (DC->isRecord()) {
9656 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9659 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9660 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9661 /*isImplicitlyDeclared=*/false, ConstexprKind,
9662 TrailingRequiresClause);
9663 // User defined destructors start as not selected if the class definition is still
9664 // not done.
9665 if (Record->isBeingDefined())
9666 NewDD->setIneligibleOrNotSelected(true);
9667
9668 // If the destructor needs an implicit exception specification, set it
9669 // now. FIXME: It'd be nice to be able to create the right type to start
9670 // with, but the type needs to reference the destructor declaration.
9671 if (SemaRef.getLangOpts().CPlusPlus11)
9672 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9673
9674 IsVirtualOkay = true;
9675 return NewDD;
9676
9677 } else {
9678 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9679 D.setInvalidType();
9680
9681 // Create a FunctionDecl to satisfy the function definition parsing
9682 // code path.
9683 return FunctionDecl::Create(
9684 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9685 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9686 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9687 }
9688
9690 if (!DC->isRecord()) {
9691 SemaRef.Diag(D.getIdentifierLoc(),
9692 diag::err_conv_function_not_member);
9693 return nullptr;
9694 }
9695
9696 SemaRef.CheckConversionDeclarator(D, R, SC);
9697 if (D.isInvalidType())
9698 return nullptr;
9699
9700 IsVirtualOkay = true;
9702 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9703 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9704 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9705 TrailingRequiresClause);
9706
9708 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9709 return nullptr;
9711 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9712 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9713 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9714 } else if (DC->isRecord()) {
9715 // If the name of the function is the same as the name of the record,
9716 // then this must be an invalid constructor that has a return type.
9717 // (The parser checks for a return type and makes the declarator a
9718 // constructor if it has no return type).
9719 if (Name.getAsIdentifierInfo() &&
9720 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9721 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9724 return nullptr;
9725 }
9726
9727 // This is a C++ method declaration.
9729 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9730 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9731 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9732 IsVirtualOkay = !Ret->isStatic();
9733 return Ret;
9734 } else {
9735 bool isFriend =
9736 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9737 if (!isFriend && SemaRef.CurContext->isRecord())
9738 return nullptr;
9739
9740 // Determine whether the function was written with a
9741 // prototype. This true when:
9742 // - we're in C++ (where every function has a prototype),
9743 return FunctionDecl::Create(
9744 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9745 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9746 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9747 }
9748}
9749
9758
9760 // Size dependent types are just typedefs to normal integer types
9761 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9762 // integers other than by their names.
9763 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9764
9765 // Remove typedefs one by one until we reach a typedef
9766 // for a size dependent type.
9767 QualType DesugaredTy = Ty;
9768 do {
9769 ArrayRef<StringRef> Names(SizeTypeNames);
9770 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9771 if (Names.end() != Match)
9772 return true;
9773
9774 Ty = DesugaredTy;
9775 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9776 } while (DesugaredTy != Ty);
9777
9778 return false;
9779}
9780
9782 if (PT->isDependentType())
9783 return InvalidKernelParam;
9784
9785 if (PT->isPointerOrReferenceType()) {
9786 QualType PointeeType = PT->getPointeeType();
9787 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9788 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9789 PointeeType.getAddressSpace() == LangAS::Default)
9791
9792 if (PointeeType->isPointerType()) {
9793 // This is a pointer to pointer parameter.
9794 // Recursively check inner type.
9795 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9796 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9797 ParamKind == InvalidKernelParam)
9798 return ParamKind;
9799
9800 // OpenCL v3.0 s6.11.a:
9801 // A restriction to pass pointers to pointers only applies to OpenCL C
9802 // v1.2 or below.
9804 return ValidKernelParam;
9805
9806 return PtrPtrKernelParam;
9807 }
9808
9809 // C++ for OpenCL v1.0 s2.4:
9810 // Moreover the types used in parameters of the kernel functions must be:
9811 // Standard layout types for pointer parameters. The same applies to
9812 // reference if an implementation supports them in kernel parameters.
9813 if (S.getLangOpts().OpenCLCPlusPlus &&
9815 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9816 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9817 bool IsStandardLayoutType = true;
9818 if (CXXRec) {
9819 // If template type is not ODR-used its definition is only available
9820 // in the template definition not its instantiation.
9821 // FIXME: This logic doesn't work for types that depend on template
9822 // parameter (PR58590).
9823 if (!CXXRec->hasDefinition())
9824 CXXRec = CXXRec->getTemplateInstantiationPattern();
9825 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9826 IsStandardLayoutType = false;
9827 }
9828 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9829 !IsStandardLayoutType)
9830 return InvalidKernelParam;
9831 }
9832
9833 // OpenCL v1.2 s6.9.p:
9834 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9836 return ValidKernelParam;
9837
9838 return PtrKernelParam;
9839 }
9840
9841 // OpenCL v1.2 s6.9.k:
9842 // Arguments to kernel functions in a program cannot be declared with the
9843 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9844 // uintptr_t or a struct and/or union that contain fields declared to be one
9845 // of these built-in scalar types.
9847 return InvalidKernelParam;
9848
9849 if (PT->isImageType())
9850 return PtrKernelParam;
9851
9852 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9853 return InvalidKernelParam;
9854
9855 // OpenCL extension spec v1.2 s9.5:
9856 // This extension adds support for half scalar and vector types as built-in
9857 // types that can be used for arithmetic operations, conversions etc.
9858 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9859 PT->isHalfType())
9860 return InvalidKernelParam;
9861
9862 // Look into an array argument to check if it has a forbidden type.
9863 if (PT->isArrayType()) {
9864 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9865 // Call ourself to check an underlying type of an array. Since the
9866 // getPointeeOrArrayElementType returns an innermost type which is not an
9867 // array, this recursive call only happens once.
9868 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9869 }
9870
9871 // C++ for OpenCL v1.0 s2.4:
9872 // Moreover the types used in parameters of the kernel functions must be:
9873 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9874 // types) for parameters passed by value;
9875 if (S.getLangOpts().OpenCLCPlusPlus &&
9877 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9878 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9879 return InvalidKernelParam;
9880
9881 if (PT->isRecordType())
9882 return RecordKernelParam;
9883
9884 return ValidKernelParam;
9885}
9886
9888 Sema &S,
9889 Declarator &D,
9890 ParmVarDecl *Param,
9891 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9892 QualType PT = Param->getType();
9893
9894 // Cache the valid types we encounter to avoid rechecking structs that are
9895 // used again
9896 if (ValidTypes.count(PT.getTypePtr()))
9897 return;
9898
9899 switch (getOpenCLKernelParameterType(S, PT)) {
9900 case PtrPtrKernelParam:
9901 // OpenCL v3.0 s6.11.a:
9902 // A kernel function argument cannot be declared as a pointer to a pointer
9903 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9904 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9905 D.setInvalidType();
9906 return;
9907
9909 // OpenCL v1.0 s6.5:
9910 // __kernel function arguments declared to be a pointer of a type can point
9911 // to one of the following address spaces only : __global, __local or
9912 // __constant.
9913 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9914 D.setInvalidType();
9915 return;
9916
9917 // OpenCL v1.2 s6.9.k:
9918 // Arguments to kernel functions in a program cannot be declared with the
9919 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9920 // uintptr_t or a struct and/or union that contain fields declared to be
9921 // one of these built-in scalar types.
9922
9923 case InvalidKernelParam:
9924 // OpenCL v1.2 s6.8 n:
9925 // A kernel function argument cannot be declared
9926 // of event_t type.
9927 // Do not diagnose half type since it is diagnosed as invalid argument
9928 // type for any function elsewhere.
9929 if (!PT->isHalfType()) {
9930 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9931
9932 // Explain what typedefs are involved.
9933 const TypedefType *Typedef = nullptr;
9934 while ((Typedef = PT->getAs<TypedefType>())) {
9935 SourceLocation Loc = Typedef->getDecl()->getLocation();
9936 // SourceLocation may be invalid for a built-in type.
9937 if (Loc.isValid())
9938 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9939 PT = Typedef->desugar();
9940 }
9941 }
9942
9943 D.setInvalidType();
9944 return;
9945
9946 case PtrKernelParam:
9947 case ValidKernelParam:
9948 ValidTypes.insert(PT.getTypePtr());
9949 return;
9950
9951 case RecordKernelParam:
9952 break;
9953 }
9954
9955 // Track nested structs we will inspect
9957
9958 // Track where we are in the nested structs. Items will migrate from
9959 // VisitStack to HistoryStack as we do the DFS for bad field.
9961 HistoryStack.push_back(nullptr);
9962
9963 // At this point we already handled everything except of a RecordType.
9964 assert(PT->isRecordType() && "Unexpected type.");
9965 const auto *PD = PT->castAsRecordDecl();
9966 VisitStack.push_back(PD);
9967 assert(VisitStack.back() && "First decl null?");
9968
9969 do {
9970 const Decl *Next = VisitStack.pop_back_val();
9971 if (!Next) {
9972 assert(!HistoryStack.empty());
9973 // Found a marker, we have gone up a level
9974 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9975 ValidTypes.insert(Hist->getType().getTypePtr());
9976
9977 continue;
9978 }
9979
9980 // Adds everything except the original parameter declaration (which is not a
9981 // field itself) to the history stack.
9982 const RecordDecl *RD;
9983 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9984 HistoryStack.push_back(Field);
9985
9986 QualType FieldTy = Field->getType();
9987 // Other field types (known to be valid or invalid) are handled while we
9988 // walk around RecordDecl::fields().
9989 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9990 "Unexpected type.");
9991 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9992
9993 RD = FieldRecTy->castAsRecordDecl();
9994 } else {
9995 RD = cast<RecordDecl>(Next);
9996 }
9997
9998 // Add a null marker so we know when we've gone back up a level
9999 VisitStack.push_back(nullptr);
10000
10001 for (const auto *FD : RD->fields()) {
10002 QualType QT = FD->getType();
10003
10004 if (ValidTypes.count(QT.getTypePtr()))
10005 continue;
10006
10008 if (ParamType == ValidKernelParam)
10009 continue;
10010
10011 if (ParamType == RecordKernelParam) {
10012 VisitStack.push_back(FD);
10013 continue;
10014 }
10015
10016 // OpenCL v1.2 s6.9.p:
10017 // Arguments to kernel functions that are declared to be a struct or union
10018 // do not allow OpenCL objects to be passed as elements of the struct or
10019 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10020 // of SVM.
10021 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10022 ParamType == InvalidAddrSpacePtrKernelParam) {
10023 S.Diag(Param->getLocation(),
10024 diag::err_record_with_pointers_kernel_param)
10025 << PT->isUnionType()
10026 << PT;
10027 } else {
10028 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
10029 }
10030
10031 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
10032 << PD->getDeclName();
10033
10034 // We have an error, now let's go back up through history and show where
10035 // the offending field came from
10037 I = HistoryStack.begin() + 1,
10038 E = HistoryStack.end();
10039 I != E; ++I) {
10040 const FieldDecl *OuterField = *I;
10041 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
10042 << OuterField->getType();
10043 }
10044
10045 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
10046 << QT->isPointerType()
10047 << QT;
10048 D.setInvalidType();
10049 return;
10050 }
10051 } while (!VisitStack.empty());
10052}
10053
10054/// Find the DeclContext in which a tag is implicitly declared if we see an
10055/// elaborated type specifier in the specified context, and lookup finds
10056/// nothing.
10058 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10059 DC = DC->getParent();
10060 return DC;
10061}
10062
10063/// Find the Scope in which a tag is implicitly declared if we see an
10064/// elaborated type specifier in the specified context, and lookup finds
10065/// nothing.
10066static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10067 while (S->isClassScope() ||
10068 (LangOpts.CPlusPlus &&
10070 ((S->getFlags() & Scope::DeclScope) == 0) ||
10071 (S->getEntity() && S->getEntity()->isTransparentContext()))
10072 S = S->getParent();
10073 return S;
10074}
10075
10076/// Determine whether a declaration matches a known function in namespace std.
10078 unsigned BuiltinID) {
10079 switch (BuiltinID) {
10080 case Builtin::BI__GetExceptionInfo:
10081 // No type checking whatsoever.
10082 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10083
10084 case Builtin::BIaddressof:
10085 case Builtin::BI__addressof:
10086 case Builtin::BIforward:
10087 case Builtin::BIforward_like:
10088 case Builtin::BImove:
10089 case Builtin::BImove_if_noexcept:
10090 case Builtin::BIas_const: {
10091 // Ensure that we don't treat the algorithm
10092 // OutputIt std::move(InputIt, InputIt, OutputIt)
10093 // as the builtin std::move.
10094 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10095 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10096 }
10097
10098 default:
10099 return false;
10100 }
10101}
10102
10103NamedDecl*
10106 MultiTemplateParamsArg TemplateParamListsRef,
10107 bool &AddToScope) {
10108 QualType R = TInfo->getType();
10109
10110 assert(R->isFunctionType());
10111 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10112 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10113
10114 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10115 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10117 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10118 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10119 TemplateParamLists.back() = Invented;
10120 else
10121 TemplateParamLists.push_back(Invented);
10122 }
10123
10124 // TODO: consider using NameInfo for diagnostic.
10126 DeclarationName Name = NameInfo.getName();
10128
10131 diag::err_invalid_thread)
10133
10138
10139 bool isFriend = false;
10141 bool isMemberSpecialization = false;
10142 bool isFunctionTemplateSpecialization = false;
10143
10144 bool HasExplicitTemplateArgs = false;
10145 TemplateArgumentListInfo TemplateArgs;
10146
10147 bool isVirtualOkay = false;
10148
10149 DeclContext *OriginalDC = DC;
10150 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10151
10152 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10153 isVirtualOkay);
10154 if (!NewFD) return nullptr;
10155
10156 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10158
10159 // Set the lexical context. If this is a function-scope declaration, or has a
10160 // C++ scope specifier, or is the object of a friend declaration, the lexical
10161 // context will be different from the semantic context.
10163
10164 if (IsLocalExternDecl)
10165 NewFD->setLocalExternDecl();
10166
10167 if (getLangOpts().CPlusPlus) {
10168 // The rules for implicit inlines changed in C++20 for methods and friends
10169 // with an in-class definition (when such a definition is not attached to
10170 // the global module). This does not affect declarations that are already
10171 // inline (whether explicitly or implicitly by being declared constexpr,
10172 // consteval, etc).
10173 // FIXME: We need a better way to separate C++ standard and clang modules.
10174 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10175 !NewFD->getOwningModule() ||
10176 NewFD->isFromGlobalModule() ||
10178 bool isInline = D.getDeclSpec().isInlineSpecified();
10179 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10180 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10181 isFriend = D.getDeclSpec().isFriendSpecified();
10182 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10183 // Pre-C++20 [class.friend]p5
10184 // A function can be defined in a friend declaration of a
10185 // class . . . . Such a function is implicitly inline.
10186 // Post C++20 [class.friend]p7
10187 // Such a function is implicitly an inline function if it is attached
10188 // to the global module.
10189 NewFD->setImplicitlyInline();
10190 }
10191
10192 // If this is a method defined in an __interface, and is not a constructor
10193 // or an overloaded operator, then set the pure flag (isVirtual will already
10194 // return true).
10195 if (const CXXRecordDecl *Parent =
10196 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10197 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10198 NewFD->setIsPureVirtual(true);
10199
10200 // C++ [class.union]p2
10201 // A union can have member functions, but not virtual functions.
10202 if (isVirtual && Parent->isUnion()) {
10203 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10204 NewFD->setInvalidDecl();
10205 }
10206 if ((Parent->isClass() || Parent->isStruct()) &&
10207 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10208 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10209 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10210 if (auto *Def = Parent->getDefinition())
10211 Def->setInitMethod(true);
10212 }
10213 }
10214
10215 SetNestedNameSpecifier(*this, NewFD, D);
10216 isMemberSpecialization = false;
10217 isFunctionTemplateSpecialization = false;
10218 if (D.isInvalidType())
10219 NewFD->setInvalidDecl();
10220
10221 // Match up the template parameter lists with the scope specifier, then
10222 // determine whether we have a template or a template specialization.
10223 bool Invalid = false;
10224 TemplateIdAnnotation *TemplateId =
10226 ? D.getName().TemplateId
10227 : nullptr;
10228 TemplateParameterList *TemplateParams =
10231 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10232 isMemberSpecialization, Invalid);
10233 if (TemplateParams) {
10234 // Check that we can declare a template here.
10235 if (CheckTemplateDeclScope(S, TemplateParams))
10236 NewFD->setInvalidDecl();
10237
10238 if (TemplateParams->size() > 0) {
10239 // This is a function template
10240
10241 // A destructor cannot be a template.
10243 Diag(NewFD->getLocation(), diag::err_destructor_template);
10244 NewFD->setInvalidDecl();
10245 // Function template with explicit template arguments.
10246 } else if (TemplateId) {
10247 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10248 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10249 NewFD->setInvalidDecl();
10250 }
10251
10252 // If we're adding a template to a dependent context, we may need to
10253 // rebuilding some of the types used within the template parameter list,
10254 // now that we know what the current instantiation is.
10255 if (DC->isDependentContext()) {
10256 ContextRAII SavedContext(*this, DC);
10258 Invalid = true;
10259 }
10260
10262 NewFD->getLocation(),
10263 Name, TemplateParams,
10264 NewFD);
10265 FunctionTemplate->setLexicalDeclContext(CurContext);
10267
10268 // For source fidelity, store the other template param lists.
10269 if (TemplateParamLists.size() > 1) {
10271 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10272 .drop_back(1));
10273 }
10274 } else {
10275 // This is a function template specialization.
10276 isFunctionTemplateSpecialization = true;
10277 // For source fidelity, store all the template param lists.
10278 if (TemplateParamLists.size() > 0)
10279 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10280
10281 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10282 if (isFriend) {
10283 // We want to remove the "template<>", found here.
10284 SourceRange RemoveRange = TemplateParams->getSourceRange();
10285
10286 // If we remove the template<> and the name is not a
10287 // template-id, we're actually silently creating a problem:
10288 // the friend declaration will refer to an untemplated decl,
10289 // and clearly the user wants a template specialization. So
10290 // we need to insert '<>' after the name.
10291 SourceLocation InsertLoc;
10293 InsertLoc = D.getName().getSourceRange().getEnd();
10294 InsertLoc = getLocForEndOfToken(InsertLoc);
10295 }
10296
10297 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10298 << Name << RemoveRange
10299 << FixItHint::CreateRemoval(RemoveRange)
10300 << FixItHint::CreateInsertion(InsertLoc, "<>");
10301 Invalid = true;
10302
10303 // Recover by faking up an empty template argument list.
10304 HasExplicitTemplateArgs = true;
10305 TemplateArgs.setLAngleLoc(InsertLoc);
10306 TemplateArgs.setRAngleLoc(InsertLoc);
10307 }
10308 }
10309 } else {
10310 // Check that we can declare a template here.
10311 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10312 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10313 NewFD->setInvalidDecl();
10314
10315 // All template param lists were matched against the scope specifier:
10316 // this is NOT (an explicit specialization of) a template.
10317 if (TemplateParamLists.size() > 0)
10318 // For source fidelity, store all the template param lists.
10319 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10320
10321 // "friend void foo<>(int);" is an implicit specialization decl.
10322 if (isFriend && TemplateId)
10323 isFunctionTemplateSpecialization = true;
10324 }
10325
10326 // If this is a function template specialization and the unqualified-id of
10327 // the declarator-id is a template-id, convert the template argument list
10328 // into our AST format and check for unexpanded packs.
10329 if (isFunctionTemplateSpecialization && TemplateId) {
10330 HasExplicitTemplateArgs = true;
10331
10332 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10333 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10334 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10335 TemplateId->NumArgs);
10336 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10337
10338 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10339 // declaration of a function template partial specialization? Should we
10340 // consider the unexpanded pack context to be a partial specialization?
10341 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10343 ArgLoc, isFriend ? UPPC_FriendDeclaration
10345 NewFD->setInvalidDecl();
10346 }
10347 }
10348
10349 if (Invalid) {
10350 NewFD->setInvalidDecl();
10351 if (FunctionTemplate)
10352 FunctionTemplate->setInvalidDecl();
10353 }
10354
10355 // C++ [dcl.fct.spec]p5:
10356 // The virtual specifier shall only be used in declarations of
10357 // nonstatic class member functions that appear within a
10358 // member-specification of a class declaration; see 10.3.
10359 //
10360 if (isVirtual && !NewFD->isInvalidDecl()) {
10361 if (!isVirtualOkay) {
10363 diag::err_virtual_non_function);
10364 } else if (!CurContext->isRecord()) {
10365 // 'virtual' was specified outside of the class.
10367 diag::err_virtual_out_of_class)
10369 } else if (NewFD->getDescribedFunctionTemplate()) {
10370 // C++ [temp.mem]p3:
10371 // A member function template shall not be virtual.
10373 diag::err_virtual_member_function_template)
10375 } else {
10376 // Okay: Add virtual to the method.
10377 NewFD->setVirtualAsWritten(true);
10378 }
10379
10380 if (getLangOpts().CPlusPlus14 &&
10381 NewFD->getReturnType()->isUndeducedType())
10382 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10383 }
10384
10385 // C++ [dcl.fct.spec]p3:
10386 // The inline specifier shall not appear on a block scope function
10387 // declaration.
10388 if (isInline && !NewFD->isInvalidDecl()) {
10389 if (CurContext->isFunctionOrMethod()) {
10390 // 'inline' is not allowed on block scope function declaration.
10392 diag::err_inline_declaration_block_scope) << Name
10394 }
10395 }
10396
10397 // C++ [dcl.fct.spec]p6:
10398 // The explicit specifier shall be used only in the declaration of a
10399 // constructor or conversion function within its class definition;
10400 // see 12.3.1 and 12.3.2.
10401 if (hasExplicit && !NewFD->isInvalidDecl() &&
10403 if (!CurContext->isRecord()) {
10404 // 'explicit' was specified outside of the class.
10406 diag::err_explicit_out_of_class)
10408 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10409 !isa<CXXConversionDecl>(NewFD)) {
10410 // 'explicit' was specified on a function that wasn't a constructor
10411 // or conversion function.
10413 diag::err_explicit_non_ctor_or_conv_function)
10415 }
10416 }
10417
10419 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10420 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10421 // are implicitly inline.
10422 NewFD->setImplicitlyInline();
10423
10424 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10425 // be either constructors or to return a literal type. Therefore,
10426 // destructors cannot be declared constexpr.
10427 if (isa<CXXDestructorDecl>(NewFD) &&
10429 ConstexprKind == ConstexprSpecKind::Consteval)) {
10430 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10431 << static_cast<int>(ConstexprKind);
10435 }
10436 // C++20 [dcl.constexpr]p2: An allocation function, or a
10437 // deallocation function shall not be declared with the consteval
10438 // specifier.
10439 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10442 diag::err_invalid_consteval_decl_kind)
10443 << NewFD;
10445 }
10446 }
10447
10448 // If __module_private__ was specified, mark the function accordingly.
10450 if (isFunctionTemplateSpecialization) {
10451 SourceLocation ModulePrivateLoc
10453 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10454 << 0
10455 << FixItHint::CreateRemoval(ModulePrivateLoc);
10456 } else {
10457 NewFD->setModulePrivate();
10458 if (FunctionTemplate)
10459 FunctionTemplate->setModulePrivate();
10460 }
10461 }
10462
10463 if (isFriend) {
10464 if (FunctionTemplate) {
10465 FunctionTemplate->setObjectOfFriendDecl();
10466 FunctionTemplate->setAccess(AS_public);
10467 }
10468 NewFD->setObjectOfFriendDecl();
10469 NewFD->setAccess(AS_public);
10470 }
10471
10472 // If a function is defined as defaulted or deleted, mark it as such now.
10473 // We'll do the relevant checks on defaulted / deleted functions later.
10474 switch (D.getFunctionDefinitionKind()) {
10477 break;
10478
10480 NewFD->setDefaulted();
10481 break;
10482
10484 NewFD->setDeletedAsWritten();
10485 break;
10486 }
10487
10488 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10490 // Pre C++20 [class.mfct]p2:
10491 // A member function may be defined (8.4) in its class definition, in
10492 // which case it is an inline member function (7.1.2)
10493 // Post C++20 [class.mfct]p1:
10494 // If a member function is attached to the global module and is defined
10495 // in its class definition, it is inline.
10496 NewFD->setImplicitlyInline();
10497 }
10498
10499 if (!isFriend && SC != SC_None) {
10500 // C++ [temp.expl.spec]p2:
10501 // The declaration in an explicit-specialization shall not be an
10502 // export-declaration. An explicit specialization shall not use a
10503 // storage-class-specifier other than thread_local.
10504 //
10505 // We diagnose friend declarations with storage-class-specifiers
10506 // elsewhere.
10507 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10509 diag::ext_explicit_specialization_storage_class)
10512 }
10513
10514 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10515 assert(isa<CXXMethodDecl>(NewFD) &&
10516 "Out-of-line member function should be a CXXMethodDecl");
10517 // C++ [class.static]p1:
10518 // A data or function member of a class may be declared static
10519 // in a class definition, in which case it is a static member of
10520 // the class.
10521
10522 // Complain about the 'static' specifier if it's on an out-of-line
10523 // member function definition.
10524
10525 // MSVC permits the use of a 'static' storage specifier on an
10526 // out-of-line member function template declaration and class member
10527 // template declaration (MSVC versions before 2015), warn about this.
10529 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10530 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10531 (getLangOpts().MSVCCompat &&
10533 ? diag::ext_static_out_of_line
10534 : diag::err_static_out_of_line)
10537 }
10538 }
10539
10540 // C++11 [except.spec]p15:
10541 // A deallocation function with no exception-specification is treated
10542 // as if it were specified with noexcept(true).
10543 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10544 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10545 !FPT->hasExceptionSpec())
10546 NewFD->setType(Context.getFunctionType(
10547 FPT->getReturnType(), FPT->getParamTypes(),
10549
10550 // C++20 [dcl.inline]/7
10551 // If an inline function or variable that is attached to a named module
10552 // is declared in a definition domain, it shall be defined in that
10553 // domain.
10554 // So, if the current declaration does not have a definition, we must
10555 // check at the end of the TU (or when the PMF starts) to see that we
10556 // have a definition at that point.
10557 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10558 NewFD->isInNamedModule()) {
10559 PendingInlineFuncDecls.insert(NewFD);
10560 }
10561 }
10562
10563 // Filter out previous declarations that don't match the scope.
10566 isMemberSpecialization ||
10567 isFunctionTemplateSpecialization);
10568
10570
10571 // Handle GNU asm-label extension (encoded as an attribute).
10572 if (Expr *E = D.getAsmLabel()) {
10573 // The parser guarantees this is a string.
10575 NewFD->addAttr(
10576 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10577 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10578 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10580 if (I != ExtnameUndeclaredIdentifiers.end()) {
10581 if (isDeclExternC(NewFD)) {
10582 NewFD->addAttr(I->second);
10584 } else if (NewFD->getDeclContext()
10587 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10588 << /*Variable*/0 << NewFD;
10589 }
10590 }
10591
10592 // Copy the parameter declarations from the declarator D to the function
10593 // declaration NewFD, if they are available. First scavenge them into Params.
10595 unsigned FTIIdx;
10596 if (D.isFunctionDeclarator(FTIIdx)) {
10598
10599 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10600 // function that takes no arguments, not a function that takes a
10601 // single void argument.
10602 // We let through "const void" here because Sema::GetTypeForDeclarator
10603 // already checks for that case.
10604 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10605 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10606 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10607 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10608 Param->setDeclContext(NewFD);
10609 Params.push_back(Param);
10610
10611 if (Param->isInvalidDecl())
10612 NewFD->setInvalidDecl();
10613 }
10614 }
10615
10616 if (!getLangOpts().CPlusPlus) {
10617 // In C, find all the tag declarations from the prototype and move them
10618 // into the function DeclContext. Remove them from the surrounding tag
10619 // injection context of the function, which is typically but not always
10620 // the TU.
10621 DeclContext *PrototypeTagContext =
10623 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10624 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10625
10626 // We don't want to reparent enumerators. Look at their parent enum
10627 // instead.
10628 if (!TD) {
10629 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10630 TD = cast<EnumDecl>(ECD->getDeclContext());
10631 }
10632 if (!TD)
10633 continue;
10634 DeclContext *TagDC = TD->getLexicalDeclContext();
10635 if (!TagDC->containsDecl(TD))
10636 continue;
10637 TagDC->removeDecl(TD);
10638 TD->setDeclContext(NewFD);
10639 NewFD->addDecl(TD);
10640
10641 // Preserve the lexical DeclContext if it is not the surrounding tag
10642 // injection context of the FD. In this example, the semantic context of
10643 // E will be f and the lexical context will be S, while both the
10644 // semantic and lexical contexts of S will be f:
10645 // void f(struct S { enum E { a } f; } s);
10646 if (TagDC != PrototypeTagContext)
10647 TD->setLexicalDeclContext(TagDC);
10648 }
10649 }
10650 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10651 // When we're declaring a function with a typedef, typeof, etc as in the
10652 // following example, we'll need to synthesize (unnamed)
10653 // parameters for use in the declaration.
10654 //
10655 // @code
10656 // typedef void fn(int);
10657 // fn f;
10658 // @endcode
10659
10660 // Synthesize a parameter for each argument type.
10661 for (const auto &AI : FT->param_types()) {
10662 ParmVarDecl *Param =
10664 Param->setScopeInfo(0, Params.size());
10665 Params.push_back(Param);
10666 }
10667 } else {
10668 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10669 "Should not need args for typedef of non-prototype fn");
10670 }
10671
10672 // Finally, we know we have the right number of parameters, install them.
10673 NewFD->setParams(Params);
10674
10675 // If this declarator is a declaration and not a definition, its parameters
10676 // will not be pushed onto a scope chain. That means we will not issue any
10677 // reserved identifier warnings for the declaration, but we will for the
10678 // definition. Handle those here.
10679 if (!D.isFunctionDefinition()) {
10680 for (const ParmVarDecl *PVD : Params)
10682 }
10683
10685 NewFD->addAttr(
10686 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10687
10688 // Functions returning a variably modified type violate C99 6.7.5.2p2
10689 // because all functions have linkage.
10690 if (!NewFD->isInvalidDecl() &&
10692 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10693 NewFD->setInvalidDecl();
10694 }
10695
10696 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10698 !NewFD->hasAttr<SectionAttr>())
10699 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10700 Context, PragmaClangTextSection.SectionName,
10701 PragmaClangTextSection.PragmaLocation));
10702
10703 // Apply an implicit SectionAttr if #pragma code_seg is active.
10704 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10705 !NewFD->hasAttr<SectionAttr>()) {
10706 NewFD->addAttr(SectionAttr::CreateImplicit(
10707 Context, CodeSegStack.CurrentValue->getString(),
10708 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10709 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10712 NewFD))
10713 NewFD->dropAttr<SectionAttr>();
10714 }
10715
10716 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10717 // active.
10718 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10719 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10720 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10721 Context, PragmaClangTextSection.PragmaLocation));
10722
10723 // Apply an implicit CodeSegAttr from class declspec or
10724 // apply an implicit SectionAttr from #pragma code_seg if active.
10725 if (!NewFD->hasAttr<CodeSegAttr>()) {
10727 D.isFunctionDefinition())) {
10728 NewFD->addAttr(SAttr);
10729 }
10730 }
10731
10732 // Handle attributes.
10733 ProcessDeclAttributes(S, NewFD, D);
10734 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10735 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10736 !NewTVA->isDefaultVersion() &&
10737 !Context.getTargetInfo().hasFeature("fmv")) {
10738 // Don't add to scope fmv functions declarations if fmv disabled
10739 AddToScope = false;
10740 return NewFD;
10741 }
10742
10743 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10744 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10745 // type.
10746 //
10747 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10748 // type declaration will generate a compilation error.
10749 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10750 if (AddressSpace != LangAS::Default) {
10751 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10752 NewFD->setInvalidDecl();
10753 }
10754 }
10755
10756 if (!getLangOpts().CPlusPlus) {
10757 // Perform semantic checking on the function declaration.
10758 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10759 CheckMain(NewFD, D.getDeclSpec());
10760
10761 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10762 CheckMSVCRTEntryPoint(NewFD);
10763
10764 if (!NewFD->isInvalidDecl())
10766 isMemberSpecialization,
10768 else if (!Previous.empty())
10769 // Recover gracefully from an invalid redeclaration.
10770 D.setRedeclaration(true);
10771 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10772 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10773 "previous declaration set still overloaded");
10774
10775 // Diagnose no-prototype function declarations with calling conventions that
10776 // don't support variadic calls. Only do this in C and do it after merging
10777 // possibly prototyped redeclarations.
10778 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10780 CallingConv CC = FT->getExtInfo().getCC();
10781 if (!supportsVariadicCall(CC)) {
10782 // Windows system headers sometimes accidentally use stdcall without
10783 // (void) parameters, so we relax this to a warning.
10784 int DiagID =
10785 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10786 Diag(NewFD->getLocation(), DiagID)
10788 }
10789 }
10790
10794 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10796 } else {
10797 // C++11 [replacement.functions]p3:
10798 // The program's definitions shall not be specified as inline.
10799 //
10800 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10801 //
10802 // Suppress the diagnostic if the function is __attribute__((used)), since
10803 // that forces an external definition to be emitted.
10804 if (D.getDeclSpec().isInlineSpecified() &&
10806 !NewFD->hasAttr<UsedAttr>())
10808 diag::ext_operator_new_delete_declared_inline)
10809 << NewFD->getDeclName();
10810
10811 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10812 // C++20 [dcl.decl.general]p4:
10813 // The optional requires-clause in an init-declarator or
10814 // member-declarator shall be present only if the declarator declares a
10815 // templated function.
10816 //
10817 // C++20 [temp.pre]p8:
10818 // An entity is templated if it is
10819 // - a template,
10820 // - an entity defined or created in a templated entity,
10821 // - a member of a templated entity,
10822 // - an enumerator for an enumeration that is a templated entity, or
10823 // - the closure type of a lambda-expression appearing in the
10824 // declaration of a templated entity.
10825 //
10826 // [Note 6: A local class, a local or block variable, or a friend
10827 // function defined in a templated entity is a templated entity.
10828 // — end note]
10829 //
10830 // A templated function is a function template or a function that is
10831 // templated. A templated class is a class template or a class that is
10832 // templated. A templated variable is a variable template or a variable
10833 // that is templated.
10834 if (!FunctionTemplate) {
10835 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10836 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10837 // An explicit specialization shall not have a trailing
10838 // requires-clause unless it declares a function template.
10839 //
10840 // Since a friend function template specialization cannot be
10841 // definition, and since a non-template friend declaration with a
10842 // trailing requires-clause must be a definition, we diagnose
10843 // friend function template specializations with trailing
10844 // requires-clauses on the same path as explicit specializations
10845 // even though they aren't necessarily prohibited by the same
10846 // language rule.
10847 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10848 << isFriend;
10849 } else if (isFriend && NewFD->isTemplated() &&
10850 !D.isFunctionDefinition()) {
10851 // C++ [temp.friend]p9:
10852 // A non-template friend declaration with a requires-clause shall be
10853 // a definition.
10854 Diag(NewFD->getBeginLoc(),
10855 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10856 NewFD->setInvalidDecl();
10857 } else if (!NewFD->isTemplated() ||
10858 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10859 Diag(TRC->getBeginLoc(),
10860 diag::err_constrained_non_templated_function);
10861 }
10862 }
10863 }
10864
10865 // We do not add HD attributes to specializations here because
10866 // they may have different constexpr-ness compared to their
10867 // templates and, after maybeAddHostDeviceAttrs() is applied,
10868 // may end up with different effective targets. Instead, a
10869 // specialization inherits its target attributes from its template
10870 // in the CheckFunctionTemplateSpecialization() call below.
10871 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10873
10874 // Handle explicit specializations of function templates
10875 // and friend function declarations with an explicit
10876 // template argument list.
10877 if (isFunctionTemplateSpecialization) {
10878 bool isDependentSpecialization = false;
10879 if (isFriend) {
10880 // For friend function specializations, this is a dependent
10881 // specialization if its semantic context is dependent, its
10882 // type is dependent, or if its template-id is dependent.
10883 isDependentSpecialization =
10884 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10885 (HasExplicitTemplateArgs &&
10886 TemplateSpecializationType::
10887 anyInstantiationDependentTemplateArguments(
10888 TemplateArgs.arguments()));
10889 assert((!isDependentSpecialization ||
10890 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10891 "dependent friend function specialization without template "
10892 "args");
10893 } else {
10894 // For class-scope explicit specializations of function templates,
10895 // if the lexical context is dependent, then the specialization
10896 // is dependent.
10897 isDependentSpecialization =
10898 CurContext->isRecord() && CurContext->isDependentContext();
10899 }
10900
10901 TemplateArgumentListInfo *ExplicitTemplateArgs =
10902 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10903 if (isDependentSpecialization) {
10904 // If it's a dependent specialization, it may not be possible
10905 // to determine the primary template (for explicit specializations)
10906 // or befriended declaration (for friends) until the enclosing
10907 // template is instantiated. In such cases, we store the declarations
10908 // found by name lookup and defer resolution until instantiation.
10910 NewFD, ExplicitTemplateArgs, Previous))
10911 NewFD->setInvalidDecl();
10912 } else if (!NewFD->isInvalidDecl()) {
10913 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10914 Previous))
10915 NewFD->setInvalidDecl();
10916 }
10917 } else if (isMemberSpecialization && !FunctionTemplate) {
10919 NewFD->setInvalidDecl();
10920 }
10921
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
10937 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10938 !D.isRedeclaration() ||
10939 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10940 "previous declaration set still overloaded");
10941
10942 NamedDecl *PrincipalDecl = (FunctionTemplate
10944 : NewFD);
10945
10946 if (isFriend && NewFD->getPreviousDecl()) {
10947 AccessSpecifier Access = AS_public;
10948 if (!NewFD->isInvalidDecl())
10949 Access = NewFD->getPreviousDecl()->getAccess();
10950
10951 NewFD->setAccess(Access);
10952 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10953 }
10954
10955 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10957 PrincipalDecl->setNonMemberOperator();
10958
10959 // If we have a function template, check the template parameter
10960 // list. This will check and merge default template arguments.
10961 if (FunctionTemplate) {
10962 FunctionTemplateDecl *PrevTemplate =
10963 FunctionTemplate->getPreviousDecl();
10964 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10965 PrevTemplate ? PrevTemplate->getTemplateParameters()
10966 : nullptr,
10971 : (D.getCXXScopeSpec().isSet() &&
10972 DC && DC->isRecord() &&
10973 DC->isDependentContext())
10976 }
10977
10978 if (NewFD->isInvalidDecl()) {
10979 // Ignore all the rest of this.
10980 } else if (!D.isRedeclaration()) {
10981 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10982 AddToScope };
10983 // Fake up an access specifier if it's supposed to be a class member.
10984 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10985 NewFD->setAccess(AS_public);
10986
10987 // Qualified decls generally require a previous declaration.
10988 if (D.getCXXScopeSpec().isSet()) {
10989 // ...with the major exception of templated-scope or
10990 // dependent-scope friend declarations.
10991
10992 // TODO: we currently also suppress this check in dependent
10993 // contexts because (1) the parameter depth will be off when
10994 // matching friend templates and (2) we might actually be
10995 // selecting a friend based on a dependent factor. But there
10996 // are situations where these conditions don't apply and we
10997 // can actually do this check immediately.
10998 //
10999 // Unless the scope is dependent, it's always an error if qualified
11000 // redeclaration lookup found nothing at all. Diagnose that now;
11001 // nothing will diagnose that error later.
11002 if (isFriend &&
11004 (!Previous.empty() && CurContext->isDependentContext()))) {
11005 // ignore these
11006 } else if (NewFD->isCPUDispatchMultiVersion() ||
11007 NewFD->isCPUSpecificMultiVersion()) {
11008 // ignore this, we allow the redeclaration behavior here to create new
11009 // versions of the function.
11010 } else {
11011 // The user tried to provide an out-of-line definition for a
11012 // function that is a member of a class or namespace, but there
11013 // was no such member function declared (C++ [class.mfct]p2,
11014 // C++ [namespace.memdef]p2). For example:
11015 //
11016 // class X {
11017 // void f() const;
11018 // };
11019 //
11020 // void X::f() { } // ill-formed
11021 //
11022 // Complain about this problem, and attempt to suggest close
11023 // matches (e.g., those that differ only in cv-qualifiers and
11024 // whether the parameter types are references).
11025
11027 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
11028 AddToScope = ExtraArgs.AddToScope;
11029 return Result;
11030 }
11031 }
11032
11033 // Unqualified local friend declarations are required to resolve
11034 // to something.
11035 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
11037 *this, Previous, NewFD, ExtraArgs, true, S)) {
11038 AddToScope = ExtraArgs.AddToScope;
11039 return Result;
11040 }
11041 }
11042 } else if (!D.isFunctionDefinition() &&
11043 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
11044 !isFriend && !isFunctionTemplateSpecialization &&
11045 !isMemberSpecialization) {
11046 // An out-of-line member function declaration must also be a
11047 // definition (C++ [class.mfct]p2).
11048 // Note that this is not the case for explicit specializations of
11049 // function templates or member functions of class templates, per
11050 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11051 // extension for compatibility with old SWIG code which likes to
11052 // generate them.
11053 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
11054 << D.getCXXScopeSpec().getRange();
11055 }
11056 }
11057
11058 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11059 // Any top level function could potentially be specified as an entry.
11060 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11061 HLSL().ActOnTopLevelFunction(NewFD);
11062
11063 if (NewFD->hasAttr<HLSLShaderAttr>())
11064 HLSL().CheckEntryPoint(NewFD);
11065
11066 // Resources cannot be passed to functions that are not inlined.
11067 if (const NoInlineAttr *NoInline = NewFD->getAttr<NoInlineAttr>()) {
11068 for (const ParmVarDecl *PVD : NewFD->parameters()) {
11069 QualType ParamTy = PVD->getType().getNonReferenceType();
11070 QualType EltTy = Context.getBaseElementType(ParamTy);
11071 // `isCompleteType` forces completion of the element type without
11072 // reporting an error (diagnosed elsewhere) so the resource parameter
11073 // check is valid.
11074 if (!EltTy->isDependentType() &&
11075 isCompleteType(PVD->getLocation(), EltTy) &&
11076 ParamTy->isHLSLIntangibleType()) {
11077 Diag(PVD->getLocation(),
11078 diag::err_hlsl_resource_param_in_noinline_function)
11079 << ParamTy;
11080 Diag(NoInline->getLocation(), diag::note_attribute);
11081 }
11082 }
11083 }
11084 }
11085
11086 // If this is the first declaration of a library builtin function, add
11087 // attributes as appropriate.
11088 if (!D.isRedeclaration()) {
11089 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11090 if (unsigned BuiltinID = II->getBuiltinID()) {
11091 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
11092 if (!InStdNamespace &&
11094 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11095 // Validate the type matches unless this builtin is specified as
11096 // matching regardless of its declared type.
11097 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
11098 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11099 } else {
11101 LookupNecessaryTypesForBuiltin(S, BuiltinID);
11102 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
11103
11104 if (!Error && !BuiltinType.isNull() &&
11105 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11106 NewFD->getType(), BuiltinType))
11107 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11108 }
11109 }
11110 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11111 isStdBuiltin(Context, NewFD, BuiltinID)) {
11112 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11113 }
11114 }
11115 }
11116 }
11117
11118 ProcessPragmaWeak(S, NewFD);
11119 ProcessPragmaExport(NewFD);
11120 checkAttributesAfterMerging(*this, *NewFD);
11121
11123 // The above can add the format attribute for known builtin/library functions
11124 // which is required by the modular_format attribute, thus
11125 // validate modular_format now after those attributes have been added.
11126 checkModularFormatAttr(*this, *NewFD);
11127
11128 if (NewFD->hasAttr<OverloadableAttr>() &&
11129 !NewFD->getType()->getAs<FunctionProtoType>()) {
11130 Diag(NewFD->getLocation(),
11131 diag::err_attribute_overloadable_no_prototype)
11132 << NewFD;
11133 NewFD->dropAttr<OverloadableAttr>();
11134 }
11135
11136 // If there's a #pragma GCC visibility in scope, and this isn't a class
11137 // member, set the visibility of this function.
11138 if (!DC->isRecord() && NewFD->isExternallyVisible())
11140
11141 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11142 // marking the function.
11143 ObjC().AddCFAuditedAttribute(NewFD);
11144
11145 // If this is a function definition, check if we have to apply any
11146 // attributes (i.e. optnone and no_builtin) due to a pragma.
11147 if (D.isFunctionDefinition()) {
11148 AddRangeBasedOptnone(NewFD);
11150 AddSectionMSAllocText(NewFD);
11152 }
11153
11154 // If this is the first declaration of an extern C variable, update
11155 // the map of such variables.
11156 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11157 isIncompleteDeclExternC(*this, NewFD))
11159
11160 // Set this FunctionDecl's range up to the right paren.
11161 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11162
11163 if (D.isRedeclaration() && !Previous.empty()) {
11164 NamedDecl *Prev = Previous.getRepresentativeDecl();
11165 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11166 isMemberSpecialization ||
11167 isFunctionTemplateSpecialization,
11169 }
11170
11171 if (getLangOpts().CUDA) {
11172 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11173 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11175 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11176 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11178 Context.setcudaConfigureCallDecl(NewFD);
11179 }
11180 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11181 !NewFD->isInvalidDecl() &&
11183 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11184 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11186 Context.setcudaGetParameterBufferDecl(NewFD);
11187 }
11188 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11189 !NewFD->isInvalidDecl() &&
11191 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11192 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11194 Context.setcudaLaunchDeviceDecl(NewFD);
11195 }
11196 }
11197 }
11198
11200
11201 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11202 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11203 if (SC == SC_Static) {
11204 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11205 D.setInvalidType();
11206 }
11207
11208 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11209 if (!NewFD->getReturnType()->isVoidType()) {
11210 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11211 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11212 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11213 : FixItHint());
11214 D.setInvalidType();
11215 }
11216
11218 for (auto *Param : NewFD->parameters())
11219 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11220
11221 if (getLangOpts().OpenCLCPlusPlus) {
11222 if (DC->isRecord()) {
11223 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11224 D.setInvalidType();
11225 }
11226 if (FunctionTemplate) {
11227 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11228 D.setInvalidType();
11229 }
11230 }
11231 }
11232
11233 if (getLangOpts().CPlusPlus) {
11234 // Precalculate whether this is a friend function template with a constraint
11235 // that depends on an enclosing template, per [temp.friend]p9.
11236 if (isFriend && FunctionTemplate &&
11239
11240 // C++ [temp.friend]p9:
11241 // A friend function template with a constraint that depends on a
11242 // template parameter from an enclosing template shall be a definition.
11243 if (!D.isFunctionDefinition()) {
11244 Diag(NewFD->getBeginLoc(),
11245 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11246 NewFD->setInvalidDecl();
11247 }
11248 }
11249
11250 if (FunctionTemplate) {
11251 if (NewFD->isInvalidDecl())
11252 FunctionTemplate->setInvalidDecl();
11253 return FunctionTemplate;
11254 }
11255
11256 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11258 }
11259
11260 for (const ParmVarDecl *Param : NewFD->parameters()) {
11261 QualType PT = Param->getType();
11262
11263 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11264 // types.
11265 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11266 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11267 QualType ElemTy = PipeTy->getElementType();
11268 if (ElemTy->isPointerOrReferenceType()) {
11269 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11270 D.setInvalidType();
11271 }
11272 }
11273 }
11274 // WebAssembly tables can't be used as function parameters.
11275 if (Context.getTargetInfo().getTriple().isWasm()) {
11277 Diag(Param->getTypeSpecStartLoc(),
11278 diag::err_wasm_table_as_function_parameter);
11279 D.setInvalidType();
11280 }
11281 }
11282 }
11283
11284 // Diagnose availability attributes. Availability cannot be used on functions
11285 // that are run during load/unload.
11286 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11287 if (NewFD->hasAttr<ConstructorAttr>()) {
11288 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11289 << 1;
11290 NewFD->dropAttr<AvailabilityAttr>();
11291 }
11292 if (NewFD->hasAttr<DestructorAttr>()) {
11293 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11294 << 2;
11295 NewFD->dropAttr<AvailabilityAttr>();
11296 }
11297 }
11298
11299 // Diagnose no_builtin attribute on function declaration that are not a
11300 // definition.
11301 // FIXME: We should really be doing this in
11302 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11303 // the FunctionDecl and at this point of the code
11304 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11305 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11306 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11307 switch (D.getFunctionDefinitionKind()) {
11310 Diag(NBA->getLocation(),
11311 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11312 << NBA->getSpelling();
11313 break;
11315 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11316 << NBA->getSpelling();
11317 break;
11319 break;
11320 }
11321
11322 // Similar to no_builtin logic above, at this point of the code
11323 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11324 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11325 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11326 !NewFD->isInvalidDecl() &&
11328 ExternalDeclarations.push_back(NewFD);
11329
11330 // Used for a warning on the 'next' declaration when used with a
11331 // `routine(name)`.
11332 if (getLangOpts().OpenACC)
11334
11335 return NewFD;
11336}
11337
11338/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11339/// when __declspec(code_seg) "is applied to a class, all member functions of
11340/// the class and nested classes -- this includes compiler-generated special
11341/// member functions -- are put in the specified segment."
11342/// The actual behavior is a little more complicated. The Microsoft compiler
11343/// won't check outer classes if there is an active value from #pragma code_seg.
11344/// The CodeSeg is always applied from the direct parent but only from outer
11345/// classes when the #pragma code_seg stack is empty. See:
11346/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11347/// available since MS has removed the page.
11349 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11350 if (!Method)
11351 return nullptr;
11352 const CXXRecordDecl *Parent = Method->getParent();
11353 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11354 Attr *NewAttr = SAttr->clone(S.getASTContext());
11355 NewAttr->setImplicit(true);
11356 return NewAttr;
11357 }
11358
11359 // The Microsoft compiler won't check outer classes for the CodeSeg
11360 // when the #pragma code_seg stack is active.
11361 if (S.CodeSegStack.CurrentValue)
11362 return nullptr;
11363
11364 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11365 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11366 Attr *NewAttr = SAttr->clone(S.getASTContext());
11367 NewAttr->setImplicit(true);
11368 return NewAttr;
11369 }
11370 }
11371 return nullptr;
11372}
11373
11375 bool IsDefinition) {
11376 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11377 return A;
11378 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11379 CodeSegStack.CurrentValue)
11380 return SectionAttr::CreateImplicit(
11381 getASTContext(), CodeSegStack.CurrentValue->getString(),
11382 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11383 return nullptr;
11384}
11385
11387 QualType NewT, QualType OldT) {
11389 return true;
11390
11391 // For dependently-typed local extern declarations and friends, we can't
11392 // perform a correct type check in general until instantiation:
11393 //
11394 // int f();
11395 // template<typename T> void g() { T f(); }
11396 //
11397 // (valid if g() is only instantiated with T = int).
11398 if (NewT->isDependentType() &&
11399 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11400 return false;
11401
11402 // Similarly, if the previous declaration was a dependent local extern
11403 // declaration, we don't really know its type yet.
11404 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11405 return false;
11406
11407 return true;
11408}
11409
11412 return true;
11413
11414 // Don't chain dependent friend function definitions until instantiation, to
11415 // permit cases like
11416 //
11417 // void func();
11418 // template<typename T> class C1 { friend void func() {} };
11419 // template<typename T> class C2 { friend void func() {} };
11420 //
11421 // ... which is valid if only one of C1 and C2 is ever instantiated.
11422 //
11423 // FIXME: This need only apply to function definitions. For now, we proxy
11424 // this by checking for a file-scope function. We do not want this to apply
11425 // to friend declarations nominating member functions, because that gets in
11426 // the way of access checks.
11428 return false;
11429
11430 auto *VD = dyn_cast<ValueDecl>(D);
11431 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11432 return !VD || !PrevVD ||
11433 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11434 PrevVD->getType());
11435}
11436
11437/// Check the target or target_version attribute of the function for
11438/// MultiVersion validity.
11439///
11440/// Returns true if there was an error, false otherwise.
11441static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11442 const auto *TA = FD->getAttr<TargetAttr>();
11443 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11444
11445 assert((TA || TVA) && "Expecting target or target_version attribute");
11446
11448 enum ErrType { Feature = 0, Architecture = 1 };
11449
11450 if (TA) {
11451 ParsedTargetAttr ParseInfo =
11452 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11453 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11454 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11455 << Architecture << ParseInfo.CPU;
11456 return true;
11457 }
11458 for (const auto &Feat : ParseInfo.Features) {
11459 auto BareFeat = StringRef{Feat}.substr(1);
11460 if (Feat[0] == '-') {
11461 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11462 << Feature << ("no-" + BareFeat);
11463 return true;
11464 }
11465
11466 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11467 !TargetInfo.isValidFeatureName(BareFeat) ||
11468 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11469 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11470 << Feature << BareFeat;
11471 return true;
11472 }
11473 }
11474 }
11475
11476 if (TVA) {
11478 ParsedTargetAttr ParseInfo;
11479 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11480 ParseInfo =
11481 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11482 for (auto &Feat : ParseInfo.Features)
11483 Feats.push_back(StringRef{Feat}.substr(1));
11484 } else {
11485 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11486 TVA->getFeatures(Feats);
11487 }
11488 for (const auto &Feat : Feats) {
11489 if (!TargetInfo.validateCpuSupports(Feat)) {
11490 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11491 << Feature << Feat;
11492 return true;
11493 }
11494 }
11495 }
11496 return false;
11497}
11498
11499// Provide a white-list of attributes that are allowed to be combined with
11500// multiversion functions.
11502 MultiVersionKind MVKind) {
11503 // Note: this list/diagnosis must match the list in
11504 // checkMultiversionAttributesAllSame.
11505 switch (Kind) {
11506 default:
11507 return false;
11508 case attr::ArmLocallyStreaming:
11509 return MVKind == MultiVersionKind::TargetVersion ||
11511 case attr::Used:
11512 return MVKind == MultiVersionKind::Target;
11513 case attr::NonNull:
11514 case attr::NoThrow:
11515 return true;
11516 }
11517}
11518
11520 const FunctionDecl *FD,
11521 const FunctionDecl *CausedFD,
11522 MultiVersionKind MVKind) {
11523 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11524 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11525 << static_cast<unsigned>(MVKind) << A;
11526 if (CausedFD)
11527 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11528 return true;
11529 };
11530
11531 for (const Attr *A : FD->attrs()) {
11532 switch (A->getKind()) {
11533 case attr::CPUDispatch:
11534 case attr::CPUSpecific:
11535 if (MVKind != MultiVersionKind::CPUDispatch &&
11537 return Diagnose(S, A);
11538 break;
11539 case attr::Target:
11540 if (MVKind != MultiVersionKind::Target)
11541 return Diagnose(S, A);
11542 break;
11543 case attr::TargetVersion:
11544 if (MVKind != MultiVersionKind::TargetVersion &&
11546 return Diagnose(S, A);
11547 break;
11548 case attr::TargetClones:
11549 if (MVKind != MultiVersionKind::TargetClones &&
11551 return Diagnose(S, A);
11552 break;
11553 default:
11554 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11555 return Diagnose(S, A);
11556 break;
11557 }
11558 }
11559 return false;
11560}
11561
11563 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11564 const PartialDiagnostic &NoProtoDiagID,
11565 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11566 const PartialDiagnosticAt &NoSupportDiagIDAt,
11567 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11568 bool ConstexprSupported, bool CLinkageMayDiffer) {
11569 enum DoesntSupport {
11570 FuncTemplates = 0,
11571 VirtFuncs = 1,
11572 DeducedReturn = 2,
11573 Constructors = 3,
11574 Destructors = 4,
11575 DeletedFuncs = 5,
11576 DefaultedFuncs = 6,
11577 ConstexprFuncs = 7,
11578 ConstevalFuncs = 8,
11579 Lambda = 9,
11580 };
11581 enum Different {
11582 CallingConv = 0,
11583 ReturnType = 1,
11584 ConstexprSpec = 2,
11585 InlineSpec = 3,
11586 Linkage = 4,
11587 LanguageLinkage = 5,
11588 };
11589
11590 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11591 !OldFD->getType()->getAs<FunctionProtoType>()) {
11592 Diag(OldFD->getLocation(), NoProtoDiagID);
11593 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11594 return true;
11595 }
11596
11597 if (NoProtoDiagID.getDiagID() != 0 &&
11598 !NewFD->getType()->getAs<FunctionProtoType>())
11599 return Diag(NewFD->getLocation(), NoProtoDiagID);
11600
11601 if (!TemplatesSupported &&
11603 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11604 << FuncTemplates;
11605
11606 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11607 if (NewCXXFD->isVirtual())
11608 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11609 << VirtFuncs;
11610
11611 if (isa<CXXConstructorDecl>(NewCXXFD))
11612 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11613 << Constructors;
11614
11615 if (isa<CXXDestructorDecl>(NewCXXFD))
11616 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11617 << Destructors;
11618 }
11619
11620 if (NewFD->isDeleted())
11621 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11622 << DeletedFuncs;
11623
11624 if (NewFD->isDefaulted())
11625 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11626 << DefaultedFuncs;
11627
11628 if (!ConstexprSupported && NewFD->isConstexpr())
11629 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11630 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11631
11632 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11633 const auto *NewType = cast<FunctionType>(NewQType);
11634 QualType NewReturnType = NewType->getReturnType();
11635
11636 if (NewReturnType->isUndeducedType())
11637 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11638 << DeducedReturn;
11639
11640 // Ensure the return type is identical.
11641 if (OldFD) {
11642 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11643 const auto *OldType = cast<FunctionType>(OldQType);
11644 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11645 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11646
11647 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11648 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11649
11650 bool ArmStreamingCCMismatched = false;
11651 if (OldFPT && NewFPT) {
11652 unsigned Diff =
11653 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11654 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11655 // cannot be mixed.
11658 ArmStreamingCCMismatched = true;
11659 }
11660
11661 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11662 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11663
11664 QualType OldReturnType = OldType->getReturnType();
11665
11666 if (OldReturnType != NewReturnType)
11667 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11668
11669 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11670 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11671
11672 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11673 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11674
11675 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11676 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11677
11678 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11679 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11680
11681 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11682 NewFD->getLocation()))
11683 return true;
11684 }
11685 return false;
11686}
11687
11689 const FunctionDecl *NewFD,
11690 bool CausesMV,
11691 MultiVersionKind MVKind) {
11693 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11694 if (OldFD)
11695 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11696 return true;
11697 }
11698
11699 bool IsCPUSpecificCPUDispatchMVKind =
11702
11703 if (CausesMV && OldFD &&
11704 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11705 return true;
11706
11707 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11708 return true;
11709
11710 // Only allow transition to MultiVersion if it hasn't been used.
11711 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11712 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11713 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11714 return true;
11715 }
11716
11718 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11720 S.PDiag(diag::note_multiversioning_caused_here)),
11722 S.PDiag(diag::err_multiversion_doesnt_support)
11723 << static_cast<unsigned>(MVKind)),
11725 S.PDiag(diag::err_multiversion_diff)),
11726 /*TemplatesSupported=*/false,
11727 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11728 /*CLinkageMayDiffer=*/false);
11729}
11730
11731/// Check the validity of a multiversion function declaration that is the
11732/// first of its kind. Also sets the multiversion'ness' of the function itself.
11733///
11734/// This sets NewFD->isInvalidDecl() to true if there was an error.
11735///
11736/// Returns true if there was an error, false otherwise.
11739 assert(MVKind != MultiVersionKind::None &&
11740 "Function lacks multiversion attribute");
11741 const auto *TA = FD->getAttr<TargetAttr>();
11742 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11743 // The target attribute only causes MV if this declaration is the default,
11744 // otherwise it is treated as a normal function.
11745 if (TA && !TA->isDefaultVersion())
11746 return false;
11747
11748 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11749 FD->setInvalidDecl();
11750 return true;
11751 }
11752
11753 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11754 FD->setInvalidDecl();
11755 return true;
11756 }
11757
11758 FD->setIsMultiVersion();
11759 return false;
11760}
11761
11763 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11765 return true;
11766 }
11767
11768 return false;
11769}
11770
11772 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11773 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11774 return;
11775
11776 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11777 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11778
11779 if (MVKindTo == MultiVersionKind::None &&
11780 (MVKindFrom == MultiVersionKind::TargetVersion ||
11781 MVKindFrom == MultiVersionKind::TargetClones))
11782 To->addAttr(TargetVersionAttr::CreateImplicit(
11783 To->getASTContext(), "default", To->getSourceRange()));
11784}
11785
11787 FunctionDecl *NewFD,
11788 bool &Redeclaration,
11789 NamedDecl *&OldDecl,
11791 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11792
11793 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11794 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11795 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11796 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11797
11798 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11799
11800 // The definitions should be allowed in any order. If we have discovered
11801 // a new target version and the preceeding was the default, then add the
11802 // corresponding attribute to it.
11803 patchDefaultTargetVersion(NewFD, OldFD);
11804
11805 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11806 // to change, this is a simple redeclaration.
11807 if (NewTA && !NewTA->isDefaultVersion() &&
11808 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11809 return false;
11810
11811 // Otherwise, this decl causes MultiVersioning.
11812 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11815 NewFD->setInvalidDecl();
11816 return true;
11817 }
11818
11819 if (CheckMultiVersionValue(S, NewFD)) {
11820 NewFD->setInvalidDecl();
11821 return true;
11822 }
11823
11824 // If this is 'default', permit the forward declaration.
11825 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11826 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11827 Redeclaration = true;
11828 OldDecl = OldFD;
11829 OldFD->setIsMultiVersion();
11830 NewFD->setIsMultiVersion();
11831 return false;
11832 }
11833
11834 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11835 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11836 NewFD->setInvalidDecl();
11837 return true;
11838 }
11839
11840 if (NewTA) {
11841 ParsedTargetAttr OldParsed =
11843 OldTA->getFeaturesStr());
11844 llvm::sort(OldParsed.Features);
11845 ParsedTargetAttr NewParsed =
11847 NewTA->getFeaturesStr());
11848 // Sort order doesn't matter, it just needs to be consistent.
11849 llvm::sort(NewParsed.Features);
11850 if (OldParsed == NewParsed) {
11851 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11852 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11853 NewFD->setInvalidDecl();
11854 return true;
11855 }
11856 }
11857
11858 for (const auto *FD : OldFD->redecls()) {
11859 const auto *CurTA = FD->getAttr<TargetAttr>();
11860 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11861 // We allow forward declarations before ANY multiversioning attributes, but
11862 // nothing after the fact.
11864 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11865 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11866 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11867 << (NewTA ? 0 : 2);
11868 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11869 NewFD->setInvalidDecl();
11870 return true;
11871 }
11872 }
11873
11874 OldFD->setIsMultiVersion();
11875 NewFD->setIsMultiVersion();
11876 Redeclaration = false;
11877 OldDecl = nullptr;
11878 Previous.clear();
11879 return false;
11880}
11881
11883 MultiVersionKind OldKind = Old->getMultiVersionKind();
11884 MultiVersionKind NewKind = New->getMultiVersionKind();
11885
11886 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11887 NewKind == MultiVersionKind::None)
11888 return true;
11889
11890 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11891 switch (OldKind) {
11893 return NewKind == MultiVersionKind::TargetClones;
11895 return NewKind == MultiVersionKind::TargetVersion;
11896 default:
11897 return false;
11898 }
11899 } else {
11900 switch (OldKind) {
11902 return NewKind == MultiVersionKind::CPUSpecific;
11904 return NewKind == MultiVersionKind::CPUDispatch;
11905 default:
11906 return false;
11907 }
11908 }
11909}
11910
11911/// Check the validity of a new function declaration being added to an existing
11912/// multiversioned declaration collection.
11914 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11915 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11916 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11918
11919 // Disallow mixing of multiversioning types.
11920 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11921 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11922 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11923 NewFD->setInvalidDecl();
11924 return true;
11925 }
11926
11927 // Add the default target_version attribute if it's missing.
11928 patchDefaultTargetVersion(OldFD, NewFD);
11929 patchDefaultTargetVersion(NewFD, OldFD);
11930
11931 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11932 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11933 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11934 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11935
11936 ParsedTargetAttr NewParsed;
11937 if (NewTA) {
11939 NewTA->getFeaturesStr());
11940 llvm::sort(NewParsed.Features);
11941 }
11943 if (NewTVA) {
11944 NewTVA->getFeatures(NewFeats);
11945 llvm::sort(NewFeats);
11946 }
11947
11948 bool UseMemberUsingDeclRules =
11949 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11950
11951 bool MayNeedOverloadableChecks =
11953
11954 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11955 // of a previous member of the MultiVersion set.
11956 for (NamedDecl *ND : Previous) {
11957 FunctionDecl *CurFD = ND->getAsFunction();
11958 if (!CurFD || CurFD->isInvalidDecl())
11959 continue;
11960 if (MayNeedOverloadableChecks &&
11961 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11962 continue;
11963
11964 switch (NewMVKind) {
11966 assert(OldMVKind == MultiVersionKind::TargetClones &&
11967 "Only target_clones can be omitted in subsequent declarations");
11968 break;
11970 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11971 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11972 NewFD->setIsMultiVersion();
11973 Redeclaration = true;
11974 OldDecl = ND;
11975 return false;
11976 }
11977
11978 ParsedTargetAttr CurParsed =
11980 CurTA->getFeaturesStr());
11981 llvm::sort(CurParsed.Features);
11982 if (CurParsed == NewParsed) {
11983 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11984 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11985 NewFD->setInvalidDecl();
11986 return true;
11987 }
11988 break;
11989 }
11991 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11992 if (CurTVA->getName() == NewTVA->getName()) {
11993 NewFD->setIsMultiVersion();
11994 Redeclaration = true;
11995 OldDecl = ND;
11996 return false;
11997 }
11999 CurTVA->getFeatures(CurFeats);
12000 llvm::sort(CurFeats);
12001
12002 if (CurFeats == NewFeats) {
12003 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12004 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12005 NewFD->setInvalidDecl();
12006 return true;
12007 }
12008 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12009 // Default
12010 if (NewFeats.empty())
12011 break;
12012
12013 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
12015 CurClones->getFeatures(CurFeats, I);
12016 llvm::sort(CurFeats);
12017
12018 if (CurFeats == NewFeats) {
12019 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12020 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12021 NewFD->setInvalidDecl();
12022 return true;
12023 }
12024 }
12025 }
12026 break;
12027 }
12029 assert(NewClones && "MultiVersionKind does not match attribute type");
12030 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12031 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
12032 !std::equal(CurClones->featuresStrs_begin(),
12033 CurClones->featuresStrs_end(),
12034 NewClones->featuresStrs_begin())) {
12035 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
12036 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12037 NewFD->setInvalidDecl();
12038 return true;
12039 }
12040 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12042 CurTVA->getFeatures(CurFeats);
12043 llvm::sort(CurFeats);
12044
12045 // Default
12046 if (CurFeats.empty())
12047 break;
12048
12049 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12050 NewFeats.clear();
12051 NewClones->getFeatures(NewFeats, I);
12052 llvm::sort(NewFeats);
12053
12054 if (CurFeats == NewFeats) {
12055 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12056 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12057 NewFD->setInvalidDecl();
12058 return true;
12059 }
12060 }
12061 break;
12062 }
12063 Redeclaration = true;
12064 OldDecl = CurFD;
12065 NewFD->setIsMultiVersion();
12066 return false;
12067 }
12070 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12071 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12072 // Handle CPUDispatch/CPUSpecific versions.
12073 // Only 1 CPUDispatch function is allowed, this will make it go through
12074 // the redeclaration errors.
12075 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12076 CurFD->hasAttr<CPUDispatchAttr>()) {
12077 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12078 std::equal(
12079 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
12080 NewCPUDisp->cpus_begin(),
12081 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12082 return Cur->getName() == New->getName();
12083 })) {
12084 NewFD->setIsMultiVersion();
12085 Redeclaration = true;
12086 OldDecl = ND;
12087 return false;
12088 }
12089
12090 // If the declarations don't match, this is an error condition.
12091 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
12092 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12093 NewFD->setInvalidDecl();
12094 return true;
12095 }
12096 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12097 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12098 std::equal(
12099 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
12100 NewCPUSpec->cpus_begin(),
12101 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12102 return Cur->getName() == New->getName();
12103 })) {
12104 NewFD->setIsMultiVersion();
12105 Redeclaration = true;
12106 OldDecl = ND;
12107 return false;
12108 }
12109
12110 // Only 1 version of CPUSpecific is allowed for each CPU.
12111 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12112 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12113 if (CurII == NewII) {
12114 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12115 << NewII;
12116 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12117 NewFD->setInvalidDecl();
12118 return true;
12119 }
12120 }
12121 }
12122 }
12123 break;
12124 }
12125 }
12126 }
12127
12128 // Redeclarations of a target_clones function may omit the attribute, in which
12129 // case it will be inherited during declaration merging.
12130 if (NewMVKind == MultiVersionKind::None &&
12131 OldMVKind == MultiVersionKind::TargetClones) {
12132 NewFD->setIsMultiVersion();
12133 Redeclaration = true;
12134 OldDecl = OldFD;
12135 return false;
12136 }
12137
12138 // Else, this is simply a non-redecl case. Checking the 'value' is only
12139 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12140 // handled in the attribute adding step.
12141 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12142 NewFD->setInvalidDecl();
12143 return true;
12144 }
12145
12146 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12147 !OldFD->isMultiVersion(), NewMVKind)) {
12148 NewFD->setInvalidDecl();
12149 return true;
12150 }
12151
12152 // Permit forward declarations in the case where these two are compatible.
12153 if (!OldFD->isMultiVersion()) {
12154 OldFD->setIsMultiVersion();
12155 NewFD->setIsMultiVersion();
12156 Redeclaration = true;
12157 OldDecl = OldFD;
12158 return false;
12159 }
12160
12161 NewFD->setIsMultiVersion();
12162 Redeclaration = false;
12163 OldDecl = nullptr;
12164 Previous.clear();
12165 return false;
12166}
12167
12168/// Check the validity of a mulitversion function declaration.
12169/// Also sets the multiversion'ness' of the function itself.
12170///
12171/// This sets NewFD->isInvalidDecl() to true if there was an error.
12172///
12173/// Returns true if there was an error, false otherwise.
12175 bool &Redeclaration, NamedDecl *&OldDecl,
12177 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12178
12179 // Check if FMV is disabled.
12180 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12181 return false;
12182
12183 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12184 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12185 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12186 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12187 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12188 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12189
12190 // Main isn't allowed to become a multiversion function, however it IS
12191 // permitted to have 'main' be marked with the 'target' optimization hint,
12192 // for 'target_version' only default is allowed.
12193 if (NewFD->isMain()) {
12194 if (MVKind != MultiVersionKind::None &&
12195 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12196 !(MVKind == MultiVersionKind::TargetVersion &&
12197 NewTVA->isDefaultVersion())) {
12198 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12199 NewFD->setInvalidDecl();
12200 return true;
12201 }
12202 return false;
12203 }
12204
12205 // Target attribute on AArch64 is not used for multiversioning
12206 if (NewTA && TI.getTriple().isAArch64())
12207 return false;
12208
12209 // Target attribute on RISCV is not used for multiversioning
12210 if (NewTA && TI.getTriple().isRISCV())
12211 return false;
12212
12213 if (!OldDecl || !OldDecl->getAsFunction() ||
12214 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12215 NewFD->getDeclContext()->getRedeclContext())) {
12216 // If there's no previous declaration, AND this isn't attempting to cause
12217 // multiversioning, this isn't an error condition.
12218 if (MVKind == MultiVersionKind::None)
12219 return false;
12220 return CheckMultiVersionFirstFunction(S, NewFD);
12221 }
12222
12223 FunctionDecl *OldFD = OldDecl->getAsFunction();
12224
12225 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12226 return false;
12227
12228 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12229 // for target_clones and target_version.
12230 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12233 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12235 NewFD->setInvalidDecl();
12236 return true;
12237 }
12238
12239 if (!OldFD->isMultiVersion()) {
12240 switch (MVKind) {
12244 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12246 if (OldFD->isUsed(false)) {
12247 NewFD->setInvalidDecl();
12248 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12249 }
12250 OldFD->setIsMultiVersion();
12251 break;
12252
12256 break;
12257 }
12258 }
12259
12260 // At this point, we have a multiversion function decl (in OldFD) AND an
12261 // appropriate attribute in the current function decl (unless it's allowed to
12262 // omit the attribute). Resolve that these are still compatible with previous
12263 // declarations.
12264 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12265 NewCPUSpec, NewClones, Redeclaration,
12266 OldDecl, Previous);
12267}
12268
12270 bool IsPure = NewFD->hasAttr<PureAttr>();
12271 bool IsConst = NewFD->hasAttr<ConstAttr>();
12272
12273 // If there are no pure or const attributes, there's nothing to check.
12274 if (!IsPure && !IsConst)
12275 return;
12276
12277 // If the function is marked both pure and const, we retain the const
12278 // attribute because it makes stronger guarantees than the pure attribute, and
12279 // we drop the pure attribute explicitly to prevent later confusion about
12280 // semantics.
12281 if (IsPure && IsConst) {
12282 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12283 NewFD->dropAttrs<PureAttr>();
12284 }
12285
12286 // Constructors and destructors are functions which return void, so are
12287 // handled here as well.
12288 if (NewFD->getReturnType()->isVoidType()) {
12289 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12290 << IsConst;
12291 NewFD->dropAttrs<PureAttr, ConstAttr>();
12292 }
12293}
12294
12297 bool IsMemberSpecialization,
12298 bool DeclIsDefn) {
12299 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12300 "Variably modified return types are not handled here");
12301
12302 // Determine whether the type of this function should be merged with
12303 // a previous visible declaration. This never happens for functions in C++,
12304 // and always happens in C if the previous declaration was visible.
12305 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12306 !Previous.isShadowed();
12307
12308 bool Redeclaration = false;
12309 NamedDecl *OldDecl = nullptr;
12310 bool MayNeedOverloadableChecks = false;
12311
12313 // Merge or overload the declaration with an existing declaration of
12314 // the same name, if appropriate.
12315 if (!Previous.empty()) {
12316 // Determine whether NewFD is an overload of PrevDecl or
12317 // a declaration that requires merging. If it's an overload,
12318 // there's no more work to do here; we'll just add the new
12319 // function to the scope.
12321 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12322 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12323 Redeclaration = true;
12324 OldDecl = Candidate;
12325 }
12326 } else {
12327 MayNeedOverloadableChecks = true;
12328 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12329 /*NewIsUsingDecl*/ false)) {
12331 Redeclaration = true;
12332 break;
12333
12335 Redeclaration = true;
12336 break;
12337
12339 Redeclaration = false;
12340 break;
12341 }
12342 }
12343 }
12344
12345 // Check for a previous extern "C" declaration with this name.
12346 if (!Redeclaration &&
12348 if (!Previous.empty()) {
12349 // This is an extern "C" declaration with the same name as a previous
12350 // declaration, and thus redeclares that entity...
12351 Redeclaration = true;
12352 OldDecl = Previous.getFoundDecl();
12353 MergeTypeWithPrevious = false;
12354
12355 // ... except in the presence of __attribute__((overloadable)).
12356 if (OldDecl->hasAttr<OverloadableAttr>() ||
12357 NewFD->hasAttr<OverloadableAttr>()) {
12358 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12359 MayNeedOverloadableChecks = true;
12360 Redeclaration = false;
12361 OldDecl = nullptr;
12362 }
12363 }
12364 }
12365 }
12366
12367 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12368 return Redeclaration;
12369
12370 // PPC MMA non-pointer types are not allowed as function return types.
12371 if (Context.getTargetInfo().getTriple().isPPC64() &&
12372 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12373 NewFD->setInvalidDecl();
12374 }
12375
12376 CheckConstPureAttributesUsage(*this, NewFD);
12377
12378 // C++ [dcl.spec.auto.general]p12:
12379 // Return type deduction for a templated function with a placeholder in its
12380 // declared type occurs when the definition is instantiated even if the
12381 // function body contains a return statement with a non-type-dependent
12382 // operand.
12383 //
12384 // C++ [temp.dep.expr]p3:
12385 // An id-expression is type-dependent if it is a template-id that is not a
12386 // concept-id and is dependent; or if its terminal name is:
12387 // - [...]
12388 // - associated by name lookup with one or more declarations of member
12389 // functions of a class that is the current instantiation declared with a
12390 // return type that contains a placeholder type,
12391 // - [...]
12392 //
12393 // If this is a templated function with a placeholder in its return type,
12394 // make the placeholder type dependent since it won't be deduced until the
12395 // definition is instantiated. We do this here because it needs to happen
12396 // for implicitly instantiated member functions/member function templates.
12397 if (getLangOpts().CPlusPlus14 &&
12398 (NewFD->isDependentContext() &&
12399 NewFD->getReturnType()->isUndeducedType())) {
12400 const FunctionProtoType *FPT =
12401 NewFD->getType()->castAs<FunctionProtoType>();
12402 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12403 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12404 FPT->getExtProtoInfo()));
12405 }
12406
12407 // C++11 [dcl.constexpr]p8:
12408 // A constexpr specifier for a non-static member function that is not
12409 // a constructor declares that member function to be const.
12410 //
12411 // This needs to be delayed until we know whether this is an out-of-line
12412 // definition of a static member function.
12413 //
12414 // This rule is not present in C++1y, so we produce a backwards
12415 // compatibility warning whenever it happens in C++11.
12416 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12417 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12418 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12420 CXXMethodDecl *OldMD = nullptr;
12421 if (OldDecl)
12422 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12423 if (!OldMD || !OldMD->isStatic()) {
12424 const FunctionProtoType *FPT =
12427 EPI.TypeQuals.addConst();
12428 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12429 FPT->getParamTypes(), EPI));
12430
12431 // Warn that we did this, if we're not performing template instantiation.
12432 // In that case, we'll have warned already when the template was defined.
12433 if (!inTemplateInstantiation()) {
12434 SourceLocation AddConstLoc;
12437 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12438
12439 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12440 << FixItHint::CreateInsertion(AddConstLoc, " const");
12441 }
12442 }
12443 }
12444
12445 if (Redeclaration) {
12446 // NewFD and OldDecl represent declarations that need to be
12447 // merged.
12448 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12449 DeclIsDefn)) {
12450 NewFD->setInvalidDecl();
12451 return Redeclaration;
12452 }
12453
12454 Previous.clear();
12455 Previous.addDecl(OldDecl);
12456
12457 if (FunctionTemplateDecl *OldTemplateDecl =
12458 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12459 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12460 FunctionTemplateDecl *NewTemplateDecl
12462 assert(NewTemplateDecl && "Template/non-template mismatch");
12463
12464 // The call to MergeFunctionDecl above may have created some state in
12465 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12466 // can add it as a redeclaration.
12467 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12468
12469 NewFD->setPreviousDeclaration(OldFD);
12470 if (NewFD->isCXXClassMember()) {
12471 NewFD->setAccess(OldTemplateDecl->getAccess());
12472 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12473 }
12474
12475 // If this is an explicit specialization of a member that is a function
12476 // template, mark it as a member specialization.
12477 if (IsMemberSpecialization &&
12478 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12479 NewTemplateDecl->setMemberSpecialization();
12480 assert(OldTemplateDecl->isMemberSpecialization());
12481 // Explicit specializations of a member template do not inherit deleted
12482 // status from the parent member template that they are specializing.
12483 if (OldFD->isDeleted()) {
12484 // FIXME: This assert will not hold in the presence of modules.
12485 assert(OldFD->getCanonicalDecl() == OldFD);
12486 // FIXME: We need an update record for this AST mutation.
12487 OldFD->setDeletedAsWritten(false);
12488 }
12489 }
12490
12491 } else {
12492 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12493 auto *OldFD = cast<FunctionDecl>(OldDecl);
12494 // This needs to happen first so that 'inline' propagates.
12495 NewFD->setPreviousDeclaration(OldFD);
12496 if (NewFD->isCXXClassMember())
12497 NewFD->setAccess(OldFD->getAccess());
12498 }
12499 }
12500 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12501 !NewFD->getAttr<OverloadableAttr>()) {
12502 assert((Previous.empty() ||
12503 llvm::any_of(Previous,
12504 [](const NamedDecl *ND) {
12505 return ND->hasAttr<OverloadableAttr>();
12506 })) &&
12507 "Non-redecls shouldn't happen without overloadable present");
12508
12509 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12510 const auto *FD = dyn_cast<FunctionDecl>(ND);
12511 return FD && !FD->hasAttr<OverloadableAttr>();
12512 });
12513
12514 if (OtherUnmarkedIter != Previous.end()) {
12515 Diag(NewFD->getLocation(),
12516 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12517 Diag((*OtherUnmarkedIter)->getLocation(),
12518 diag::note_attribute_overloadable_prev_overload)
12519 << false;
12520
12521 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12522 }
12523 }
12524
12525 if (LangOpts.OpenMP)
12527
12528 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12530
12531 if (NewFD->hasAttr<SYCLExternalAttr>())
12533
12534 // Semantic checking for this function declaration (in isolation).
12535
12536 if (getLangOpts().CPlusPlus) {
12537 // C++-specific checks.
12538 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12540 } else if (CXXDestructorDecl *Destructor =
12541 dyn_cast<CXXDestructorDecl>(NewFD)) {
12542 // We check here for invalid destructor names.
12543 // If we have a friend destructor declaration that is dependent, we can't
12544 // diagnose right away because cases like this are still valid:
12545 // template <class T> struct A { friend T::X::~Y(); };
12546 // struct B { struct Y { ~Y(); }; using X = Y; };
12547 // template struct A<B>;
12549 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12550 CanQualType ClassType =
12551 Context.getCanonicalTagType(Destructor->getParent());
12552
12553 DeclarationName Name =
12554 Context.DeclarationNames.getCXXDestructorName(ClassType);
12555 if (NewFD->getDeclName() != Name) {
12556 Diag(NewFD->getLocation(), diag::err_destructor_name);
12557 NewFD->setInvalidDecl();
12558 return Redeclaration;
12559 }
12560 }
12561 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12562 if (auto *TD = Guide->getDescribedFunctionTemplate())
12564
12565 // A deduction guide is not on the list of entities that can be
12566 // explicitly specialized.
12567 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12568 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12569 << /*explicit specialization*/ 1;
12570 }
12571
12572 // Find any virtual functions that this function overrides.
12573 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12574 if (!Method->isFunctionTemplateSpecialization() &&
12575 !Method->getDescribedFunctionTemplate() &&
12576 Method->isCanonicalDecl()) {
12577 AddOverriddenMethods(Method->getParent(), Method);
12578 }
12579 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12580 // C++2a [class.virtual]p6
12581 // A virtual method shall not have a requires-clause.
12583 diag::err_constrained_virtual_method);
12584
12585 if (Method->isStatic())
12587 }
12588
12589 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12590 ActOnConversionDeclarator(Conversion);
12591
12592 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12593 if (NewFD->isOverloadedOperator() &&
12595 NewFD->setInvalidDecl();
12596 return Redeclaration;
12597 }
12598
12599 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12600 if (NewFD->getLiteralIdentifier() &&
12602 NewFD->setInvalidDecl();
12603 return Redeclaration;
12604 }
12605
12606 // In C++, check default arguments now that we have merged decls. Unless
12607 // the lexical context is the class, because in this case this is done
12608 // during delayed parsing anyway.
12609 if (!CurContext->isRecord())
12611
12612 // If this function is declared as being extern "C", then check to see if
12613 // the function returns a UDT (class, struct, or union type) that is not C
12614 // compatible, and if it does, warn the user.
12615 // But, issue any diagnostic on the first declaration only.
12616 if (Previous.empty() && NewFD->isExternC()) {
12617 QualType R = NewFD->getReturnType();
12618 if (R->isIncompleteType() && !R->isVoidType())
12619 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12620 << NewFD << R;
12621 else if (!R.isPODType(Context) && !R->isVoidType() &&
12622 !R->isObjCObjectPointerType())
12623 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12624 }
12625
12626 // C++1z [dcl.fct]p6:
12627 // [...] whether the function has a non-throwing exception-specification
12628 // [is] part of the function type
12629 //
12630 // This results in an ABI break between C++14 and C++17 for functions whose
12631 // declared type includes an exception-specification in a parameter or
12632 // return type. (Exception specifications on the function itself are OK in
12633 // most cases, and exception specifications are not permitted in most other
12634 // contexts where they could make it into a mangling.)
12635 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12636 auto HasNoexcept = [&](QualType T) -> bool {
12637 // Strip off declarator chunks that could be between us and a function
12638 // type. We don't need to look far, exception specifications are very
12639 // restricted prior to C++17.
12640 if (auto *RT = T->getAs<ReferenceType>())
12641 T = RT->getPointeeType();
12642 else if (T->isAnyPointerType())
12643 T = T->getPointeeType();
12644 else if (auto *MPT = T->getAs<MemberPointerType>())
12645 T = MPT->getPointeeType();
12646 if (auto *FPT = T->getAs<FunctionProtoType>())
12647 if (FPT->isNothrow())
12648 return true;
12649 return false;
12650 };
12651
12652 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12653 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12654 for (QualType T : FPT->param_types())
12655 AnyNoexcept |= HasNoexcept(T);
12656 if (AnyNoexcept)
12657 Diag(NewFD->getLocation(),
12658 diag::warn_cxx17_compat_exception_spec_in_signature)
12659 << NewFD;
12660 }
12661
12662 if (!Redeclaration && LangOpts.CUDA) {
12663 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12664 for (auto *Parm : NewFD->parameters()) {
12665 if (!Parm->getType()->isDependentType() &&
12666 Parm->hasAttr<CUDAGridConstantAttr>() &&
12667 !(IsKernel && Parm->getType().isConstQualified()))
12668 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12669 diag::err_cuda_grid_constant_not_allowed);
12670 }
12672 }
12673 }
12674
12675 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12677
12678 return Redeclaration;
12679}
12680
12682 // [basic.start.main]p3
12683 // The main function shall not be declared with C linkage-specification.
12684 if (FD->isExternCContext())
12685 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12686
12687 // C++11 [basic.start.main]p3:
12688 // A program that [...] declares main to be inline, static or
12689 // constexpr is ill-formed.
12690 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12691 // appear in a declaration of main.
12692 // static main is not an error under C99, but we should warn about it.
12693 // We accept _Noreturn main as an extension.
12694 if (FD->getStorageClass() == SC_Static)
12696 ? diag::err_static_main : diag::warn_static_main)
12698 if (FD->isInlineSpecified())
12699 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12701 if (DS.isNoreturnSpecified()) {
12702 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12703 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12704 Diag(NoreturnLoc, diag::ext_noreturn_main);
12705 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12706 << FixItHint::CreateRemoval(NoreturnRange);
12707 }
12708 if (FD->isConstexpr()) {
12709 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12710 << FD->isConsteval()
12713 }
12714
12715 if (getLangOpts().OpenCL) {
12716 Diag(FD->getLocation(), diag::err_opencl_no_main)
12717 << FD->hasAttr<DeviceKernelAttr>();
12718 FD->setInvalidDecl();
12719 return;
12720 }
12721
12722 if (FD->hasAttr<SYCLExternalAttr>()) {
12723 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12724 << FD->getAttr<SYCLExternalAttr>();
12725 FD->setInvalidDecl();
12726 return;
12727 }
12728
12729 // Functions named main in hlsl are default entries, but don't have specific
12730 // signatures they are required to conform to.
12731 if (getLangOpts().HLSL)
12732 return;
12733
12734 QualType T = FD->getType();
12735 assert(T->isFunctionType() && "function decl is not of function type");
12736 const FunctionType* FT = T->castAs<FunctionType>();
12737
12738 // Set default calling convention for main()
12739 if (FT->getCallConv() != CC_C) {
12740 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12741 FD->setType(QualType(FT, 0));
12742 T = Context.getCanonicalType(FD->getType());
12743 }
12744
12746 // In C with GNU extensions we allow main() to have non-integer return
12747 // type, but we should warn about the extension, and we disable the
12748 // implicit-return-zero rule.
12749
12750 // GCC in C mode accepts qualified 'int'.
12751 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12752 FD->setHasImplicitReturnZero(true);
12753 else {
12754 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12755 SourceRange RTRange = FD->getReturnTypeSourceRange();
12756 if (RTRange.isValid())
12757 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12758 << FixItHint::CreateReplacement(RTRange, "int");
12759 }
12760 } else {
12761 // In C and C++, main magically returns 0 if you fall off the end;
12762 // set the flag which tells us that.
12763 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12764
12765 // All the standards say that main() should return 'int'.
12766 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12767 FD->setHasImplicitReturnZero(true);
12768 else {
12769 // Otherwise, this is just a flat-out error.
12770 SourceRange RTRange = FD->getReturnTypeSourceRange();
12771 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12772 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12773 : FixItHint());
12774 FD->setInvalidDecl(true);
12775 }
12776
12777 // [basic.start.main]p3:
12778 // A program that declares a function main that belongs to the global scope
12779 // and is attached to a named module is ill-formed.
12780 if (FD->isInNamedModule()) {
12781 const SourceLocation start = FD->getTypeSpecStartLoc();
12782 Diag(start, diag::warn_main_in_named_module)
12783 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12784 }
12785 }
12786
12787 // Treat protoless main() as nullary.
12788 if (isa<FunctionNoProtoType>(FT)) return;
12789
12791 unsigned nparams = FTP->getNumParams();
12792 assert(FD->getNumParams() == nparams);
12793
12794 bool HasExtraParameters = (nparams > 3);
12795
12796 if (FTP->isVariadic()) {
12797 Diag(FD->getLocation(), diag::ext_variadic_main);
12798 // FIXME: if we had information about the location of the ellipsis, we
12799 // could add a FixIt hint to remove it as a parameter.
12800 }
12801
12802 // Darwin passes an undocumented fourth argument of type char**. If
12803 // other platforms start sprouting these, the logic below will start
12804 // getting shifty.
12805 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12806 HasExtraParameters = false;
12807
12808 if (HasExtraParameters) {
12809 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12810 FD->setInvalidDecl(true);
12811 nparams = 3;
12812 }
12813
12814 // FIXME: a lot of the following diagnostics would be improved
12815 // if we had some location information about types.
12816
12817 QualType CharPP =
12818 Context.getPointerType(Context.getPointerType(Context.CharTy));
12819 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12820
12821 for (unsigned i = 0; i < nparams; ++i) {
12822 QualType AT = FTP->getParamType(i);
12823
12824 bool mismatch = true;
12825
12826 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12827 mismatch = false;
12828 else if (Expected[i] == CharPP) {
12829 // As an extension, the following forms are okay:
12830 // char const **
12831 // char const * const *
12832 // char * const *
12833
12835 const PointerType* PT;
12836 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12837 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12838 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12839 Context.CharTy)) {
12840 qs.removeConst();
12841 mismatch = !qs.empty();
12842 }
12843 }
12844
12845 if (mismatch) {
12846 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12847 // TODO: suggest replacing given type with expected type
12848 FD->setInvalidDecl(true);
12849 }
12850 }
12851
12852 if (nparams == 1 && !FD->isInvalidDecl()) {
12853 Diag(FD->getLocation(), diag::warn_main_one_arg);
12854 }
12855
12856 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12857 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12858 FD->setInvalidDecl();
12859 }
12860}
12861
12862static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12863
12864 // Default calling convention for main and wmain is __cdecl
12865 if (FD->getName() == "main" || FD->getName() == "wmain")
12866 return false;
12867
12868 // Default calling convention for MinGW and Cygwin is __cdecl
12869 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12870 if (T.isOSCygMing())
12871 return false;
12872
12873 // Default calling convention for WinMain, wWinMain and DllMain
12874 // is __stdcall on 32 bit Windows
12875 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12876 return true;
12877
12878 return false;
12879}
12880
12882 QualType T = FD->getType();
12883 assert(T->isFunctionType() && "function decl is not of function type");
12884 const FunctionType *FT = T->castAs<FunctionType>();
12885
12886 // Set an implicit return of 'zero' if the function can return some integral,
12887 // enumeration, pointer or nullptr type.
12891 // DllMain is exempt because a return value of zero means it failed.
12892 if (FD->getName() != "DllMain")
12893 FD->setHasImplicitReturnZero(true);
12894
12895 // Explicitly specified calling conventions are applied to MSVC entry points
12896 if (!hasExplicitCallingConv(T)) {
12897 if (isDefaultStdCall(FD, *this)) {
12898 if (FT->getCallConv() != CC_X86StdCall) {
12899 FT = Context.adjustFunctionType(
12901 FD->setType(QualType(FT, 0));
12902 }
12903 } else if (FT->getCallConv() != CC_C) {
12904 FT = Context.adjustFunctionType(FT,
12906 FD->setType(QualType(FT, 0));
12907 }
12908 }
12909
12910 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12911 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12912 FD->setInvalidDecl();
12913 }
12914}
12915
12917 // FIXME: Need strict checking. In C89, we need to check for
12918 // any assignment, increment, decrement, function-calls, or
12919 // commas outside of a sizeof. In C99, it's the same list,
12920 // except that the aforementioned are allowed in unevaluated
12921 // expressions. Everything else falls under the
12922 // "may accept other forms of constant expressions" exception.
12923 //
12924 // Regular C++ code will not end up here (exceptions: language extensions,
12925 // OpenCL C++ etc), so the constant expression rules there don't matter.
12926 if (Init->isValueDependent()) {
12927 assert(Init->containsErrors() &&
12928 "Dependent code should only occur in error-recovery path.");
12929 return true;
12930 }
12931 const Expr *Culprit;
12932 if (Init->isConstantInitializer(Context, /*ForRef=*/false, &Culprit))
12933 return false;
12934
12935 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
12936 if (getLangOpts().ObjCConstantLiterals && isa<ObjCObjectLiteral>(Culprit)) {
12937
12938 // For collection literals iterate the elements to highlight which one is
12939 // the offender.
12940 if (auto ALE = dyn_cast<ObjCArrayLiteral>(Init)) {
12941 for (auto *Elm : ALE->elements()) {
12942 if (!Elm->isConstantInitializer(Context)) {
12943 Diag(Elm->getExprLoc(),
12944 diag::err_objc_literal_nonconstant_at_file_scope)
12945 << ObjC().CheckLiteralKind(Init) << Elm->getSourceRange();
12946 return true;
12947 }
12948 }
12949 }
12950
12951 if (auto DLE = dyn_cast<ObjCDictionaryLiteral>(Init)) {
12952 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
12953 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(I);
12954
12955 // Check that the key is a string literal and is constant.
12956 if (!isa<ObjCStringLiteral>(Elm.Key) ||
12958 Diag(Elm.Key->getExprLoc(),
12959 diag::err_objc_literal_nonconstant_at_file_scope)
12961 return true;
12962 }
12963
12964 if (!Elm.Value->isConstantInitializer(Context)) {
12965 Diag(Elm.Value->getExprLoc(),
12966 diag::err_objc_literal_nonconstant_at_file_scope)
12968 return true;
12969 }
12970 }
12971 }
12972
12973 Diag(Culprit->getExprLoc(),
12974 diag::err_objc_literal_nonconstant_at_file_scope)
12975 << ObjC().CheckLiteralKind(Init) << Culprit->getSourceRange();
12976 return true;
12977 }
12978
12979 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12980 return true;
12981}
12982
12983namespace {
12984 // Visits an initialization expression to see if OrigDecl is evaluated in
12985 // its own initialization and throws a warning if it does.
12986 class SelfReferenceChecker
12987 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12988 Sema &S;
12989 Decl *OrigDecl;
12990 bool isRecordType;
12991 bool isPODType;
12992 bool isReferenceType;
12993 bool isInCXXOperatorCall;
12994
12995 bool isInitList;
12996 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12997
12998 public:
13000
13001 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
13002 S(S), OrigDecl(OrigDecl) {
13003 isPODType = false;
13004 isRecordType = false;
13005 isReferenceType = false;
13006 isInCXXOperatorCall = false;
13007 isInitList = false;
13008 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
13009 isPODType = VD->getType().isPODType(S.Context);
13010 isRecordType = VD->getType()->isRecordType();
13011 isReferenceType = VD->getType()->isReferenceType();
13012 }
13013 }
13014
13015 // For most expressions, just call the visitor. For initializer lists,
13016 // track the index of the field being initialized since fields are
13017 // initialized in order allowing use of previously initialized fields.
13018 void CheckExpr(Expr *E) {
13019 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
13020 if (!InitList) {
13021 Visit(E);
13022 return;
13023 }
13024
13025 // Track and increment the index here.
13026 isInitList = true;
13027 InitFieldIndex.push_back(0);
13028 for (auto *Child : InitList->children()) {
13029 CheckExpr(cast<Expr>(Child));
13030 ++InitFieldIndex.back();
13031 }
13032 InitFieldIndex.pop_back();
13033 }
13034
13035 // Returns true if MemberExpr is checked and no further checking is needed.
13036 // Returns false if additional checking is required.
13037 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
13038 llvm::SmallVector<FieldDecl*, 4> Fields;
13039 Expr *Base = E;
13040 bool ReferenceField = false;
13041
13042 // Get the field members used.
13043 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13044 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13045 if (!FD)
13046 return false;
13047 Fields.push_back(FD);
13048 if (FD->getType()->isReferenceType())
13049 ReferenceField = true;
13050 Base = ME->getBase()->IgnoreParenImpCasts();
13051 }
13052
13053 // Keep checking only if the base Decl is the same.
13054 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
13055 if (!DRE || DRE->getDecl() != OrigDecl)
13056 return false;
13057
13058 // A reference field can be bound to an unininitialized field.
13059 if (CheckReference && !ReferenceField)
13060 return true;
13061
13062 // Convert FieldDecls to their index number.
13063 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13064 for (const FieldDecl *I : llvm::reverse(Fields))
13065 UsedFieldIndex.push_back(I->getFieldIndex());
13066
13067 // See if a warning is needed by checking the first difference in index
13068 // numbers. If field being used has index less than the field being
13069 // initialized, then the use is safe.
13070 for (auto UsedIter = UsedFieldIndex.begin(),
13071 UsedEnd = UsedFieldIndex.end(),
13072 OrigIter = InitFieldIndex.begin(),
13073 OrigEnd = InitFieldIndex.end();
13074 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13075 if (*UsedIter < *OrigIter)
13076 return true;
13077 if (*UsedIter > *OrigIter)
13078 break;
13079 }
13080
13081 // TODO: Add a different warning which will print the field names.
13082 HandleDeclRefExpr(DRE);
13083 return true;
13084 }
13085
13086 // For most expressions, the cast is directly above the DeclRefExpr.
13087 // For conditional operators, the cast can be outside the conditional
13088 // operator if both expressions are DeclRefExpr's.
13089 void HandleValue(Expr *E) {
13090 E = E->IgnoreParens();
13091 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
13092 HandleDeclRefExpr(DRE);
13093 return;
13094 }
13095
13096 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
13097 Visit(CO->getCond());
13098 HandleValue(CO->getTrueExpr());
13099 HandleValue(CO->getFalseExpr());
13100 return;
13101 }
13102
13103 if (BinaryConditionalOperator *BCO =
13104 dyn_cast<BinaryConditionalOperator>(E)) {
13105 Visit(BCO->getCond());
13106 HandleValue(BCO->getFalseExpr());
13107 return;
13108 }
13109
13110 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
13111 if (Expr *SE = OVE->getSourceExpr())
13112 HandleValue(SE);
13113 return;
13114 }
13115
13116 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13117 if (BO->getOpcode() == BO_Comma) {
13118 Visit(BO->getLHS());
13119 HandleValue(BO->getRHS());
13120 return;
13121 }
13122 }
13123
13124 if (isa<MemberExpr>(E)) {
13125 if (isInitList) {
13126 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
13127 false /*CheckReference*/))
13128 return;
13129 }
13130
13131 Expr *Base = E->IgnoreParenImpCasts();
13132 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13133 // Check for static member variables and don't warn on them.
13134 if (!isa<FieldDecl>(ME->getMemberDecl()))
13135 return;
13136 Base = ME->getBase()->IgnoreParenImpCasts();
13137 }
13138 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
13139 HandleDeclRefExpr(DRE);
13140 return;
13141 }
13142
13143 Visit(E);
13144 }
13145
13146 // Reference types not handled in HandleValue are handled here since all
13147 // uses of references are bad, not just r-value uses.
13148 void VisitDeclRefExpr(DeclRefExpr *E) {
13149 if (isReferenceType)
13150 HandleDeclRefExpr(E);
13151 }
13152
13153 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13154 if (E->getCastKind() == CK_LValueToRValue) {
13155 HandleValue(E->getSubExpr());
13156 return;
13157 }
13158
13159 Inherited::VisitImplicitCastExpr(E);
13160 }
13161
13162 void VisitMemberExpr(MemberExpr *E) {
13163 if (isInitList) {
13164 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13165 return;
13166 }
13167
13168 // Don't warn on arrays since they can be treated as pointers.
13169 if (E->getType()->canDecayToPointerType()) return;
13170
13171 // Warn when a non-static method call is followed by non-static member
13172 // field accesses, which is followed by a DeclRefExpr.
13173 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13174 bool Warn = (MD && !MD->isStatic());
13175 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13176 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13177 if (!isa<FieldDecl>(ME->getMemberDecl()))
13178 Warn = false;
13179 Base = ME->getBase()->IgnoreParenImpCasts();
13180 }
13181
13182 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13183 if (Warn)
13184 HandleDeclRefExpr(DRE);
13185 return;
13186 }
13187
13188 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13189 // Visit that expression.
13190 Visit(Base);
13191 }
13192
13193 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13194 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13195 Expr *Callee = E->getCallee();
13196
13197 if (isa<UnresolvedLookupExpr>(Callee))
13198 return Inherited::VisitCXXOperatorCallExpr(E);
13199
13200 Visit(Callee);
13201 for (auto Arg: E->arguments())
13202 HandleValue(Arg->IgnoreParenImpCasts());
13203 }
13204
13205 void VisitLambdaExpr(LambdaExpr *E) {
13206 if (!isInCXXOperatorCall) {
13207 Inherited::VisitLambdaExpr(E);
13208 return;
13209 }
13210
13211 for (Expr *Init : E->capture_inits())
13212 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13213 HandleDeclRefExpr(DRE);
13214 else if (Init)
13215 Visit(Init);
13216 }
13217
13218 void VisitUnaryOperator(UnaryOperator *E) {
13219 // For POD record types, addresses of its own members are well-defined.
13220 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13222 if (!isPODType)
13223 HandleValue(E->getSubExpr());
13224 return;
13225 }
13226
13227 if (E->isIncrementDecrementOp()) {
13228 HandleValue(E->getSubExpr());
13229 return;
13230 }
13231
13232 Inherited::VisitUnaryOperator(E);
13233 }
13234
13235 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13236
13237 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13238 if (E->getConstructor()->isCopyConstructor()) {
13239 Expr *ArgExpr = E->getArg(0);
13240 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13241 if (ILE->getNumInits() == 1)
13242 ArgExpr = ILE->getInit(0);
13243 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13244 if (ICE->getCastKind() == CK_NoOp)
13245 ArgExpr = ICE->getSubExpr();
13246 HandleValue(ArgExpr);
13247 return;
13248 }
13249 Inherited::VisitCXXConstructExpr(E);
13250 }
13251
13252 void VisitCallExpr(CallExpr *E) {
13253 // Treat std::move as a use.
13254 if (E->isCallToStdMove()) {
13255 HandleValue(E->getArg(0));
13256 return;
13257 }
13258
13259 Inherited::VisitCallExpr(E);
13260 }
13261
13262 void VisitBinaryOperator(BinaryOperator *E) {
13263 if (E->isCompoundAssignmentOp()) {
13264 HandleValue(E->getLHS());
13265 Visit(E->getRHS());
13266 return;
13267 }
13268
13269 Inherited::VisitBinaryOperator(E);
13270 }
13271
13272 // A custom visitor for BinaryConditionalOperator is needed because the
13273 // regular visitor would check the condition and true expression separately
13274 // but both point to the same place giving duplicate diagnostics.
13275 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13276 Visit(E->getCond());
13277 Visit(E->getFalseExpr());
13278 }
13279
13280 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13281 Decl* ReferenceDecl = DRE->getDecl();
13282 if (OrigDecl != ReferenceDecl) return;
13283 unsigned diag;
13284 if (isReferenceType) {
13285 diag = diag::warn_uninit_self_reference_in_reference_init;
13286 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13287 diag = diag::warn_static_self_reference_in_init;
13288 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13289 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13290 DRE->getDecl()->getType()->isRecordType()) {
13291 diag = diag::warn_uninit_self_reference_in_init;
13292 } else {
13293 // Local variables will be handled by the CFG analysis.
13294 return;
13295 }
13296
13297 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13298 S.PDiag(diag)
13299 << DRE->getDecl() << OrigDecl->getLocation()
13300 << DRE->getSourceRange());
13301 }
13302 };
13303
13304 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13305 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13306 bool DirectInit) {
13307 // Parameters arguments are occassionially constructed with itself,
13308 // for instance, in recursive functions. Skip them.
13309 if (isa<ParmVarDecl>(OrigDecl))
13310 return;
13311
13312 // Skip checking for file-scope constexpr variables - constant evaluation
13313 // will produce appropriate errors without needing runtime diagnostics.
13314 // Local constexpr should still emit runtime warnings.
13315 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13316 VD && VD->isConstexpr() && VD->isFileVarDecl())
13317 return;
13318
13319 E = E->IgnoreParens();
13320
13321 // Skip checking T a = a where T is not a record or reference type.
13322 // Doing so is a way to silence uninitialized warnings.
13323 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13324 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13325 if (ICE->getCastKind() == CK_LValueToRValue)
13326 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13327 if (DRE->getDecl() == OrigDecl)
13328 return;
13329
13330 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13331 }
13332} // end anonymous namespace
13333
13334namespace {
13335 // Simple wrapper to add the name of a variable or (if no variable is
13336 // available) a DeclarationName into a diagnostic.
13337 struct VarDeclOrName {
13338 VarDecl *VDecl;
13339 DeclarationName Name;
13340
13341 friend const Sema::SemaDiagnosticBuilder &
13342 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13343 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13344 }
13345 };
13346} // end anonymous namespace
13347
13350 TypeSourceInfo *TSI,
13351 SourceRange Range, bool DirectInit,
13352 Expr *Init) {
13353 bool IsInitCapture = !VDecl;
13354 assert((!VDecl || !VDecl->isInitCapture()) &&
13355 "init captures are expected to be deduced prior to initialization");
13356
13357 VarDeclOrName VN{VDecl, Name};
13358
13359 DeducedType *Deduced = Type->getContainedDeducedType();
13360 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13361
13362 // Diagnose auto array declarations in C23, unless it's a supported extension.
13363 if (getLangOpts().C23 && Type->isArrayType() &&
13364 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13365 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13366 << (int)Deduced->getContainedAutoType()->getKeyword()
13367 << /*in array decl*/ 23 << Range;
13368 return QualType();
13369 }
13370
13371 // C++11 [dcl.spec.auto]p3
13372 if (!Init) {
13373 assert(VDecl && "no init for init capture deduction?");
13374
13375 // Except for class argument deduction, and then for an initializing
13376 // declaration only, i.e. no static at class scope or extern.
13378 VDecl->hasExternalStorage() ||
13379 VDecl->isStaticDataMember()) {
13380 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13381 << VDecl->getDeclName() << Type;
13382 return QualType();
13383 }
13384 }
13385
13386 ArrayRef<Expr*> DeduceInits;
13387 if (Init)
13388 DeduceInits = Init;
13389
13390 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13391 if (DirectInit && PL)
13392 DeduceInits = PL->exprs();
13393
13395 assert(VDecl && "non-auto type for init capture deduction?");
13398 VDecl->getLocation(), DirectInit, Init);
13399 // FIXME: Initialization should not be taking a mutable list of inits.
13400 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13401 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13402 InitsCopy);
13403 }
13404
13405 if (DirectInit) {
13406 if (auto *IL = dyn_cast<InitListExpr>(Init))
13407 DeduceInits = IL->inits();
13408 }
13409
13410 // Deduction only works if we have exactly one source expression.
13411 if (DeduceInits.empty()) {
13412 // It isn't possible to write this directly, but it is possible to
13413 // end up in this situation with "auto x(some_pack...);"
13414 Diag(Init->getBeginLoc(), IsInitCapture
13415 ? diag::err_init_capture_no_expression
13416 : diag::err_auto_var_init_no_expression)
13417 << VN << Type << Range;
13418 return QualType();
13419 }
13420
13421 if (DeduceInits.size() > 1) {
13422 Diag(DeduceInits[1]->getBeginLoc(),
13423 IsInitCapture ? diag::err_init_capture_multiple_expressions
13424 : diag::err_auto_var_init_multiple_expressions)
13425 << VN << Type << Range;
13426 return QualType();
13427 }
13428
13429 Expr *DeduceInit = DeduceInits[0];
13430 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13431 Diag(Init->getBeginLoc(), IsInitCapture
13432 ? diag::err_init_capture_paren_braces
13433 : diag::err_auto_var_init_paren_braces)
13434 << isa<InitListExpr>(Init) << VN << Type << Range;
13435 return QualType();
13436 }
13437
13438 // Expressions default to 'id' when we're in a debugger.
13439 bool DefaultedAnyToId = false;
13440 if (getLangOpts().DebuggerCastResultToId &&
13441 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13443 if (Result.isInvalid()) {
13444 return QualType();
13445 }
13446 Init = Result.get();
13447 DefaultedAnyToId = true;
13448 }
13449
13450 // C++ [dcl.decomp]p1:
13451 // If the assignment-expression [...] has array type A and no ref-qualifier
13452 // is present, e has type cv A
13453 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13454 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13455 DeduceInit->getType()->isConstantArrayType())
13456 return Context.getQualifiedType(DeduceInit->getType(),
13457 Type.getQualifiers());
13458
13459 QualType DeducedType;
13460 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13462 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13465 if (!IsInitCapture)
13466 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13467 else if (isa<InitListExpr>(Init))
13468 Diag(Range.getBegin(),
13469 diag::err_init_capture_deduction_failure_from_init_list)
13470 << VN
13471 << (DeduceInit->getType().isNull() ? TSI->getType()
13472 : DeduceInit->getType())
13473 << DeduceInit->getSourceRange();
13474 else
13475 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13476 << VN << TSI->getType()
13477 << (DeduceInit->getType().isNull() ? TSI->getType()
13478 : DeduceInit->getType())
13479 << DeduceInit->getSourceRange();
13480 }
13481
13482 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13483 // 'id' instead of a specific object type prevents most of our usual
13484 // checks.
13485 // We only want to warn outside of template instantiations, though:
13486 // inside a template, the 'id' could have come from a parameter.
13487 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13488 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13489 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13490 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13491 }
13492
13493 return DeducedType;
13494}
13495
13497 Expr *Init) {
13498 assert(!Init || !Init->containsErrors());
13500 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13501 VDecl->getSourceRange(), DirectInit, Init);
13502 if (DeducedType.isNull()) {
13503 VDecl->setInvalidDecl();
13504 return true;
13505 }
13506
13507 VDecl->setType(DeducedType);
13508 assert(VDecl->isLinkageValid());
13509
13510 // In ARC, infer lifetime.
13511 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13512 VDecl->setInvalidDecl();
13513
13514 if (getLangOpts().OpenCL)
13516
13517 if (getLangOpts().HLSL)
13518 HLSL().deduceAddressSpace(VDecl);
13519
13520 // If this is a redeclaration, check that the type we just deduced matches
13521 // the previously declared type.
13522 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13523 // We never need to merge the type, because we cannot form an incomplete
13524 // array of auto, nor deduce such a type.
13525 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13526 }
13527
13528 // Check the deduced type is valid for a variable declaration.
13530 return VDecl->isInvalidDecl();
13531}
13532
13534 SourceLocation Loc) {
13535 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13536 Init = EWC->getSubExpr();
13537
13538 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13539 Init = CE->getSubExpr();
13540
13541 QualType InitType = Init->getType();
13544 "shouldn't be called if type doesn't have a non-trivial C struct");
13545 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13546 for (auto *I : ILE->inits()) {
13547 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13548 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13549 continue;
13550 SourceLocation SL = I->getExprLoc();
13551 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13552 }
13553 return;
13554 }
13555
13558 checkNonTrivialCUnion(InitType, Loc,
13560 NTCUK_Init);
13561 } else {
13562 // Assume all other explicit initializers involving copying some existing
13563 // object.
13564 // TODO: ignore any explicit initializers where we can guarantee
13565 // copy-elision.
13568 NTCUK_Copy);
13569 }
13570}
13571
13572namespace {
13573
13574bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13575 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13576 // in the source code or implicitly by the compiler if it is in a union
13577 // defined in a system header and has non-trivial ObjC ownership
13578 // qualifications. We don't want those fields to participate in determining
13579 // whether the containing union is non-trivial.
13580 return FD->hasAttr<UnavailableAttr>();
13581}
13582
13583struct DiagNonTrivalCUnionDefaultInitializeVisitor
13584 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13585 void> {
13586 using Super =
13587 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13588 void>;
13589
13590 DiagNonTrivalCUnionDefaultInitializeVisitor(
13591 QualType OrigTy, SourceLocation OrigLoc,
13592 NonTrivialCUnionContext UseContext, Sema &S)
13593 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13594
13595 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13596 const FieldDecl *FD, bool InNonTrivialUnion) {
13597 if (const auto *AT = S.Context.getAsArrayType(QT))
13598 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13599 InNonTrivialUnion);
13600 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13601 }
13602
13603 void visitARCStrong(QualType QT, const FieldDecl *FD,
13604 bool InNonTrivialUnion) {
13605 if (InNonTrivialUnion)
13606 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13607 << 1 << 0 << QT << FD->getName();
13608 }
13609
13610 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13611 if (InNonTrivialUnion)
13612 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13613 << 1 << 0 << QT << FD->getName();
13614 }
13615
13616 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13617 const auto *RD = QT->castAsRecordDecl();
13618 if (RD->isUnion()) {
13619 if (OrigLoc.isValid()) {
13620 bool IsUnion = false;
13621 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13622 IsUnion = OrigRD->isUnion();
13623 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13624 << 0 << OrigTy << IsUnion << UseContext;
13625 // Reset OrigLoc so that this diagnostic is emitted only once.
13626 OrigLoc = SourceLocation();
13627 }
13628 InNonTrivialUnion = true;
13629 }
13630
13631 if (InNonTrivialUnion)
13632 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13633 << 0 << 0 << QT.getUnqualifiedType() << "";
13634
13635 for (const FieldDecl *FD : RD->fields())
13636 if (!shouldIgnoreForRecordTriviality(FD))
13637 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13638 }
13639
13640 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13641
13642 // The non-trivial C union type or the struct/union type that contains a
13643 // non-trivial C union.
13644 QualType OrigTy;
13645 SourceLocation OrigLoc;
13646 NonTrivialCUnionContext UseContext;
13647 Sema &S;
13648};
13649
13650struct DiagNonTrivalCUnionDestructedTypeVisitor
13651 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13652 using Super =
13653 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13654
13655 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13656 SourceLocation OrigLoc,
13657 NonTrivialCUnionContext UseContext,
13658 Sema &S)
13659 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13660
13661 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13662 const FieldDecl *FD, bool InNonTrivialUnion) {
13663 if (const auto *AT = S.Context.getAsArrayType(QT))
13664 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13665 InNonTrivialUnion);
13666 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13667 }
13668
13669 void visitARCStrong(QualType QT, const FieldDecl *FD,
13670 bool InNonTrivialUnion) {
13671 if (InNonTrivialUnion)
13672 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13673 << 1 << 1 << QT << FD->getName();
13674 }
13675
13676 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13677 if (InNonTrivialUnion)
13678 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13679 << 1 << 1 << QT << FD->getName();
13680 }
13681
13682 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13683 const auto *RD = QT->castAsRecordDecl();
13684 if (RD->isUnion()) {
13685 if (OrigLoc.isValid()) {
13686 bool IsUnion = false;
13687 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13688 IsUnion = OrigRD->isUnion();
13689 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13690 << 1 << OrigTy << IsUnion << UseContext;
13691 // Reset OrigLoc so that this diagnostic is emitted only once.
13692 OrigLoc = SourceLocation();
13693 }
13694 InNonTrivialUnion = true;
13695 }
13696
13697 if (InNonTrivialUnion)
13698 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13699 << 0 << 1 << QT.getUnqualifiedType() << "";
13700
13701 for (const FieldDecl *FD : RD->fields())
13702 if (!shouldIgnoreForRecordTriviality(FD))
13703 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13704 }
13705
13706 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13707 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13708 bool InNonTrivialUnion) {}
13709
13710 // The non-trivial C union type or the struct/union type that contains a
13711 // non-trivial C union.
13712 QualType OrigTy;
13713 SourceLocation OrigLoc;
13714 NonTrivialCUnionContext UseContext;
13715 Sema &S;
13716};
13717
13718struct DiagNonTrivalCUnionCopyVisitor
13719 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13720 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13721
13722 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13723 NonTrivialCUnionContext UseContext, Sema &S)
13724 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13725
13726 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13727 const FieldDecl *FD, bool InNonTrivialUnion) {
13728 if (const auto *AT = S.Context.getAsArrayType(QT))
13729 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13730 InNonTrivialUnion);
13731 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13732 }
13733
13734 void visitARCStrong(QualType QT, const FieldDecl *FD,
13735 bool InNonTrivialUnion) {
13736 if (InNonTrivialUnion)
13737 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13738 << 1 << 2 << QT << FD->getName();
13739 }
13740
13741 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13742 if (InNonTrivialUnion)
13743 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13744 << 1 << 2 << QT << FD->getName();
13745 }
13746
13747 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13748 const auto *RD = QT->castAsRecordDecl();
13749 if (RD->isUnion()) {
13750 if (OrigLoc.isValid()) {
13751 bool IsUnion = false;
13752 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13753 IsUnion = OrigRD->isUnion();
13754 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13755 << 2 << OrigTy << IsUnion << UseContext;
13756 // Reset OrigLoc so that this diagnostic is emitted only once.
13757 OrigLoc = SourceLocation();
13758 }
13759 InNonTrivialUnion = true;
13760 }
13761
13762 if (InNonTrivialUnion)
13763 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13764 << 0 << 2 << QT.getUnqualifiedType() << "";
13765
13766 for (const FieldDecl *FD : RD->fields())
13767 if (!shouldIgnoreForRecordTriviality(FD))
13768 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13769 }
13770
13771 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13772 if (InNonTrivialUnion)
13773 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13774 << 1 << 2 << QT << FD->getName();
13775 }
13776
13777 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13778 const FieldDecl *FD, bool InNonTrivialUnion) {}
13779 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13780 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13781 bool InNonTrivialUnion) {}
13782
13783 // The non-trivial C union type or the struct/union type that contains a
13784 // non-trivial C union.
13785 QualType OrigTy;
13786 SourceLocation OrigLoc;
13787 NonTrivialCUnionContext UseContext;
13788 Sema &S;
13789};
13790
13791} // namespace
13792
13794 NonTrivialCUnionContext UseContext,
13795 unsigned NonTrivialKind) {
13799 "shouldn't be called if type doesn't have a non-trivial C union");
13800
13801 if ((NonTrivialKind & NTCUK_Init) &&
13803 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13804 .visit(QT, nullptr, false);
13805 if ((NonTrivialKind & NTCUK_Destruct) &&
13807 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13808 .visit(QT, nullptr, false);
13809 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13810 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13811 .visit(QT, nullptr, false);
13812}
13813
13815 const VarDecl *Dcl) {
13816 if (!getLangOpts().CPlusPlus)
13817 return false;
13818
13819 // We only need to warn if the definition is in a header file, so wait to
13820 // diagnose until we've seen the definition.
13821 if (!Dcl->isThisDeclarationADefinition())
13822 return false;
13823
13824 // If an object is defined in a source file, its definition can't get
13825 // duplicated since it will never appear in more than one TU.
13827 return false;
13828
13829 // If the variable we're looking at is a static local, then we actually care
13830 // about the properties of the function containing it.
13831 const ValueDecl *Target = Dcl;
13832 // VarDecls and FunctionDecls have different functions for checking
13833 // inline-ness, and whether they were originally templated, so we have to
13834 // call the appropriate functions manually.
13835 bool TargetIsInline = Dcl->isInline();
13836 bool TargetWasTemplated =
13838
13839 // Update the Target and TargetIsInline property if necessary
13840 if (Dcl->isStaticLocal()) {
13841 const DeclContext *Ctx = Dcl->getDeclContext();
13842 if (!Ctx)
13843 return false;
13844
13845 const FunctionDecl *FunDcl =
13846 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13847 if (!FunDcl)
13848 return false;
13849
13850 Target = FunDcl;
13851 // IsInlined() checks for the C++ inline property
13852 TargetIsInline = FunDcl->isInlined();
13853 TargetWasTemplated =
13855 }
13856
13857 // Non-inline functions/variables can only legally appear in one TU
13858 // unless they were part of a template. Unfortunately, making complex
13859 // template instantiations visible is infeasible in practice, since
13860 // everything the template depends on also has to be visible. To avoid
13861 // giving impractical-to-fix warnings, don't warn if we're inside
13862 // something that was templated, even on inline stuff.
13863 if (!TargetIsInline || TargetWasTemplated)
13864 return false;
13865
13866 // If the object isn't hidden, the dynamic linker will prevent duplication.
13867 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13868
13869 // The target is "hidden" (from the dynamic linker) if:
13870 // 1. On posix, it has hidden visibility, or
13871 // 2. On windows, it has no import/export annotation, and neither does the
13872 // class which directly contains it.
13873 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13874 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13875 return false;
13876
13877 // If the variable isn't directly annotated, check to see if it's a member
13878 // of an annotated class.
13879 const CXXRecordDecl *Ctx =
13880 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13881 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13882 return false;
13883
13884 } else if (Lnk.getVisibility() != HiddenVisibility) {
13885 // Posix case
13886 return false;
13887 }
13888
13889 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13891 return false;
13892
13893 return true;
13894}
13895
13896// Determine whether the object seems mutable for the purpose of diagnosing
13897// possible unique object duplication, i.e. non-const-qualified, and
13898// not an always-constant type like a function.
13899// Not perfect: doesn't account for mutable members, for example, or
13900// elements of container types.
13901// For nested pointers, any individual level being non-const is sufficient.
13902static bool looksMutable(QualType T, const ASTContext &Ctx) {
13903 T = T.getNonReferenceType();
13904 if (T->isFunctionType())
13905 return false;
13906 if (!T.isConstant(Ctx))
13907 return true;
13908 if (T->isPointerType())
13909 return looksMutable(T->getPointeeType(), Ctx);
13910 return false;
13911}
13912
13914 // If this object has external linkage and hidden visibility, it might be
13915 // duplicated when built into a shared library, which causes problems if it's
13916 // mutable (since the copies won't be in sync) or its initialization has side
13917 // effects (since it will run once per copy instead of once globally).
13918
13919 // Don't diagnose if we're inside a template, because it's not practical to
13920 // fix the warning in most cases.
13921 if (!VD->isTemplated() &&
13923
13924 QualType Type = VD->getType();
13925 if (looksMutable(Type, VD->getASTContext())) {
13926 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13927 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13928 }
13929
13930 // To keep false positives low, only warn if we're certain that the
13931 // initializer has side effects. Don't warn on operator new, since a mutable
13932 // pointer will trigger the previous warning, and an immutable pointer
13933 // getting duplicated just results in a little extra memory usage.
13934 const Expr *Init = VD->getAnyInitializer();
13935 if (Init &&
13936 Init->HasSideEffects(VD->getASTContext(),
13937 /*IncludePossibleEffects=*/false) &&
13938 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13939 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13940 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13941 }
13942 }
13943}
13944
13946 llvm::scope_exit ResetDeclForInitializer([this]() {
13947 if (!this->ExprEvalContexts.empty())
13948 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13949 });
13950
13951 // If there is no declaration, there was an error parsing it. Just ignore
13952 // the initializer.
13953 if (!RealDecl) {
13954 return;
13955 }
13956
13957 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13958 if (!Method->isInvalidDecl()) {
13959 // Pure-specifiers are handled in ActOnPureSpecifier.
13960 Diag(Method->getLocation(), diag::err_member_function_initialization)
13961 << Method->getDeclName() << Init->getSourceRange();
13962 Method->setInvalidDecl();
13963 }
13964 return;
13965 }
13966
13967 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13968 if (!VDecl) {
13969 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13970 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13971 RealDecl->setInvalidDecl();
13972 return;
13973 }
13974
13975 if (VDecl->isInvalidDecl()) {
13976 ExprResult Recovery =
13977 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13978 if (Expr *E = Recovery.get())
13979 VDecl->setInit(E);
13980 return;
13981 }
13982
13983 // __amdgpu_feature_predicate_t cannot be initialised
13984 if (VDecl->getType().getDesugaredType(Context) ==
13985 Context.AMDGPUFeaturePredicateTy) {
13986 Diag(VDecl->getLocation(),
13987 diag::err_amdgcn_predicate_type_is_not_constructible)
13988 << VDecl;
13989 VDecl->setInvalidDecl();
13990 return;
13991 }
13992
13993 // WebAssembly tables can't be used to initialise a variable.
13994 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13995 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13996 VDecl->setInvalidDecl();
13997 return;
13998 }
13999
14000 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
14001 if (VDecl->getType()->isUndeducedType()) {
14002 if (Init->containsErrors()) {
14003 // Invalidate the decl as we don't know the type for recovery-expr yet.
14004 RealDecl->setInvalidDecl();
14005 VDecl->setInit(Init);
14006 return;
14007 }
14008
14010 assert(VDecl->isInvalidDecl() &&
14011 "decl should be invalidated when deduce fails");
14012 if (auto *RecoveryExpr =
14013 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init})
14014 .get())
14015 VDecl->setInit(RecoveryExpr);
14016 return;
14017 }
14018 }
14019
14020 this->CheckAttributesOnDeducedType(RealDecl);
14021
14022 // we don't initialize groupshared variables so warn and return
14023 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
14024 Diag(VDecl->getLocation(), diag::warn_hlsl_groupshared_init);
14025 return;
14026 }
14027
14028 // dllimport cannot be used on variable definitions.
14029 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
14030 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
14031 VDecl->setInvalidDecl();
14032 return;
14033 }
14034
14035 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
14036 // the identifier has external or internal linkage, the declaration shall
14037 // have no initializer for the identifier.
14038 // C++14 [dcl.init]p5 is the same restriction for C++.
14039 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14040 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
14041 VDecl->setInvalidDecl();
14042 return;
14043 }
14044
14045 if (!VDecl->getType()->isDependentType()) {
14046 // A definition must end up with a complete type, which means it must be
14047 // complete with the restriction that an array type might be completed by
14048 // the initializer; note that later code assumes this restriction.
14049 QualType BaseDeclType = VDecl->getType();
14050 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
14051 BaseDeclType = Array->getElementType();
14052 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
14053 diag::err_typecheck_decl_incomplete_type)) {
14054 RealDecl->setInvalidDecl();
14055 return;
14056 }
14057
14058 // The variable can not have an abstract class type.
14059 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
14060 diag::err_abstract_type_in_decl,
14062 VDecl->setInvalidDecl();
14063 }
14064
14065 // C++ [module.import/6]
14066 // ...
14067 // A header unit shall not contain a definition of a non-inline function or
14068 // variable whose name has external linkage.
14069 //
14070 // We choose to allow weak & selectany definitions, as they are common in
14071 // headers, and have semantics similar to inline definitions which are allowed
14072 // in header units.
14073 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14074 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14075 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14076 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
14078 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14079 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
14080 VDecl->setInvalidDecl();
14081 }
14082
14083 // If adding the initializer will turn this declaration into a definition,
14084 // and we already have a definition for this variable, diagnose or otherwise
14085 // handle the situation.
14086 if (VarDecl *Def = VDecl->getDefinition())
14087 if (Def != VDecl &&
14088 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14090 checkVarDeclRedefinition(Def, VDecl))
14091 return;
14092
14093 if (getLangOpts().CPlusPlus) {
14094 // C++ [class.static.data]p4
14095 // If a static data member is of const integral or const
14096 // enumeration type, its declaration in the class definition can
14097 // specify a constant-initializer which shall be an integral
14098 // constant expression (5.19). In that case, the member can appear
14099 // in integral constant expressions. The member shall still be
14100 // defined in a namespace scope if it is used in the program and the
14101 // namespace scope definition shall not contain an initializer.
14102 //
14103 // We already performed a redefinition check above, but for static
14104 // data members we also need to check whether there was an in-class
14105 // declaration with an initializer.
14106 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14107 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
14108 << VDecl->getDeclName();
14109 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14110 diag::note_previous_initializer)
14111 << 0;
14112 return;
14113 }
14114
14116 VDecl->setInvalidDecl();
14117 return;
14118 }
14119 }
14120
14121 // If the variable has an initializer and local storage, check whether
14122 // anything jumps over the initialization.
14123 if (VDecl->hasLocalStorage())
14125
14126 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14127 // a kernel function cannot be initialized."
14128 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14129 Diag(VDecl->getLocation(), diag::err_local_cant_init);
14130 VDecl->setInvalidDecl();
14131 return;
14132 }
14133
14134 // The LoaderUninitialized attribute acts as a definition (of undef).
14135 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14136 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
14137 VDecl->setInvalidDecl();
14138 return;
14139 }
14140
14141 if (getLangOpts().HLSL)
14142 if (!HLSL().handleInitialization(VDecl, Init))
14143 return;
14144
14145 // Get the decls type and save a reference for later, since
14146 // CheckInitializerTypes may change it.
14147 QualType DclT = VDecl->getType(), SavT = DclT;
14148
14149 // Expressions default to 'id' when we're in a debugger
14150 // and we are assigning it to a variable of Objective-C pointer type.
14151 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14152 Init->getType() == Context.UnknownAnyTy) {
14154 if (!Result.isUsable()) {
14155 VDecl->setInvalidDecl();
14156 return;
14157 }
14158 Init = Result.get();
14159 }
14160
14161 // Perform the initialization.
14162 bool InitializedFromParenListExpr = false;
14163 bool IsParenListInit = false;
14164 if (!VDecl->isInvalidDecl()) {
14167 VDecl->getLocation(), DirectInit, Init);
14168
14169 MultiExprArg Args = Init;
14170 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
14171 Args =
14172 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14173 InitializedFromParenListExpr = true;
14174 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
14175 Args = CXXDirectInit->getInitExprs();
14176 InitializedFromParenListExpr = true;
14177 }
14178
14179 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14180 /*TopLevelOfInitList=*/false,
14181 /*TreatUnavailableAsInvalid=*/false);
14182 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14183 if (!Result.isUsable()) {
14184 // If the provided initializer fails to initialize the var decl,
14185 // we attach a recovery expr for better recovery.
14186 auto RecoveryExpr =
14187 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14188 if (RecoveryExpr.get())
14189 VDecl->setInit(RecoveryExpr.get());
14190 // In general, for error recovery purposes, the initializer doesn't play
14191 // part in the valid bit of the declaration. There are a few exceptions:
14192 // 1) if the var decl has a deduced auto type, and the type cannot be
14193 // deduced by an invalid initializer;
14194 // 2) if the var decl is a decomposition decl with a non-deduced type,
14195 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14196 // Case 1) was already handled elsewhere.
14197 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14198 VDecl->setInvalidDecl();
14199 return;
14200 }
14201
14202 Init = Result.getAs<Expr>();
14203 IsParenListInit = !InitSeq.steps().empty() &&
14204 InitSeq.step_begin()->Kind ==
14206 QualType VDeclType = VDecl->getType();
14207 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14208 !VDeclType->isDependentType() &&
14209 Context.getAsIncompleteArrayType(VDeclType) &&
14210 Context.getAsIncompleteArrayType(Init->getType())) {
14211 // Bail out if it is not possible to deduce array size from the
14212 // initializer.
14213 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14214 << VDeclType;
14215 VDecl->setInvalidDecl();
14216 return;
14217 }
14218 }
14219
14220 // Check for self-references within variable initializers.
14221 // Variables declared within a function/method body (except for references)
14222 // are handled by a dataflow analysis.
14223 // This is undefined behavior in C++, but valid in C.
14224 if (getLangOpts().CPlusPlus)
14225 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14226 VDecl->getType()->isReferenceType())
14227 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14228
14229 // If the type changed, it means we had an incomplete type that was
14230 // completed by the initializer. For example:
14231 // int ary[] = { 1, 3, 5 };
14232 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14233 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14234 VDecl->setType(DclT);
14235
14236 if (!VDecl->isInvalidDecl()) {
14237 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14238
14239 if (VDecl->hasAttr<BlocksAttr>())
14240 ObjC().checkRetainCycles(VDecl, Init);
14241
14242 // It is safe to assign a weak reference into a strong variable.
14243 // Although this code can still have problems:
14244 // id x = self.weakProp;
14245 // id y = self.weakProp;
14246 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14247 // paths through the function. This should be revisited if
14248 // -Wrepeated-use-of-weak is made flow-sensitive.
14249 if (FunctionScopeInfo *FSI = getCurFunction())
14250 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14252 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14253 Init->getBeginLoc()))
14254 FSI->markSafeWeakUse(Init);
14255 }
14256
14257 // The initialization is usually a full-expression.
14258 //
14259 // FIXME: If this is a braced initialization of an aggregate, it is not
14260 // an expression, and each individual field initializer is a separate
14261 // full-expression. For instance, in:
14262 //
14263 // struct Temp { ~Temp(); };
14264 // struct S { S(Temp); };
14265 // struct T { S a, b; } t = { Temp(), Temp() }
14266 //
14267 // we should destroy the first Temp before constructing the second.
14268
14269 // Set context flag for OverflowBehaviorType initialization analysis
14271 true);
14274 /*DiscardedValue*/ false, VDecl->isConstexpr());
14275 if (!Result.isUsable()) {
14276 VDecl->setInvalidDecl();
14277 return;
14278 }
14279 Init = Result.get();
14280
14281 // Attach the initializer to the decl.
14282 VDecl->setInit(Init);
14283
14284 if (VDecl->isLocalVarDecl()) {
14285 // Don't check the initializer if the declaration is malformed.
14286 if (VDecl->isInvalidDecl()) {
14287 // do nothing
14288
14289 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14290 // This is true even in C++ for OpenCL.
14291 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14293
14294 // Otherwise, C++ does not restrict the initializer.
14295 } else if (getLangOpts().CPlusPlus) {
14296 // do nothing
14297
14298 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14299 // static storage duration shall be constant expressions or string literals.
14300 } else if (VDecl->getStorageClass() == SC_Static) {
14301 // Avoid evaluating the initializer twice for constexpr variables. It will
14302 // be evaluated later.
14303 if (!VDecl->isConstexpr())
14305
14306 // C89 is stricter than C99 for aggregate initializers.
14307 // C89 6.5.7p3: All the expressions [...] in an initializer list
14308 // for an object that has aggregate or union type shall be
14309 // constant expressions.
14310 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14312 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14313 }
14314
14315 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14316 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14317 if (VDecl->hasLocalStorage())
14318 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14319 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14320 VDecl->getLexicalDeclContext()->isRecord()) {
14321 // This is an in-class initialization for a static data member, e.g.,
14322 //
14323 // struct S {
14324 // static const int value = 17;
14325 // };
14326
14327 // C++ [class.mem]p4:
14328 // A member-declarator can contain a constant-initializer only
14329 // if it declares a static member (9.4) of const integral or
14330 // const enumeration type, see 9.4.2.
14331 //
14332 // C++11 [class.static.data]p3:
14333 // If a non-volatile non-inline const static data member is of integral
14334 // or enumeration type, its declaration in the class definition can
14335 // specify a brace-or-equal-initializer in which every initializer-clause
14336 // that is an assignment-expression is a constant expression. A static
14337 // data member of literal type can be declared in the class definition
14338 // with the constexpr specifier; if so, its declaration shall specify a
14339 // brace-or-equal-initializer in which every initializer-clause that is
14340 // an assignment-expression is a constant expression.
14341
14342 // Do nothing on dependent types.
14343 if (DclT->isDependentType()) {
14344
14345 // Allow any 'static constexpr' members, whether or not they are of literal
14346 // type. We separately check that every constexpr variable is of literal
14347 // type.
14348 } else if (VDecl->isConstexpr()) {
14349
14350 // Require constness.
14351 } else if (!DclT.isConstQualified()) {
14352 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14353 << Init->getSourceRange();
14354 VDecl->setInvalidDecl();
14355
14356 // We allow integer constant expressions in all cases.
14357 } else if (DclT->isIntegralOrEnumerationType()) {
14359 // In C++11, a non-constexpr const static data member with an
14360 // in-class initializer cannot be volatile.
14361 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14362
14363 // We allow foldable floating-point constants as an extension.
14364 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14365 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14366 // it anyway and provide a fixit to add the 'constexpr'.
14367 if (getLangOpts().CPlusPlus11) {
14368 Diag(VDecl->getLocation(),
14369 diag::ext_in_class_initializer_float_type_cxx11)
14370 << DclT << Init->getSourceRange();
14371 Diag(VDecl->getBeginLoc(),
14372 diag::note_in_class_initializer_float_type_cxx11)
14373 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14374 } else {
14375 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14376 << DclT << Init->getSourceRange();
14377
14378 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14379 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14380 << Init->getSourceRange();
14381 VDecl->setInvalidDecl();
14382 }
14383 }
14384
14385 // Suggest adding 'constexpr' in C++11 for literal types.
14386 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14387 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14388 << DclT << Init->getSourceRange()
14389 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14390 VDecl->setConstexpr(true);
14391
14392 } else {
14393 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14394 << DclT << Init->getSourceRange();
14395 VDecl->setInvalidDecl();
14396 }
14397 } else if (VDecl->isFileVarDecl()) {
14398 // In C, extern is typically used to avoid tentative definitions when
14399 // declaring variables in headers, but adding an initializer makes it a
14400 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14401 // In C++, extern is often used to give implicitly static const variables
14402 // external linkage, so don't warn in that case. If selectany is present,
14403 // this might be header code intended for C and C++ inclusion, so apply the
14404 // C++ rules.
14405 if (VDecl->getStorageClass() == SC_Extern &&
14406 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14407 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14408 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14410 Diag(VDecl->getLocation(), diag::warn_extern_init);
14411
14412 // In Microsoft C++ mode, a const variable defined in namespace scope has
14413 // external linkage by default if the variable is declared with
14414 // __declspec(dllexport).
14415 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14417 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14418 VDecl->setStorageClass(SC_Extern);
14419
14420 // C99 6.7.8p4. All file scoped initializers need to be constant.
14421 // Avoid duplicate diagnostics for constexpr variables.
14422 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14423 !VDecl->isConstexpr())
14425 }
14426
14427 QualType InitType = Init->getType();
14428 if (!InitType.isNull() &&
14432
14433 // We will represent direct-initialization similarly to copy-initialization:
14434 // int x(1); -as-> int x = 1;
14435 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14436 //
14437 // Clients that want to distinguish between the two forms, can check for
14438 // direct initializer using VarDecl::getInitStyle().
14439 // A major benefit is that clients that don't particularly care about which
14440 // exactly form was it (like the CodeGen) can handle both cases without
14441 // special case code.
14442
14443 // C++ 8.5p11:
14444 // The form of initialization (using parentheses or '=') matters
14445 // when the entity being initialized has class type.
14446 if (InitializedFromParenListExpr) {
14447 assert(DirectInit && "Call-style initializer must be direct init.");
14448 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14450 } else if (DirectInit) {
14451 // This must be list-initialization. No other way is direct-initialization.
14453 }
14454
14455 if (LangOpts.OpenMP &&
14456 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14457 VDecl->isFileVarDecl())
14458 DeclsToCheckForDeferredDiags.insert(VDecl);
14460
14461 if (LangOpts.OpenACC && !InitType.isNull())
14462 OpenACC().ActOnVariableInit(VDecl, InitType);
14463}
14464
14466 // Our main concern here is re-establishing invariants like "a
14467 // variable's type is either dependent or complete".
14468 if (!D || D->isInvalidDecl()) return;
14469
14470 VarDecl *VD = dyn_cast<VarDecl>(D);
14471 if (!VD) return;
14472
14473 // Bindings are not usable if we can't make sense of the initializer.
14474 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14475 for (auto *BD : DD->bindings())
14476 BD->setInvalidDecl();
14477
14478 // Auto types are meaningless if we can't make sense of the initializer.
14479 if (VD->getType()->isUndeducedType()) {
14480 D->setInvalidDecl();
14481 return;
14482 }
14483
14484 QualType Ty = VD->getType();
14485 if (Ty->isDependentType()) return;
14486
14487 // Require a complete type.
14489 Context.getBaseElementType(Ty),
14490 diag::err_typecheck_decl_incomplete_type)) {
14491 VD->setInvalidDecl();
14492 return;
14493 }
14494
14495 // Require a non-abstract type.
14496 if (RequireNonAbstractType(VD->getLocation(), Ty,
14497 diag::err_abstract_type_in_decl,
14499 VD->setInvalidDecl();
14500 return;
14501 }
14502
14503 // Don't bother complaining about constructors or destructors,
14504 // though.
14505}
14506
14508 // If there is no declaration, there was an error parsing it. Just ignore it.
14509 if (!RealDecl)
14510 return;
14511
14512 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14513 QualType Type = Var->getType();
14514
14515 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14516 Diag(Var->getLocation(),
14517 diag::err_amdgcn_predicate_type_is_not_constructible)
14518 << Var;
14519 Var->setInvalidDecl();
14520 return;
14521 }
14522 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14523 if (isa<DecompositionDecl>(RealDecl)) {
14524 // Point the caret to the token immediately after the closing bracket.
14525 auto NextLoc = dyn_cast<DecompositionDecl>(RealDecl)->getRSquareLoc();
14526 NextLoc =
14527 Lexer::findNextToken(NextLoc, PP.getSourceManager(), PP.getLangOpts())
14528 ->getLocation();
14529 Diag(NextLoc, diag::err_decomp_decl_requires_init) << Var;
14530 Var->setInvalidDecl();
14531 return;
14532 }
14533
14534 if (Type->isUndeducedType() &&
14535 DeduceVariableDeclarationType(Var, false, nullptr))
14536 return;
14537
14538 this->CheckAttributesOnDeducedType(RealDecl);
14539
14540 // C++11 [class.static.data]p3: A static data member can be declared with
14541 // the constexpr specifier; if so, its declaration shall specify
14542 // a brace-or-equal-initializer.
14543 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14544 // the definition of a variable [...] or the declaration of a static data
14545 // member.
14546 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14547 !Var->isThisDeclarationADemotedDefinition()) {
14548 if (Var->isStaticDataMember()) {
14549 // C++1z removes the relevant rule; the in-class declaration is always
14550 // a definition there.
14551 if (!getLangOpts().CPlusPlus17 &&
14552 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14553 Diag(Var->getLocation(),
14554 diag::err_constexpr_static_mem_var_requires_init)
14555 << Var;
14556 Var->setInvalidDecl();
14557 return;
14558 }
14559 } else {
14560 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14561 Var->setInvalidDecl();
14562 return;
14563 }
14564 }
14565
14566 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14567 // be initialized.
14568 if (!Var->isInvalidDecl() &&
14569 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14570 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14571 bool HasConstExprDefaultConstructor = false;
14572 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14573 for (auto *Ctor : RD->ctors()) {
14574 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14575 Ctor->getMethodQualifiers().getAddressSpace() ==
14577 HasConstExprDefaultConstructor = true;
14578 }
14579 }
14580 }
14581 if (!HasConstExprDefaultConstructor) {
14582 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14583 Var->setInvalidDecl();
14584 return;
14585 }
14586 }
14587
14588 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14589 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14590 Diag(Var->getLocation(), diag::err_specialization_const);
14591 Var->setInvalidDecl();
14592 return;
14593 }
14594
14595 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14596 if (Var->getStorageClass() == SC_Extern) {
14597 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14598 << Var;
14599 Var->setInvalidDecl();
14600 return;
14601 }
14602 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14603 diag::err_typecheck_decl_incomplete_type)) {
14604 Var->setInvalidDecl();
14605 return;
14606 }
14607 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14608 if (!RD->hasTrivialDefaultConstructor()) {
14609 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14610 Var->setInvalidDecl();
14611 return;
14612 }
14613 }
14614 // The declaration is uninitialized, no need for further checks.
14615 return;
14616 }
14617
14618 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14619 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14620 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14621 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14623 NTCUK_Init);
14624
14625 switch (DefKind) {
14627 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14628 break;
14629
14630 // We have an out-of-line definition of a static data member
14631 // that has an in-class initializer, so we type-check this like
14632 // a declaration.
14633 //
14634 [[fallthrough]];
14635
14637 // It's only a declaration.
14638
14639 // Block scope. C99 6.7p7: If an identifier for an object is
14640 // declared with no linkage (C99 6.2.2p6), the type for the
14641 // object shall be complete.
14642 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14643 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14644 RequireCompleteType(Var->getLocation(), Type,
14645 diag::err_typecheck_decl_incomplete_type))
14646 Var->setInvalidDecl();
14647
14648 // Make sure that the type is not abstract.
14649 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14650 RequireNonAbstractType(Var->getLocation(), Type,
14651 diag::err_abstract_type_in_decl,
14653 Var->setInvalidDecl();
14654 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14655 Var->getStorageClass() == SC_PrivateExtern) {
14656 Diag(Var->getLocation(), diag::warn_private_extern);
14657 Diag(Var->getLocation(), diag::note_private_extern);
14658 }
14659
14660 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14661 !Var->isInvalidDecl())
14662 ExternalDeclarations.push_back(Var);
14663
14664 return;
14665
14667 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14668 // object that has file scope without an initializer, and without a
14669 // storage-class specifier or with the storage-class specifier "static",
14670 // constitutes a tentative definition. Note: A tentative definition with
14671 // external linkage is valid (C99 6.2.2p5).
14672 if (!Var->isInvalidDecl()) {
14673 if (const IncompleteArrayType *ArrayT
14674 = Context.getAsIncompleteArrayType(Type)) {
14676 Var->getLocation(), ArrayT->getElementType(),
14677 diag::err_array_incomplete_or_sizeless_type))
14678 Var->setInvalidDecl();
14679 }
14680 if (Var->getStorageClass() == SC_Static) {
14681 // C99 6.9.2p3: If the declaration of an identifier for an object is
14682 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14683 // declared type shall not be an incomplete type.
14684 // NOTE: code such as the following
14685 // static struct s;
14686 // struct s { int a; };
14687 // is accepted by gcc. Hence here we issue a warning instead of
14688 // an error and we do not invalidate the static declaration.
14689 // NOTE: to avoid multiple warnings, only check the first declaration.
14690 if (Var->isFirstDecl())
14691 RequireCompleteType(Var->getLocation(), Type,
14692 diag::ext_typecheck_decl_incomplete_type,
14693 Type->isArrayType());
14694 }
14695 }
14696
14697 // Record the tentative definition; we're done.
14698 if (!Var->isInvalidDecl())
14699 TentativeDefinitions.push_back(Var);
14700 return;
14701 }
14702
14703 // Provide a specific diagnostic for uninitialized variable definitions
14704 // with incomplete array type, unless it is a global unbounded HLSL resource
14705 // array.
14706 if (Type->isIncompleteArrayType() &&
14707 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14709 if (Var->isConstexpr())
14710 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14711 << Var;
14712 else
14713 Diag(Var->getLocation(),
14714 diag::err_typecheck_incomplete_array_needs_initializer);
14715 Var->setInvalidDecl();
14716 return;
14717 }
14718
14719 // Provide a specific diagnostic for uninitialized variable
14720 // definitions with reference type.
14721 if (Type->isReferenceType()) {
14722 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14723 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14724 return;
14725 }
14726
14727 // Do not attempt to type-check the default initializer for a
14728 // variable with dependent type.
14729 if (Type->isDependentType())
14730 return;
14731
14732 if (Var->isInvalidDecl())
14733 return;
14734
14735 if (!Var->hasAttr<AliasAttr>()) {
14736 if (RequireCompleteType(Var->getLocation(),
14737 Context.getBaseElementType(Type),
14738 diag::err_typecheck_decl_incomplete_type)) {
14739 Var->setInvalidDecl();
14740 return;
14741 }
14742 } else {
14743 return;
14744 }
14745
14746 // The variable can not have an abstract class type.
14747 if (RequireNonAbstractType(Var->getLocation(), Type,
14748 diag::err_abstract_type_in_decl,
14750 Var->setInvalidDecl();
14751 return;
14752 }
14753
14754 // In C, if the definition is const-qualified and has no initializer, it
14755 // is left uninitialized unless it has static or thread storage duration.
14756 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14757 unsigned DiagID = diag::warn_default_init_const_unsafe;
14758 if (Var->getStorageDuration() == SD_Static ||
14759 Var->getStorageDuration() == SD_Thread)
14760 DiagID = diag::warn_default_init_const;
14761
14762 bool EmitCppCompat = !Diags.isIgnored(
14763 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14764 Var->getLocation());
14765
14766 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14767 }
14768
14769 // Check for jumps past the implicit initializer. C++0x
14770 // clarifies that this applies to a "variable with automatic
14771 // storage duration", not a "local variable".
14772 // C++11 [stmt.dcl]p3
14773 // A program that jumps from a point where a variable with automatic
14774 // storage duration is not in scope to a point where it is in scope is
14775 // ill-formed unless the variable has scalar type, class type with a
14776 // trivial default constructor and a trivial destructor, a cv-qualified
14777 // version of one of these types, or an array of one of the preceding
14778 // types and is declared without an initializer.
14779 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14780 if (const auto *CXXRecord =
14781 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14782 // Mark the function (if we're in one) for further checking even if the
14783 // looser rules of C++11 do not require such checks, so that we can
14784 // diagnose incompatibilities with C++98.
14785 if (!CXXRecord->isPOD())
14787 }
14788 }
14789 // In OpenCL, we can't initialize objects in the __local address space,
14790 // even implicitly, so don't synthesize an implicit initializer.
14791 if (getLangOpts().OpenCL &&
14792 Var->getType().getAddressSpace() == LangAS::opencl_local)
14793 return;
14794
14795 // Handle HLSL uninitialized decls
14796 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14797 return;
14798
14799 // HLSL input & push-constant variables are expected to be externally
14800 // initialized, even when marked `static`.
14801 if (getLangOpts().HLSL &&
14802 hlsl::isInitializedByPipeline(Var->getType().getAddressSpace()))
14803 return;
14804
14805 // C++03 [dcl.init]p9:
14806 // If no initializer is specified for an object, and the
14807 // object is of (possibly cv-qualified) non-POD class type (or
14808 // array thereof), the object shall be default-initialized; if
14809 // the object is of const-qualified type, the underlying class
14810 // type shall have a user-declared default
14811 // constructor. Otherwise, if no initializer is specified for
14812 // a non- static object, the object and its subobjects, if
14813 // any, have an indeterminate initial value); if the object
14814 // or any of its subobjects are of const-qualified type, the
14815 // program is ill-formed.
14816 // C++0x [dcl.init]p11:
14817 // If no initializer is specified for an object, the object is
14818 // default-initialized; [...].
14821 = InitializationKind::CreateDefault(Var->getLocation());
14822
14823 InitializationSequence InitSeq(*this, Entity, Kind, {});
14824 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14825
14826 if (Init.get()) {
14827 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14828 // This is important for template substitution.
14829 Var->setInitStyle(VarDecl::CallInit);
14830 } else if (Init.isInvalid()) {
14831 // If default-init fails, attach a recovery-expr initializer to track
14832 // that initialization was attempted and failed.
14833 auto RecoveryExpr =
14834 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14835 if (RecoveryExpr.get())
14836 Var->setInit(RecoveryExpr.get());
14837 }
14838
14840 }
14841}
14842
14843void Sema::ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt) {
14844 // If there is no declaration, there was an error parsing it. Ignore it.
14845 if (!D)
14846 return;
14847
14848 VarDecl *VD = dyn_cast<VarDecl>(D);
14849 if (!VD) {
14850 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var)
14851 << InExpansionStmt;
14852 D->setInvalidDecl();
14853 return;
14854 }
14855
14856 VD->setCXXForRangeDecl(true);
14857
14858 // for-range-declaration cannot be given a storage class specifier.
14859 int Error = -1;
14860 switch (VD->getStorageClass()) {
14861 case SC_None:
14862 break;
14863 case SC_Extern:
14864 Error = 0;
14865 break;
14866 case SC_Static:
14867 Error = 1;
14868 break;
14869 case SC_PrivateExtern:
14870 Error = 2;
14871 break;
14872 case SC_Auto:
14873 Error = 3;
14874 break;
14875 case SC_Register:
14876 Error = 4;
14877 break;
14878 }
14879
14880 // for-range-declaration cannot be given a storage class specifier con't.
14881 switch (VD->getTSCSpec()) {
14882 case TSCS_thread_local:
14883 Error = 6;
14884 break;
14885 case TSCS___thread:
14886 case TSCS__Thread_local:
14887 case TSCS_unspecified:
14888 break;
14889 }
14890
14891 if (Error != -1) {
14892 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14893 << InExpansionStmt << VD << Error;
14894 D->setInvalidDecl();
14895 }
14896}
14897
14899 IdentifierInfo *Ident,
14900 ParsedAttributes &Attrs) {
14901 // C++1y [stmt.iter]p1:
14902 // A range-based for statement of the form
14903 // for ( for-range-identifier : for-range-initializer ) statement
14904 // is equivalent to
14905 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14906 DeclSpec DS(Attrs.getPool().getFactory());
14907
14908 const char *PrevSpec;
14909 unsigned DiagID;
14910 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14912
14914 D.SetIdentifier(Ident, IdentLoc);
14915 D.takeAttributesAppending(Attrs);
14916
14917 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14918 IdentLoc);
14919 Decl *Var = ActOnDeclarator(S, D);
14920 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14922 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14923 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14924 : IdentLoc);
14925}
14926
14929 return;
14930 auto *Attr = LifetimeBoundAttr::CreateImplicit(Context, MD->getLocation());
14931 QualType MethodType = MD->getType();
14932 QualType AttributedType =
14933 Context.getAttributedType(Attr, MethodType, MethodType);
14934 TypeLocBuilder TLB;
14935 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14936 TLB.pushFullCopy(TSI->getTypeLoc());
14937 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(AttributedType);
14938 TyLoc.setAttr(Attr);
14939 MD->setType(AttributedType);
14940 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, AttributedType));
14941}
14942
14944 if (var->isInvalidDecl()) return;
14945
14947
14948 if (getLangOpts().OpenCL) {
14949 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14950 // initialiser
14951 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14952 !var->hasInit()) {
14953 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14954 << 1 /*Init*/;
14955 var->setInvalidDecl();
14956 return;
14957 }
14958 }
14959
14960 // In Objective-C, don't allow jumps past the implicit initialization of a
14961 // local retaining variable.
14962 if (getLangOpts().ObjC &&
14963 var->hasLocalStorage()) {
14964 switch (var->getType().getObjCLifetime()) {
14968 break;
14969
14973 break;
14974 }
14975 }
14976
14977 if (var->hasLocalStorage() &&
14978 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14980
14981 // Warn about externally-visible variables being defined without a
14982 // prior declaration. We only want to do this for global
14983 // declarations, but we also specifically need to avoid doing it for
14984 // class members because the linkage of an anonymous class can
14985 // change if it's later given a typedef name.
14986 if (var->isThisDeclarationADefinition() &&
14987 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14988 var->isExternallyVisible() && var->hasLinkage() &&
14989 !var->isInline() && !var->getDescribedVarTemplate() &&
14990 var->getStorageClass() != SC_Register &&
14992 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14993 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14994 var->getLocation())) {
14995 // Find a previous declaration that's not a definition.
14996 VarDecl *prev = var->getPreviousDecl();
14997 while (prev && prev->isThisDeclarationADefinition())
14998 prev = prev->getPreviousDecl();
14999
15000 if (!prev) {
15001 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
15002 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
15003 << /* variable */ 0;
15004 }
15005 }
15006
15007 // Cache the result of checking for constant initialization.
15008 std::optional<bool> CacheHasConstInit;
15009 const Expr *CacheCulprit = nullptr;
15010 auto checkConstInit = [&]() mutable {
15011 const Expr *Init = var->getInit();
15012 if (Init->isInstantiationDependent())
15013 return true;
15014
15015 if (!CacheHasConstInit)
15016 CacheHasConstInit = var->getInit()->isConstantInitializer(
15017 Context, var->getType()->isReferenceType(), &CacheCulprit);
15018 return *CacheHasConstInit;
15019 };
15020
15021 if (var->getTLSKind() == VarDecl::TLS_Static) {
15022 if (var->getType().isDestructedType()) {
15023 // GNU C++98 edits for __thread, [basic.start.term]p3:
15024 // The type of an object with thread storage duration shall not
15025 // have a non-trivial destructor.
15026 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
15028 Diag(var->getLocation(), diag::note_use_thread_local);
15029 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
15030 if (!checkConstInit()) {
15031 // GNU C++98 edits for __thread, [basic.start.init]p4:
15032 // An object of thread storage duration shall not require dynamic
15033 // initialization.
15034 // FIXME: Need strict checking here.
15035 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
15036 << CacheCulprit->getSourceRange();
15038 Diag(var->getLocation(), diag::note_use_thread_local);
15039 }
15040 }
15041 }
15042
15043
15044 if (!var->getType()->isStructureType() && var->hasInit() &&
15045 isa<InitListExpr>(var->getInit())) {
15046 const auto *ILE = cast<InitListExpr>(var->getInit());
15047 unsigned NumInits = ILE->getNumInits();
15048 if (NumInits > 2)
15049 for (unsigned I = 0; I < NumInits; ++I) {
15050 const auto *Init = ILE->getInit(I);
15051 if (!Init)
15052 break;
15053 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15054 if (!SL)
15055 break;
15056
15057 unsigned NumConcat = SL->getNumConcatenated();
15058 // Diagnose missing comma in string array initialization.
15059 // Do not warn when all the elements in the initializer are concatenated
15060 // together. Do not warn for macros too.
15061 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15062 bool OnlyOneMissingComma = true;
15063 for (unsigned J = I + 1; J < NumInits; ++J) {
15064 const auto *Init = ILE->getInit(J);
15065 if (!Init)
15066 break;
15067 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15068 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15069 OnlyOneMissingComma = false;
15070 break;
15071 }
15072 }
15073
15074 if (OnlyOneMissingComma) {
15076 for (unsigned i = 0; i < NumConcat - 1; ++i)
15077 Hints.push_back(FixItHint::CreateInsertion(
15078 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
15079
15080 Diag(SL->getStrTokenLoc(1),
15081 diag::warn_concatenated_literal_array_init)
15082 << Hints;
15083 Diag(SL->getBeginLoc(),
15084 diag::note_concatenated_string_literal_silence);
15085 }
15086 // In any case, stop now.
15087 break;
15088 }
15089 }
15090 }
15091
15092
15093 QualType type = var->getType();
15094
15095 if (var->hasAttr<BlocksAttr>())
15097
15098 Expr *Init = var->getInit();
15099 bool GlobalStorage = var->hasGlobalStorage();
15100 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15101 QualType baseType = Context.getBaseElementType(type);
15102 bool HasConstInit = true;
15103
15104 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15105 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
15106 << var;
15107
15108 // Check whether the initializer is sufficiently constant.
15109 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15110 !type->isDependentType() && Init && !Init->isValueDependent() &&
15111 (GlobalStorage || var->isConstexpr() ||
15112 var->mightBeUsableInConstantExpressions(Context))) {
15113 // If this variable might have a constant initializer or might be usable in
15114 // constant expressions, check whether or not it actually is now. We can't
15115 // do this lazily, because the result might depend on things that change
15116 // later, such as which constexpr functions happen to be defined.
15118 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15119 // Prior to C++11, in contexts where a constant initializer is required,
15120 // the set of valid constant initializers is described by syntactic rules
15121 // in [expr.const]p2-6.
15122 // FIXME: Stricter checking for these rules would be useful for constinit /
15123 // -Wglobal-constructors.
15124 HasConstInit = checkConstInit();
15125
15126 // Compute and cache the constant value, and remember that we have a
15127 // constant initializer.
15128 if (HasConstInit) {
15129 if (var->isStaticDataMember() && !var->isInline() &&
15130 var->getLexicalDeclContext()->isRecord() &&
15131 type->isIntegralOrEnumerationType()) {
15132 // In C++98, in-class initialization for a static data member must
15133 // be an integer constant expression.
15134 if (!Init->isIntegerConstantExpr(Context)) {
15135 Diag(Init->getExprLoc(),
15136 diag::ext_in_class_initializer_non_constant)
15137 << Init->getSourceRange();
15138 }
15139 }
15140 (void)var->checkForConstantInitialization(Notes);
15141 Notes.clear();
15142 } else if (CacheCulprit) {
15143 Notes.emplace_back(CacheCulprit->getExprLoc(),
15144 PDiag(diag::note_invalid_subexpr_in_const_expr));
15145 Notes.back().second << CacheCulprit->getSourceRange();
15146 }
15147 } else {
15148 // Evaluate the initializer to see if it's a constant initializer.
15149 HasConstInit = var->checkForConstantInitialization(Notes);
15150 }
15151
15152 if (HasConstInit) {
15153 // FIXME: Consider replacing the initializer with a ConstantExpr.
15154 } else if (var->isConstexpr()) {
15155 SourceLocation DiagLoc = var->getLocation();
15156 // If the note doesn't add any useful information other than a source
15157 // location, fold it into the primary diagnostic.
15158 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15159 diag::note_invalid_subexpr_in_const_expr) {
15160 DiagLoc = Notes[0].first;
15161 Notes.clear();
15162 }
15163 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
15164 << var << Init->getSourceRange();
15165 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15166 Diag(Notes[I].first, Notes[I].second);
15167 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15168 auto *Attr = var->getAttr<ConstInitAttr>();
15169 Diag(var->getLocation(), diag::err_require_constant_init_failed)
15170 << Init->getSourceRange();
15171 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
15172 << Attr->getRange() << Attr->isConstinit();
15173 for (auto &it : Notes)
15174 Diag(it.first, it.second);
15175 } else if (var->isStaticDataMember() && !var->isInline() &&
15176 var->getLexicalDeclContext()->isRecord()) {
15177 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
15178 << Init->getSourceRange();
15179 for (auto &it : Notes)
15180 Diag(it.first, it.second);
15181 var->setInvalidDecl();
15182 } else if (IsGlobal &&
15183 !getDiagnostics().isIgnored(diag::warn_global_constructor,
15184 var->getLocation())) {
15185 // Warn about globals which don't have a constant initializer. Don't
15186 // warn about globals with a non-trivial destructor because we already
15187 // warned about them.
15188 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15189 if (!(RD && !RD->hasTrivialDestructor())) {
15190 // checkConstInit() here permits trivial default initialization even in
15191 // C++11 onwards, where such an initializer is not a constant initializer
15192 // but nonetheless doesn't require a global constructor.
15193 if (!checkConstInit())
15194 Diag(var->getLocation(), diag::warn_global_constructor)
15195 << Init->getSourceRange();
15196 }
15197 }
15198 }
15199
15200 // Apply section attributes and pragmas to global variables.
15201 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15203 PragmaStack<StringLiteral *> *Stack = nullptr;
15204 int SectionFlags = ASTContext::PSF_Read;
15205 bool MSVCEnv =
15206 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15207 std::optional<QualType::NonConstantStorageReason> Reason;
15208 if (HasConstInit &&
15209 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
15210 Stack = &ConstSegStack;
15211 } else {
15212 SectionFlags |= ASTContext::PSF_Write;
15213 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15214 }
15215 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15216 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15217 SectionFlags |= ASTContext::PSF_Implicit;
15218 UnifySection(SA->getName(), SectionFlags, var);
15219 } else if (Stack->CurrentValue) {
15220 if (Stack != &ConstSegStack && MSVCEnv &&
15221 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15222 var->getType().isConstQualified()) {
15223 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15224 NonConstNonReferenceType) &&
15225 "This case should've already been handled elsewhere");
15226 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15227 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15229 : *Reason);
15230 }
15231 SectionFlags |= ASTContext::PSF_Implicit;
15232 auto SectionName = Stack->CurrentValue->getString();
15233 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15234 Stack->CurrentPragmaLocation,
15235 SectionAttr::Declspec_allocate));
15236 if (UnifySection(SectionName, SectionFlags, var))
15237 var->dropAttr<SectionAttr>();
15238 }
15239
15240 // Apply the init_seg attribute if this has an initializer. If the
15241 // initializer turns out to not be dynamic, we'll end up ignoring this
15242 // attribute.
15243 if (CurInitSeg && var->getInit())
15244 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15245 CurInitSegLoc));
15246 }
15247
15248 // All the following checks are C++ only.
15249 if (!getLangOpts().CPlusPlus) {
15250 // If this variable must be emitted, add it as an initializer for the
15251 // current module.
15252 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15253 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15254 return;
15255 }
15256
15258
15259 // Require the destructor.
15260 if (!type->isDependentType())
15261 if (auto *RD = baseType->getAsCXXRecordDecl())
15263
15264 // If this variable must be emitted, add it as an initializer for the current
15265 // module.
15266 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty() &&
15267 (ModuleScopes.back().Module->isHeaderLikeModule() ||
15268 // For named modules, we may only emit non discardable variables.
15269 !isDiscardableGVALinkage(Context.GetGVALinkageForVariable(var))))
15270 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15271
15272 // Build the bindings if this is a structured binding declaration.
15273 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15275}
15276
15278 assert(VD->isStaticLocal());
15279
15280 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15281
15282 // Find outermost function when VD is in lambda function.
15283 while (FD && !getDLLAttr(FD) &&
15284 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15285 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15286 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15287 }
15288
15289 if (!FD)
15290 return;
15291
15292 // Static locals inherit dll attributes from their function.
15293 if (Attr *A = getDLLAttr(FD)) {
15294 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15295 NewAttr->setInherited(true);
15296 VD->addAttr(NewAttr);
15297 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15298 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15299 NewAttr->setInherited(true);
15300 VD->addAttr(NewAttr);
15301
15302 // Export this function to enforce exporting this static variable even
15303 // if it is not used in this compilation unit.
15304 if (!FD->hasAttr<DLLExportAttr>())
15305 FD->addAttr(NewAttr);
15306
15307 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15308 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15309 NewAttr->setInherited(true);
15310 VD->addAttr(NewAttr);
15311 }
15312}
15313
15315 assert(VD->getTLSKind());
15316
15317 // Perform TLS alignment check here after attributes attached to the variable
15318 // which may affect the alignment have been processed. Only perform the check
15319 // if the target has a maximum TLS alignment (zero means no constraints).
15320 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15321 // Protect the check so that it's not performed on dependent types and
15322 // dependent alignments (we can't determine the alignment in that case).
15323 if (!VD->hasDependentAlignment()) {
15324 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15325 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15326 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15327 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15328 << (unsigned)MaxAlignChars.getQuantity();
15329 }
15330 }
15331 }
15332}
15333
15335 // Note that we are no longer parsing the initializer for this declaration.
15336 ParsingInitForAutoVars.erase(ThisDecl);
15337
15338 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15339 if (!VD)
15340 return;
15341
15342 // Emit any deferred warnings for the variable's initializer, even if the
15343 // variable is invalid
15344 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15345
15346 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15348 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15349 if (PragmaClangBSSSection.Valid)
15350 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15351 Context, PragmaClangBSSSection.SectionName,
15352 PragmaClangBSSSection.PragmaLocation));
15353 if (PragmaClangDataSection.Valid)
15354 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15355 Context, PragmaClangDataSection.SectionName,
15356 PragmaClangDataSection.PragmaLocation));
15357 if (PragmaClangRodataSection.Valid)
15358 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15359 Context, PragmaClangRodataSection.SectionName,
15360 PragmaClangRodataSection.PragmaLocation));
15361 if (PragmaClangRelroSection.Valid)
15362 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15363 Context, PragmaClangRelroSection.SectionName,
15364 PragmaClangRelroSection.PragmaLocation));
15365 }
15366
15367 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15368 for (auto *BD : DD->bindings()) {
15370 }
15371 }
15372
15373 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15375
15376 checkAttributesAfterMerging(*this, *VD);
15377
15378 if (VD->isStaticLocal())
15380
15381 if (VD->getTLSKind())
15383
15384 // Perform check for initializers of device-side global variables.
15385 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15386 // 7.5). We must also apply the same checks to all __shared__
15387 // variables whether they are local or not. CUDA also allows
15388 // constant initializers for __constant__ and __device__ variables.
15389 if (getLangOpts().CUDA)
15391
15392 // Grab the dllimport or dllexport attribute off of the VarDecl.
15393 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15394
15395 // Imported static data members cannot be defined out-of-line.
15396 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15397 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15399 // We allow definitions of dllimport class template static data members
15400 // with a warning.
15403 bool IsClassTemplateMember =
15405 Context->getDescribedClassTemplate();
15406
15407 Diag(VD->getLocation(),
15408 IsClassTemplateMember
15409 ? diag::warn_attribute_dllimport_static_field_definition
15410 : diag::err_attribute_dllimport_static_field_definition);
15411 Diag(IA->getLocation(), diag::note_attribute);
15412 if (!IsClassTemplateMember)
15413 VD->setInvalidDecl();
15414 }
15415 }
15416
15417 // dllimport/dllexport variables cannot be thread local, their TLS index
15418 // isn't exported with the variable.
15419 if (DLLAttr && VD->getTLSKind()) {
15420 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15421 if (F && getDLLAttr(F)) {
15422 assert(VD->isStaticLocal());
15423 // But if this is a static local in a dlimport/dllexport function, the
15424 // function will never be inlined, which means the var would never be
15425 // imported, so having it marked import/export is safe.
15426 } else {
15427 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15428 << DLLAttr;
15429 VD->setInvalidDecl();
15430 }
15431 }
15432
15433 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15434 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15435 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15436 << Attr;
15437 VD->dropAttr<UsedAttr>();
15438 }
15439 }
15440 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15441 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15442 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15443 << Attr;
15444 VD->dropAttr<RetainAttr>();
15445 }
15446 }
15447
15448 const DeclContext *DC = VD->getDeclContext();
15449 // If there's a #pragma GCC visibility in scope, and this isn't a class
15450 // member, set the visibility of this variable.
15453
15454 // FIXME: Warn on unused var template partial specializations.
15457
15458 // Now we have parsed the initializer and can update the table of magic
15459 // tag values.
15460 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15462 return;
15463
15464 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15465 const Expr *MagicValueExpr = VD->getInit();
15466 if (!MagicValueExpr) {
15467 continue;
15468 }
15469 std::optional<llvm::APSInt> MagicValueInt;
15470 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15471 Diag(I->getRange().getBegin(),
15472 diag::err_type_tag_for_datatype_not_ice)
15473 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15474 continue;
15475 }
15476 if (MagicValueInt->getActiveBits() > 64) {
15477 Diag(I->getRange().getBegin(),
15478 diag::err_type_tag_for_datatype_too_large)
15479 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15480 continue;
15481 }
15482 uint64_t MagicValue = MagicValueInt->getZExtValue();
15483 RegisterTypeTagForDatatype(I->getArgumentKind(),
15484 MagicValue,
15485 I->getMatchingCType(),
15486 I->getLayoutCompatible(),
15487 I->getMustBeNull());
15488 }
15489}
15490
15492 auto *VD = dyn_cast<VarDecl>(DD);
15493 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15494}
15495
15497 ArrayRef<Decl *> Group) {
15499
15500 if (DS.isTypeSpecOwned())
15501 Decls.push_back(DS.getRepAsDecl());
15502
15503 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15504 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15505 bool DiagnosedMultipleDecomps = false;
15506 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15507 bool DiagnosedNonDeducedAuto = false;
15508
15509 for (Decl *D : Group) {
15510 if (!D)
15511 continue;
15512 // Check if the Decl has been declared in '#pragma omp declare target'
15513 // directive and has static storage duration.
15514 if (auto *VD = dyn_cast<VarDecl>(D);
15515 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15516 VD->hasGlobalStorage())
15518 // For declarators, there are some additional syntactic-ish checks we need
15519 // to perform.
15520 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15521 if (!FirstDeclaratorInGroup)
15522 FirstDeclaratorInGroup = DD;
15523 if (!FirstDecompDeclaratorInGroup)
15524 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15525 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15526 !hasDeducedAuto(DD))
15527 FirstNonDeducedAutoInGroup = DD;
15528
15529 if (FirstDeclaratorInGroup != DD) {
15530 // A decomposition declaration cannot be combined with any other
15531 // declaration in the same group.
15532 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15533 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15534 diag::err_decomp_decl_not_alone)
15535 << FirstDeclaratorInGroup->getSourceRange()
15536 << DD->getSourceRange();
15537 DiagnosedMultipleDecomps = true;
15538 }
15539
15540 // A declarator that uses 'auto' in any way other than to declare a
15541 // variable with a deduced type cannot be combined with any other
15542 // declarator in the same group.
15543 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15544 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15545 diag::err_auto_non_deduced_not_alone)
15546 << FirstNonDeducedAutoInGroup->getType()
15548 << FirstDeclaratorInGroup->getSourceRange()
15549 << DD->getSourceRange();
15550 DiagnosedNonDeducedAuto = true;
15551 }
15552 }
15553 }
15554
15555 Decls.push_back(D);
15556 }
15557
15559 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15560 handleTagNumbering(Tag, S);
15561 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15563 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15564 }
15565 }
15566
15567 return BuildDeclaratorGroup(Decls);
15568}
15569
15572 // C++14 [dcl.spec.auto]p7: (DR1347)
15573 // If the type that replaces the placeholder type is not the same in each
15574 // deduction, the program is ill-formed.
15575 if (Group.size() > 1) {
15577 VarDecl *DeducedDecl = nullptr;
15578 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15579 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15580 if (!D || D->isInvalidDecl())
15581 break;
15582 DeducedType *DT = D->getType()->getContainedDeducedType();
15583 if (!DT || DT->getDeducedType().isNull())
15584 continue;
15585 if (Deduced.isNull()) {
15586 Deduced = DT->getDeducedType();
15587 DeducedDecl = D;
15588 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15589 auto *AT = dyn_cast<AutoType>(DT);
15590 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15591 diag::err_auto_different_deductions)
15592 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15593 << DeducedDecl->getDeclName() << DT->getDeducedType()
15594 << D->getDeclName();
15595 if (DeducedDecl->hasInit())
15596 Dia << DeducedDecl->getInit()->getSourceRange();
15597 if (D->getInit())
15598 Dia << D->getInit()->getSourceRange();
15599 D->setInvalidDecl();
15600 break;
15601 }
15602 }
15603 }
15604
15606
15607 return DeclGroupPtrTy::make(
15608 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15609}
15610
15614
15616 // Don't parse the comment if Doxygen diagnostics are ignored.
15617 if (Group.empty() || !Group[0])
15618 return;
15619
15620 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15621 Group[0]->getLocation()) &&
15622 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15623 Group[0]->getLocation()))
15624 return;
15625
15626 if (Group.size() >= 2) {
15627 // This is a decl group. Normally it will contain only declarations
15628 // produced from declarator list. But in case we have any definitions or
15629 // additional declaration references:
15630 // 'typedef struct S {} S;'
15631 // 'typedef struct S *S;'
15632 // 'struct S *pS;'
15633 // FinalizeDeclaratorGroup adds these as separate declarations.
15634 Decl *MaybeTagDecl = Group[0];
15635 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15636 Group = Group.slice(1);
15637 }
15638 }
15639
15640 // FIXME: We assume every Decl in the group is in the same file.
15641 // This is false when preprocessor constructs the group from decls in
15642 // different files (e. g. macros or #include).
15643 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15644}
15645
15647 // Check that there are no default arguments inside the type of this
15648 // parameter.
15649 if (getLangOpts().CPlusPlus)
15651
15652 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15653 if (D.getCXXScopeSpec().isSet()) {
15654 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15655 << D.getCXXScopeSpec().getRange();
15656 }
15657
15658 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15659 // simple identifier except [...irrelevant cases...].
15660 switch (D.getName().getKind()) {
15662 break;
15663
15671 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15673 break;
15674
15677 // GetNameForDeclarator would not produce a useful name in this case.
15678 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15679 break;
15680 }
15681}
15682
15684 // This only matters in C.
15685 if (getLangOpts().CPlusPlus)
15686 return;
15687
15688 // This only matters if the declaration has a type.
15689 const auto *VD = dyn_cast<ValueDecl>(D);
15690 if (!VD)
15691 return;
15692
15693 // Get the type, this only matters for tag types.
15694 QualType QT = VD->getType();
15695 const auto *TD = QT->getAsTagDecl();
15696 if (!TD)
15697 return;
15698
15699 // Check if the tag declaration is lexically declared somewhere different
15700 // from the lexical declaration of the given object, then it will be hidden
15701 // in C++ and we should warn on it.
15702 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15703 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15704 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15705 Diag(TD->getLocation(), diag::note_declared_at);
15706 }
15707}
15708
15710 SourceLocation ExplicitThisLoc) {
15711 if (!ExplicitThisLoc.isValid())
15712 return;
15713 assert(S.getLangOpts().CPlusPlus &&
15714 "explicit parameter in non-cplusplus mode");
15715 if (!S.getLangOpts().CPlusPlus23)
15716 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15717 << P->getSourceRange();
15718
15719 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15720 // parameter pack.
15721 if (P->isParameterPack()) {
15722 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15723 << P->getSourceRange();
15724 return;
15725 }
15726 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15727 if (LambdaScopeInfo *LSI = S.getCurLambda())
15728 LSI->ExplicitObjectParameter = P;
15729}
15730
15732 SourceLocation ExplicitThisLoc) {
15733 const DeclSpec &DS = D.getDeclSpec();
15734
15735 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15736 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15737 // except for the special case of a single unnamed parameter of type void
15738 // with no storage class specifier, no type qualifier, and no following
15739 // ellipsis terminator.
15740 // Clang applies the C2y rules for 'register void' in all C language modes,
15741 // same as GCC, because it's questionable what that could possibly mean.
15742
15743 // C++03 [dcl.stc]p2 also permits 'auto'.
15744 StorageClass SC = SC_None;
15746 SC = SC_Register;
15747 // In C++11, the 'register' storage class specifier is deprecated.
15748 // In C++17, it is not allowed, but we tolerate it as an extension.
15749 if (getLangOpts().CPlusPlus11) {
15751 ? diag::ext_register_storage_class
15752 : diag::warn_deprecated_register)
15754 } else if (!getLangOpts().CPlusPlus &&
15756 D.getNumTypeObjects() == 0) {
15758 diag::err_invalid_storage_class_in_func_decl)
15761 }
15762 } else if (getLangOpts().CPlusPlus &&
15764 SC = SC_Auto;
15767 diag::err_invalid_storage_class_in_func_decl);
15769 }
15770
15772 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15774 if (DS.isInlineSpecified())
15775 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15776 << getLangOpts().CPlusPlus17;
15777 if (DS.hasConstexprSpecifier())
15778 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15779 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15780
15782
15784
15786 QualType parmDeclType = TInfo->getType();
15787
15788 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15789 const IdentifierInfo *II = D.getIdentifier();
15790 if (II) {
15793 LookupName(R, S);
15794 if (!R.empty()) {
15795 NamedDecl *PrevDecl = *R.begin();
15796 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15797 // Maybe we will complain about the shadowed template parameter.
15799 // Just pretend that we didn't see the previous declaration.
15800 PrevDecl = nullptr;
15801 }
15802 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15803 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15804 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15805 // Recover by removing the name
15806 II = nullptr;
15807 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15808 D.setInvalidType(true);
15809 }
15810 }
15811 }
15812
15813 // Incomplete resource arrays are not allowed as function parameters in HLSL
15814 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType()) {
15815 QualType EltTy = Context.getBaseElementType(parmDeclType);
15816 // `isCompleteType` forces completion of the element type so the resource
15817 // check is valid.
15818 if (!EltTy->isDependentType() &&
15819 isCompleteType(D.getIdentifierLoc(), EltTy) &&
15820 parmDeclType->isHLSLResourceRecordArray()) {
15822 diag::err_hlsl_incomplete_resource_array_in_function_param);
15823 D.setInvalidType(true);
15824 }
15825 }
15826
15827 // Temporarily put parameter variables in the translation unit, not
15828 // the enclosing context. This prevents them from accidentally
15829 // looking like class members in C++.
15830 ParmVarDecl *New =
15831 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15832 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15833
15834 if (D.isInvalidType())
15835 New->setInvalidDecl();
15836
15837 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15838
15839 assert(S->isFunctionPrototypeScope());
15840 assert(S->getFunctionPrototypeDepth() >= 1);
15841 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15843
15845
15846 // Add the parameter declaration into this scope.
15847 S->AddDecl(New);
15848 if (II)
15849 IdResolver.AddDecl(New);
15850
15852
15854 Diag(New->getLocation(), diag::err_module_private_local)
15857
15858 if (New->hasAttr<BlocksAttr>())
15859 Diag(New->getLocation(), diag::err_block_not_allowed_on)
15860 << diag::NotAllowedBlockVarReason::NonlocalVariable;
15861
15862 New->deduceParmAddressSpace(Context);
15863
15864 return New;
15865}
15866
15868 SourceLocation Loc,
15869 QualType T) {
15870 /* FIXME: setting StartLoc == Loc.
15871 Would it be worth to modify callers so as to provide proper source
15872 location for the unnamed parameters, embedding the parameter's type? */
15873 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15874 T, Context.getTrivialTypeSourceInfo(T, Loc),
15875 SC_None, nullptr);
15876 Param->setImplicit();
15877 return Param;
15878}
15879
15881 // Don't diagnose unused-parameter errors in template instantiations; we
15882 // will already have done so in the template itself.
15884 return;
15885
15886 for (const ParmVarDecl *Parameter : Parameters) {
15887 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15888 !Parameter->hasAttr<UnusedAttr>() &&
15889 !Parameter->getIdentifier()->isPlaceholder()) {
15890 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15891 << Parameter->getDeclName();
15892 }
15893 }
15894}
15895
15897 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15898 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15899 return;
15900
15901 // Warn if the return value is pass-by-value and larger than the specified
15902 // threshold.
15903 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15904 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15905 if (Size > LangOpts.NumLargeByValueCopy)
15906 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15907 }
15908
15909 // Warn if any parameter is pass-by-value and larger than the specified
15910 // threshold.
15911 for (const ParmVarDecl *Parameter : Parameters) {
15912 QualType T = Parameter->getType();
15913 if (T->isDependentType() || !T.isPODType(Context))
15914 continue;
15915 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15916 if (Size > LangOpts.NumLargeByValueCopy)
15917 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15918 << Parameter << Size;
15919 }
15920}
15921
15923 SourceLocation NameLoc,
15924 const IdentifierInfo *Name, QualType T,
15925 TypeSourceInfo *TSInfo, StorageClass SC) {
15926 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15927 if (getLangOpts().ObjCAutoRefCount &&
15928 T.getObjCLifetime() == Qualifiers::OCL_None &&
15929 T->isObjCLifetimeType()) {
15930
15931 Qualifiers::ObjCLifetime lifetime;
15932
15933 // Special cases for arrays:
15934 // - if it's const, use __unsafe_unretained
15935 // - otherwise, it's an error
15936 if (T->isArrayType()) {
15937 if (!T.isConstQualified()) {
15941 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15942 else
15943 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15944 << TSInfo->getTypeLoc().getSourceRange();
15945 }
15947 } else {
15948 lifetime = T->getObjCARCImplicitLifetime();
15949 }
15950 T = Context.getLifetimeQualifiedType(T, lifetime);
15951 }
15952
15953 if (getLangOpts().OpenCL) {
15954 assert(!isa<DecayedType>(T));
15955 if (T->isArrayType() && !T.hasAddressSpace()) {
15956 QualType ET = Context.getAsArrayType(T)->getElementType();
15957 if (!ET.hasAddressSpace()) {
15958 // Add the private address space to the contents of the pointer when a
15959 // pointer parameter is declared as an array and not declared.
15961 T = Context.getAddrSpaceQualType(T, ImplAS);
15962 T = QualType(Context.getAsArrayType(T), 0);
15963 }
15964 }
15965 }
15966
15967 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15968 Context.getAdjustedParameterType(T),
15969 TSInfo, SC, nullptr);
15970
15971 // Make a note if we created a new pack in the scope of a lambda, so that
15972 // we know that references to that pack must also be expanded within the
15973 // lambda scope.
15974 if (New->isParameterPack())
15975 if (auto *CSI = getEnclosingLambdaOrBlock())
15976 CSI->LocalPacks.push_back(New);
15977
15978 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15979 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15980 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15983
15984 // Parameter declarators cannot be interface types. All ObjC objects are
15985 // passed by reference.
15986 if (T->isObjCObjectType()) {
15987 SourceLocation TypeEndLoc =
15989 Diag(NameLoc,
15990 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15991 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15992 T = Context.getObjCObjectPointerType(T);
15993 New->setType(T);
15994 }
15995
15996 // __ptrauth is forbidden on parameters.
15997 if (T.getPointerAuth()) {
15998 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15999 New->setInvalidDecl();
16000 }
16001
16002 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
16003 // duration shall not be qualified by an address-space qualifier."
16004 // Since all parameters have automatic store duration, they can not have
16005 // an address space.
16006 if (T.getAddressSpace() != LangAS::Default &&
16007 // OpenCL allows function arguments declared to be an array of a type
16008 // to be qualified with an address space.
16009 !(getLangOpts().OpenCL &&
16010 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
16011 // WebAssembly allows reference types as parameters. Funcref in particular
16012 // lives in a different address space.
16013 !(T->isFunctionPointerType() &&
16014 T.getAddressSpace() == LangAS::wasm_funcref) &&
16015 // HLSL allows function arguments to be qualified with an address space
16016 // if the groupshared annotation is used.
16017 !(getLangOpts().HLSL &&
16018 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
16019 Diag(NameLoc, diag::err_arg_with_address_space);
16020 New->setInvalidDecl();
16021 }
16022
16023 // PPC MMA non-pointer types are not allowed as function argument types.
16024 if (Context.getTargetInfo().getTriple().isPPC64() &&
16025 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
16026 New->setInvalidDecl();
16027 }
16028
16029 return New;
16030}
16031
16033 SourceLocation LocAfterDecls) {
16035
16036 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
16037 // in the declaration list shall have at least one declarator, those
16038 // declarators shall only declare identifiers from the identifier list, and
16039 // every identifier in the identifier list shall be declared.
16040 //
16041 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
16042 // identifiers it names shall be declared in the declaration list."
16043 //
16044 // This is why we only diagnose in C99 and later. Note, the other conditions
16045 // listed are checked elsewhere.
16046 if (!FTI.hasPrototype) {
16047 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
16048 --i;
16049 if (FTI.Params[i].Param == nullptr) {
16050 if (getLangOpts().C99) {
16051 SmallString<256> Code;
16052 llvm::raw_svector_ostream(Code)
16053 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16054 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
16055 << FTI.Params[i].Ident
16056 << FixItHint::CreateInsertion(LocAfterDecls, Code);
16057 }
16058
16059 // Implicitly declare the argument as type 'int' for lack of a better
16060 // type.
16061 AttributeFactory attrs;
16062 DeclSpec DS(attrs);
16063 const char* PrevSpec; // unused
16064 unsigned DiagID; // unused
16065 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
16066 DiagID, Context.getPrintingPolicy());
16067 // Use the identifier location for the type source range.
16068 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16069 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16072 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
16073 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
16074 }
16075 }
16076 }
16077}
16078
16079Decl *
16081 MultiTemplateParamsArg TemplateParameterLists,
16082 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16083 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16084 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16085 Scope *ParentScope = FnBodyScope->getParent();
16086
16087 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16088 // we define a non-templated function definition, we will create a declaration
16089 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16090 // The base function declaration will have the equivalent of an `omp declare
16091 // variant` annotation which specifies the mangled definition as a
16092 // specialization function under the OpenMP context defined as part of the
16093 // `omp begin declare variant`.
16095 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16097 ParentScope, D, TemplateParameterLists, Bases);
16098
16100 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
16101 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
16102
16103 if (!Bases.empty())
16105 Bases);
16106
16107 return Dcl;
16108}
16109
16111 Consumer.HandleInlineFunctionDefinition(D);
16112}
16113
16115 const FunctionDecl *&PossiblePrototype) {
16116 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16117 Prev = Prev->getPreviousDecl()) {
16118 // Ignore any declarations that occur in function or method
16119 // scope, because they aren't visible from the header.
16120 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16121 continue;
16122
16123 PossiblePrototype = Prev;
16124 return Prev->getType()->isFunctionProtoType();
16125 }
16126 return false;
16127}
16128
16129static bool
16131 const FunctionDecl *&PossiblePrototype) {
16132 // Don't warn about invalid declarations.
16133 if (FD->isInvalidDecl())
16134 return false;
16135
16136 // Or declarations that aren't global.
16137 if (!FD->isGlobal())
16138 return false;
16139
16140 // Don't warn about C++ member functions.
16141 if (isa<CXXMethodDecl>(FD))
16142 return false;
16143
16144 // Don't warn about 'main'.
16146 if (IdentifierInfo *II = FD->getIdentifier())
16147 if (II->isStr("main") || II->isStr("efi_main"))
16148 return false;
16149
16150 if (FD->isMSVCRTEntryPoint())
16151 return false;
16152
16153 // Don't warn about inline functions.
16154 if (FD->isInlined())
16155 return false;
16156
16157 // Don't warn about function templates.
16159 return false;
16160
16161 // Don't warn about function template specializations.
16163 return false;
16164
16165 // Don't warn for OpenCL kernels.
16166 if (FD->hasAttr<DeviceKernelAttr>())
16167 return false;
16168
16169 // Don't warn on explicitly deleted functions.
16170 if (FD->isDeleted())
16171 return false;
16172
16173 // Don't warn on implicitly local functions (such as having local-typed
16174 // parameters).
16175 if (!FD->isExternallyVisible())
16176 return false;
16177
16178 // If we were able to find a potential prototype, don't warn.
16179 if (FindPossiblePrototype(FD, PossiblePrototype))
16180 return false;
16181
16182 return true;
16183}
16184
16185void
16187 const FunctionDecl *EffectiveDefinition,
16188 SkipBodyInfo *SkipBody) {
16189 const FunctionDecl *Definition = EffectiveDefinition;
16190 if (!Definition &&
16191 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16192 return;
16193
16194 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16195 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16196 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16197 // A merged copy of the same function, instantiated as a member of
16198 // the same class, is OK.
16199 if (declaresSameEntity(OrigFD, OrigDef) &&
16200 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
16202 return;
16203 }
16204 }
16205 }
16206
16208 return;
16209
16210 // Don't emit an error when this is redefinition of a typo-corrected
16211 // definition.
16213 return;
16214
16215 bool DefinitionVisible = false;
16216 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
16217 (Definition->getFormalLinkage() == Linkage::Internal ||
16218 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16219 !Definition->getTemplateParameterLists().empty())) {
16220 SkipBody->ShouldSkip = true;
16221 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16222 if (!DefinitionVisible) {
16223 if (auto *TD = Definition->getDescribedFunctionTemplate())
16226 }
16227 return;
16228 }
16229
16230 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16231 Definition->getStorageClass() == SC_Extern)
16232 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
16233 << FD << getLangOpts().CPlusPlus;
16234 else
16235 Diag(FD->getLocation(), diag::err_redefinition) << FD;
16236
16237 Diag(Definition->getLocation(), diag::note_previous_definition);
16238 FD->setInvalidDecl();
16239}
16240
16242 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16243
16245 LSI->CallOperator = CallOperator;
16246 LSI->Lambda = LambdaClass;
16247 LSI->ReturnType = CallOperator->getReturnType();
16248 // When this function is called in situation where the context of the call
16249 // operator is not entered, we set AfterParameterList to false, so that
16250 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16251 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16252 // where we would set the CurContext to the lambda operator before
16253 // substituting into it. In this case the flag needs to be true such that
16254 // tryCaptureVariable can correctly handle potential captures thereof.
16255 LSI->AfterParameterList = CurContext == CallOperator;
16256
16257 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16258 // used at the point of dealing with potential captures.
16259 //
16260 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16261 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16262 // associated. (Technically, we could recover that list from their
16263 // instantiation patterns, but for now, the GLTemplateParameterList seems
16264 // unnecessary in these cases.)
16265 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16266 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16267 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16268
16269 if (LCD == LCD_None)
16271 else if (LCD == LCD_ByCopy)
16273 else if (LCD == LCD_ByRef)
16275 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16276
16278 LSI->Mutable = !CallOperator->isConst();
16279 if (CallOperator->isExplicitObjectMemberFunction())
16280 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16281
16282 // Add the captures to the LSI so they can be noted as already
16283 // captured within tryCaptureVar.
16284 auto I = LambdaClass->field_begin();
16285 for (const auto &C : LambdaClass->captures()) {
16286 if (C.capturesVariable()) {
16287 ValueDecl *VD = C.getCapturedVar();
16288 if (VD->isInitCapture())
16289 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16290 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16291 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16292 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16293 /*EllipsisLoc*/C.isPackExpansion()
16294 ? C.getEllipsisLoc() : SourceLocation(),
16295 I->getType(), /*Invalid*/false);
16296
16297 } else if (C.capturesThis()) {
16298 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16299 C.getCaptureKind() == LCK_StarThis);
16300 } else {
16301 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16302 I->getType());
16303 }
16304 ++I;
16305 }
16306 return LSI;
16307}
16308
16310 SkipBodyInfo *SkipBody,
16311 FnBodyKind BodyKind) {
16312 if (!D) {
16313 // Parsing the function declaration failed in some way. Push on a fake scope
16314 // anyway so we can try to parse the function body.
16317 return D;
16318 }
16319
16320 FunctionDecl *FD = nullptr;
16321
16322 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16323 FD = FunTmpl->getTemplatedDecl();
16324 else
16325 FD = cast<FunctionDecl>(D);
16326
16327 // Do not push if it is a lambda because one is already pushed when building
16328 // the lambda in ActOnStartOfLambdaDefinition().
16329 if (!isLambdaCallOperator(FD))
16331 FD);
16332
16333 // Check for defining attributes before the check for redefinition.
16334 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16335 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16336 FD->dropAttr<AliasAttr>();
16337 FD->setInvalidDecl();
16338 }
16339 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16340 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16341 FD->dropAttr<IFuncAttr>();
16342 FD->setInvalidDecl();
16343 }
16344 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16345 if (Context.getTargetInfo().getTriple().isAArch64() &&
16346 !Context.getTargetInfo().hasFeature("fmv") &&
16347 !Attr->isDefaultVersion()) {
16348 // If function multi versioning disabled skip parsing function body
16349 // defined with non-default target_version attribute
16350 if (SkipBody)
16351 SkipBody->ShouldSkip = true;
16352 return nullptr;
16353 }
16354 }
16355
16356 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16357 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16358 Ctor->isDefaultConstructor() &&
16359 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16360 // If this is an MS ABI dllexport default constructor, instantiate any
16361 // default arguments.
16362 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
16364 }
16365 }
16366
16367 // See if this is a redefinition. If 'will have body' (or similar) is already
16368 // set, then these checks were already performed when it was set.
16369 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16371 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16372
16373 // If we're skipping the body, we're done. Don't enter the scope.
16374 if (SkipBody && SkipBody->ShouldSkip)
16375 return D;
16376 }
16377
16378 // Mark this function as "will have a body eventually". This lets users to
16379 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16380 // this function.
16381 FD->setWillHaveBody();
16382
16383 // If we are instantiating a generic lambda call operator, push
16384 // a LambdaScopeInfo onto the function stack. But use the information
16385 // that's already been calculated (ActOnLambdaExpr) to prime the current
16386 // LambdaScopeInfo.
16387 // When the template operator is being specialized, the LambdaScopeInfo,
16388 // has to be properly restored so that tryCaptureVariable doesn't try
16389 // and capture any new variables. In addition when calculating potential
16390 // captures during transformation of nested lambdas, it is necessary to
16391 // have the LSI properly restored.
16393 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16394 // specialized.
16396 Diag(FD->getLocation(), diag::err_lambda_explicit_temp_spec)
16397 << /*specialization*/ 0;
16399 Diag(RD->getLocation(), diag::note_defined_here) << RD;
16400
16401 FD->setInvalidDecl();
16403 } else {
16404 assert(inTemplateInstantiation() &&
16405 "There should be an active template instantiation on the stack "
16406 "when instantiating a generic lambda!");
16408 }
16409 } else {
16410 // Enter a new function scope
16412 }
16413
16414 // Builtin functions cannot be defined.
16415 if (unsigned BuiltinID = FD->getBuiltinID()) {
16416 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16417 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16418 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16419 FD->setInvalidDecl();
16420 }
16421 }
16422
16423 // The return type of a function definition must be complete (C99 6.9.1p3).
16424 // C++23 [dcl.fct.def.general]/p2
16425 // The type of [...] the return for a function definition
16426 // shall not be a (possibly cv-qualified) class type that is incomplete
16427 // or abstract within the function body unless the function is deleted.
16428 QualType ResultType = FD->getReturnType();
16429 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16430 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16431 (RequireCompleteType(FD->getLocation(), ResultType,
16432 diag::err_func_def_incomplete_result) ||
16434 diag::err_abstract_type_in_decl,
16436 FD->setInvalidDecl();
16437
16438 if (FnBodyScope)
16439 PushDeclContext(FnBodyScope, FD);
16440
16441 // Check the validity of our function parameters
16442 if (BodyKind != FnBodyKind::Delete)
16444 /*CheckParameterNames=*/true);
16445
16446 // Add non-parameter declarations already in the function to the current
16447 // scope.
16448 if (FnBodyScope) {
16449 for (Decl *NPD : FD->decls()) {
16450 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16451 if (!NonParmDecl)
16452 continue;
16453 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16454 "parameters should not be in newly created FD yet");
16455
16456 // If the decl has a name, make it accessible in the current scope.
16457 if (NonParmDecl->getDeclName())
16458 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16459
16460 // Similarly, dive into enums and fish their constants out, making them
16461 // accessible in this scope.
16462 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16463 for (auto *EI : ED->enumerators())
16464 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16465 }
16466 }
16467 }
16468
16469 // Introduce our parameters into the function scope
16470 for (auto *Param : FD->parameters()) {
16471 Param->setOwningFunction(FD);
16472
16473 // If this has an identifier, add it to the scope stack.
16474 if (Param->getIdentifier() && FnBodyScope) {
16475 CheckShadow(FnBodyScope, Param);
16476
16477 PushOnScopeChains(Param, FnBodyScope);
16478 }
16479 }
16480
16481 // C++ [module.import/6]
16482 // ...
16483 // A header unit shall not contain a definition of a non-inline function or
16484 // variable whose name has external linkage.
16485 //
16486 // Deleted and Defaulted functions are implicitly inline (but the
16487 // inline state is not set at this point, so check the BodyKind explicitly).
16488 // We choose to allow weak & selectany definitions, as they are common in
16489 // headers, and have semantics similar to inline definitions which are allowed
16490 // in header units.
16491 // FIXME: Consider an alternate location for the test where the inlined()
16492 // state is complete.
16493 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16494 !FD->isInvalidDecl() && !FD->isInlined() &&
16495 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16496 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16497 !FD->isTemplateInstantiation() &&
16498 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16499 assert(FD->isThisDeclarationADefinition());
16500 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16501 FD->setInvalidDecl();
16502 }
16503
16504 // Ensure that the function's exception specification is instantiated.
16505 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16507
16508 // dllimport cannot be applied to non-inline function definitions.
16509 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16510 !FD->isTemplateInstantiation()) {
16511 assert(!FD->hasAttr<DLLExportAttr>());
16512 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16513 FD->setInvalidDecl();
16514 return D;
16515 }
16516
16517 // Some function attributes (like OptimizeNoneAttr) need actions before
16518 // parsing body started.
16520
16521 // We want to attach documentation to original Decl (which might be
16522 // a function template).
16524 if (getCurLexicalContext()->isObjCContainer() &&
16525 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16526 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16527 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16528
16530
16531 if (!FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16532 FnBodyScope) {
16533 // An implicit call expression is synthesized for functions declared with
16534 // the sycl_kernel_entry_point attribute. The call may resolve to a
16535 // function template, a member function template, or a call operator
16536 // of a variable template depending on the results of unqualified lookup
16537 // for 'sycl_kernel_launch' from the beginning of the function body.
16538 // Performing that lookup requires the stack of parsing scopes active
16539 // when the definition is parsed and is thus done here; the result is
16540 // cached in FunctionScopeInfo and used to synthesize the (possibly
16541 // unresolved) call expression after the function body has been parsed.
16542 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16543 if (!SKEPAttr->isInvalidAttr()) {
16544 ExprResult LaunchIdExpr =
16545 SYCL().BuildSYCLKernelLaunchIdExpr(FD, SKEPAttr->getKernelName());
16546 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16547 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16548 // treated as an error in the definition of 'FD'; treating it as an error
16549 // of the declaration would affect overload resolution which would
16550 // potentially result in additional errors. If construction of
16551 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16552 // a null pointer value below; that is expected.
16553 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16554 }
16555 }
16556
16557 return D;
16558}
16559
16561 if (!FD || FD->isInvalidDecl())
16562 return;
16563 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16564 FD = TD->getTemplatedDecl();
16565 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16568 CurFPFeatures.applyChanges(FPO);
16569 FpPragmaStack.CurrentValue =
16570 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16571 }
16572}
16573
16575 ReturnStmt **Returns = Scope->Returns.data();
16576
16577 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16578 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16579 if (!NRVOCandidate->isNRVOVariable()) {
16580 Diag(Returns[I]->getRetValue()->getExprLoc(),
16581 diag::warn_not_eliding_copy_on_return);
16582 Returns[I]->setNRVOCandidate(nullptr);
16583 }
16584 }
16585 }
16586}
16587
16589 // We can't delay parsing the body of a constexpr function template (yet).
16591 return false;
16592
16593 // We can't delay parsing the body of a function template with a deduced
16594 // return type (yet).
16595 if (D.getDeclSpec().hasAutoTypeSpec()) {
16596 // If the placeholder introduces a non-deduced trailing return type,
16597 // we can still delay parsing it.
16598 if (D.getNumTypeObjects()) {
16599 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16600 if (Outer.Kind == DeclaratorChunk::Function &&
16601 Outer.Fun.hasTrailingReturnType()) {
16602 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16603 return Ty.isNull() || !Ty->isUndeducedType();
16604 }
16605 }
16606 return false;
16607 }
16608
16609 return true;
16610}
16611
16613 // We cannot skip the body of a function (or function template) which is
16614 // constexpr, since we may need to evaluate its body in order to parse the
16615 // rest of the file.
16616 // We cannot skip the body of a function with an undeduced return type,
16617 // because any callers of that function need to know the type.
16618 if (const FunctionDecl *FD = D->getAsFunction()) {
16619 if (FD->isConstexpr())
16620 return false;
16621 // We can't simply call Type::isUndeducedType here, because inside template
16622 // auto can be deduced to a dependent type, which is not considered
16623 // "undeduced".
16624 if (FD->getReturnType()->getContainedDeducedType())
16625 return false;
16626 }
16627 return Consumer.shouldSkipFunctionBody(D);
16628}
16629
16631 if (!Decl)
16632 return nullptr;
16633 if (FunctionDecl *FD = Decl->getAsFunction())
16634 FD->setHasSkippedBody();
16635 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16636 MD->setHasSkippedBody();
16637 return Decl;
16638}
16639
16640/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16641/// body.
16643public:
16644 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16646 if (!IsLambda)
16647 S.PopExpressionEvaluationContext();
16648 }
16649
16650private:
16651 Sema &S;
16652 bool IsLambda = false;
16653};
16654
16656 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16657
16658 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16659 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16660 if (!Inserted)
16661 return It->second;
16662
16663 bool R = false;
16664 const BlockDecl *CurBD = BD;
16665
16666 do {
16667 R = !CurBD->doesNotEscape();
16668 if (R)
16669 break;
16670 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16671 } while (CurBD);
16672
16673 return It->second = R;
16674 };
16675
16676 // If the location where 'self' is implicitly retained is inside a escaping
16677 // block, emit a diagnostic.
16678 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16680 if (IsOrNestedInEscapingBlock(P.second))
16681 S.Diag(P.first, diag::warn_implicitly_retains_self)
16682 << FixItHint::CreateInsertion(P.first, "self->");
16683}
16684
16685static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16686 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16687 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16688}
16689
16691 return methodHasName(FD, "get_return_object");
16692}
16693
16695 return FD->isStatic() &&
16696 methodHasName(FD, "get_return_object_on_allocation_failure");
16697}
16698
16701 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16702 return;
16703 // Allow some_promise_type::get_return_object().
16705 return;
16706 if (!FD->hasAttr<CoroWrapperAttr>())
16707 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16708}
16709
16710Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16711 bool RetainFunctionScopeInfo) {
16713 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16714
16715 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16716 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16717
16718 SourceLocation AnalysisLoc;
16719 if (Body)
16720 AnalysisLoc = Body->getEndLoc();
16721 else if (FD)
16722 AnalysisLoc = FD->getEndLoc();
16724 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16725 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16726
16727 // If we skip function body, we can't tell if a function is a coroutine.
16728 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16729 if (FSI->isCoroutine())
16731 else
16733 }
16734
16735 // Diagnose invalid SYCL kernel entry point function declarations
16736 // and build SYCLKernelCallStmts for valid ones.
16737 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16738 SYCLKernelEntryPointAttr *SKEPAttr =
16739 FD->getAttr<SYCLKernelEntryPointAttr>();
16740 if (FD->isDefaulted()) {
16741 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16742 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16743 SKEPAttr->setInvalidAttr();
16744 } else if (FD->isDeleted()) {
16745 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16746 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16747 SKEPAttr->setInvalidAttr();
16748 } else if (FSI->isCoroutine()) {
16749 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16750 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16751 SKEPAttr->setInvalidAttr();
16752 } else if (Body && isa<CXXTryStmt>(Body)) {
16753 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16754 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16755 SKEPAttr->setInvalidAttr();
16756 }
16757
16758 // Build an unresolved SYCL kernel call statement for a function template,
16759 // validate that a SYCL kernel call statement was instantiated for an
16760 // (implicit or explicit) instantiation of a function template, or otherwise
16761 // build a (resolved) SYCL kernel call statement for a non-templated
16762 // function or an explicit specialization.
16763 if (Body && !SKEPAttr->isInvalidAttr()) {
16764 StmtResult SR;
16765 if (FD->isTemplateInstantiation()) {
16766 // The function body should already be a SYCLKernelCallStmt in this
16767 // case, but might not be if there were previous errors.
16768 SR = Body;
16769 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16770 // If name lookup for a template named sycl_kernel_launch failed
16771 // earlier, don't try to build a SYCL kernel call statement as that
16772 // would cause additional errors to be issued; just proceed with the
16773 // original function body.
16774 SR = Body;
16775 } else if (FD->isTemplated()) {
16777 cast<CompoundStmt>(Body), getCurFunction()->SYCLKernelLaunchIdExpr);
16778 } else {
16780 FD, cast<CompoundStmt>(Body),
16781 getCurFunction()->SYCLKernelLaunchIdExpr);
16782 }
16783 // If construction of the replacement body fails, just continue with the
16784 // original function body. An early error return here is not valid; the
16785 // current declaration context and function scopes must be popped before
16786 // returning.
16787 if (SR.isUsable())
16788 Body = SR.get();
16789 }
16790 }
16791
16792 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16793 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16794 if (FD->isDeletedAsWritten())
16795 Diag(SEAttr->getLocation(),
16796 diag::err_sycl_external_invalid_deleted_function)
16797 << SEAttr;
16798 }
16799
16800 {
16801 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16802 // one is already popped when finishing the lambda in BuildLambdaExpr().
16803 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16804 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16805 if (FD) {
16806 // The function body and the DefaultedOrDeletedInfo, if present, use
16807 // the same storage; don't overwrite the latter if the former is null
16808 // (the body is initialised to null anyway, so even if the latter isn't
16809 // present, this would still be a no-op).
16810 if (Body)
16811 FD->setBody(Body);
16812 FD->setWillHaveBody(false);
16813
16814 if (getLangOpts().CPlusPlus14) {
16815 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16816 FD->getReturnType()->isUndeducedType()) {
16817 // For a function with a deduced result type to return void,
16818 // the result type as written must be 'auto' or 'decltype(auto)',
16819 // possibly cv-qualified or constrained, but not ref-qualified.
16820 if (!FD->getReturnType()->getAs<AutoType>()) {
16821 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16822 << FD->getReturnType();
16823 FD->setInvalidDecl();
16824 } else {
16825 // Falling off the end of the function is the same as 'return;'.
16826 Expr *Dummy = nullptr;
16828 FD, dcl->getLocation(), Dummy,
16829 FD->getReturnType()->getAs<AutoType>()))
16830 FD->setInvalidDecl();
16831 }
16832 }
16833 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16834 // In C++11, we don't use 'auto' deduction rules for lambda call
16835 // operators because we don't support return type deduction.
16836 auto *LSI = getCurLambda();
16837 if (LSI->HasImplicitReturnType) {
16839
16840 // C++11 [expr.prim.lambda]p4:
16841 // [...] if there are no return statements in the compound-statement
16842 // [the deduced type is] the type void
16843 QualType RetType =
16844 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16845
16846 // Update the return type to the deduced type.
16847 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16848 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16849 Proto->getExtProtoInfo()));
16850 }
16851 }
16852
16853 // If the function implicitly returns zero (like 'main') or is naked,
16854 // don't complain about missing return statements.
16855 // Clang implicitly returns 0 in C89 mode, but that's considered an
16856 // extension. The check is necessary to ensure the expected extension
16857 // warning is emitted in C89 mode.
16858 if ((FD->hasImplicitReturnZero() &&
16859 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16860 FD->hasAttr<NakedAttr>())
16862
16863 // MSVC permits the use of pure specifier (=0) on function definition,
16864 // defined at class scope, warn about this non-standard construct.
16865 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16866 !FD->isOutOfLine())
16867 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16868
16869 if (!FD->isInvalidDecl()) {
16870 // Don't diagnose unused parameters of defaulted, deleted or naked
16871 // functions.
16872 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16873 !FD->hasAttr<NakedAttr>())
16876 FD->getReturnType(), FD);
16877
16878 // If this is a structor, we need a vtable.
16879 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16880 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16881 else if (CXXDestructorDecl *Destructor =
16882 dyn_cast<CXXDestructorDecl>(FD))
16883 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16884
16885 // Try to apply the named return value optimization. We have to check
16886 // if we can do this here because lambdas keep return statements around
16887 // to deduce an implicit return type.
16888 if (FD->getReturnType()->isRecordType() &&
16890 computeNRVO(Body, FSI);
16891 }
16892
16893 // GNU warning -Wmissing-prototypes:
16894 // Warn if a global function is defined without a previous
16895 // prototype declaration. This warning is issued even if the
16896 // definition itself provides a prototype. The aim is to detect
16897 // global functions that fail to be declared in header files.
16898 const FunctionDecl *PossiblePrototype = nullptr;
16899 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16900 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16901
16902 if (PossiblePrototype) {
16903 // We found a declaration that is not a prototype,
16904 // but that could be a zero-parameter prototype
16905 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16906 TypeLoc TL = TI->getTypeLoc();
16908 Diag(PossiblePrototype->getLocation(),
16909 diag::note_declaration_not_a_prototype)
16910 << (FD->getNumParams() != 0)
16912 FTL.getRParenLoc(), "void")
16913 : FixItHint{});
16914 }
16915 } else {
16916 // Returns true if the token beginning at this Loc is `const`.
16917 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16918 const LangOptions &LangOpts) {
16919 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16920 if (LocInfo.first.isInvalid())
16921 return false;
16922
16923 bool Invalid = false;
16924 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16925 if (Invalid)
16926 return false;
16927
16928 if (LocInfo.second > Buffer.size())
16929 return false;
16930
16931 const char *LexStart = Buffer.data() + LocInfo.second;
16932 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16933
16934 return StartTok.consume_front("const") &&
16935 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16936 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16937 };
16938
16939 auto findBeginLoc = [&]() {
16940 // If the return type has `const` qualifier, we want to insert
16941 // `static` before `const` (and not before the typename).
16942 if ((FD->getReturnType()->isAnyPointerType() &&
16945 // But only do this if we can determine where the `const` is.
16946
16947 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16948 getLangOpts()))
16949
16950 return FD->getBeginLoc();
16951 }
16952 return FD->getTypeSpecStartLoc();
16953 };
16955 diag::note_static_for_internal_linkage)
16956 << /* function */ 1
16957 << (FD->getStorageClass() == SC_None
16958 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16959 : FixItHint{});
16960 }
16961 }
16962
16963 // We might not have found a prototype because we didn't wish to warn on
16964 // the lack of a missing prototype. Try again without the checks for
16965 // whether we want to warn on the missing prototype.
16966 if (!PossiblePrototype)
16967 (void)FindPossiblePrototype(FD, PossiblePrototype);
16968
16969 // If the function being defined does not have a prototype, then we may
16970 // need to diagnose it as changing behavior in C23 because we now know
16971 // whether the function accepts arguments or not. This only handles the
16972 // case where the definition has no prototype but does have parameters
16973 // and either there is no previous potential prototype, or the previous
16974 // potential prototype also has no actual prototype. This handles cases
16975 // like:
16976 // void f(); void f(a) int a; {}
16977 // void g(a) int a; {}
16978 // See MergeFunctionDecl() for other cases of the behavior change
16979 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16980 // type without a prototype.
16981 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16982 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16983 !PossiblePrototype->isImplicit()))) {
16984 // The function definition has parameters, so this will change behavior
16985 // in C23. If there is a possible prototype, it comes before the
16986 // function definition.
16987 // FIXME: The declaration may have already been diagnosed as being
16988 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16989 // there's no way to test for the "changes behavior" condition in
16990 // SemaType.cpp when forming the declaration's function type. So, we do
16991 // this awkward dance instead.
16992 //
16993 // If we have a possible prototype and it declares a function with a
16994 // prototype, we don't want to diagnose it; if we have a possible
16995 // prototype and it has no prototype, it may have already been
16996 // diagnosed in SemaType.cpp as deprecated depending on whether
16997 // -Wstrict-prototypes is enabled. If we already warned about it being
16998 // deprecated, add a note that it also changes behavior. If we didn't
16999 // warn about it being deprecated (because the diagnostic is not
17000 // enabled), warn now that it is deprecated and changes behavior.
17001
17002 // This K&R C function definition definitely changes behavior in C23,
17003 // so diagnose it.
17004 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
17005 << /*definition*/ 1 << /* not supported in C23 */ 0;
17006
17007 // If we have a possible prototype for the function which is a user-
17008 // visible declaration, we already tested that it has no prototype.
17009 // This will change behavior in C23. This gets a warning rather than a
17010 // note because it's the same behavior-changing problem as with the
17011 // definition.
17012 if (PossiblePrototype)
17013 Diag(PossiblePrototype->getLocation(),
17014 diag::warn_non_prototype_changes_behavior)
17015 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
17016 << /*definition*/ 1;
17017 }
17018
17019 // Warn on CPUDispatch with an actual body.
17020 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
17021 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
17022 if (!CmpndBody->body_empty())
17023 Diag(CmpndBody->body_front()->getBeginLoc(),
17024 diag::warn_dispatch_body_ignored);
17025
17026 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
17027 const CXXMethodDecl *KeyFunction;
17028 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
17029 MD->isVirtual() &&
17030 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
17031 MD == KeyFunction->getCanonicalDecl()) {
17032 // Update the key-function state if necessary for this ABI.
17033 if (FD->isInlined() &&
17034 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
17035 Context.setNonKeyFunction(MD);
17036
17037 // If the newly-chosen key function is already defined, then we
17038 // need to mark the vtable as used retroactively.
17039 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
17040 const FunctionDecl *Definition;
17041 if (KeyFunction && KeyFunction->isDefined(Definition))
17042 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
17043 } else {
17044 // We just defined they key function; mark the vtable as used.
17045 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
17046 }
17047 }
17048 }
17049
17050 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
17051 "Function parsing confused");
17052 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
17053 assert(MD == getCurMethodDecl() && "Method parsing confused");
17054 MD->setBody(Body);
17055 if (!MD->isInvalidDecl()) {
17057 MD->getReturnType(), MD);
17058
17059 if (Body)
17060 computeNRVO(Body, FSI);
17061 }
17062 if (FSI->ObjCShouldCallSuper) {
17063 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
17064 << MD->getSelector().getAsString();
17065 FSI->ObjCShouldCallSuper = false;
17066 }
17068 const ObjCMethodDecl *InitMethod = nullptr;
17069 bool isDesignated =
17070 MD->isDesignatedInitializerForTheInterface(&InitMethod);
17071 assert(isDesignated && InitMethod);
17072 (void)isDesignated;
17073
17074 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17075 auto IFace = MD->getClassInterface();
17076 if (!IFace)
17077 return false;
17078 auto SuperD = IFace->getSuperClass();
17079 if (!SuperD)
17080 return false;
17081 return SuperD->getIdentifier() ==
17082 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
17083 };
17084 // Don't issue this warning for unavailable inits or direct subclasses
17085 // of NSObject.
17086 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17087 Diag(MD->getLocation(),
17088 diag::warn_objc_designated_init_missing_super_call);
17089 Diag(InitMethod->getLocation(),
17090 diag::note_objc_designated_init_marked_here);
17091 }
17093 }
17094 if (FSI->ObjCWarnForNoInitDelegation) {
17095 // Don't issue this warning for unavailable inits.
17096 if (!MD->isUnavailable())
17097 Diag(MD->getLocation(),
17098 diag::warn_objc_secondary_init_missing_init_call);
17099 FSI->ObjCWarnForNoInitDelegation = false;
17100 }
17101
17103 } else {
17104 // Parsing the function declaration failed in some way. Pop the fake scope
17105 // we pushed on.
17106 PopFunctionScopeInfo(ActivePolicy, dcl);
17107 return nullptr;
17108 }
17109
17110 if (Body) {
17113 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17115 }
17116
17117 assert(!FSI->ObjCShouldCallSuper &&
17118 "This should only be set for ObjC methods, which should have been "
17119 "handled in the block above.");
17120
17121 // Verify and clean out per-function state.
17122 if (Body && (!FD || !FD->isDefaulted())) {
17123 // C++ constructors that have function-try-blocks can't have return
17124 // statements in the handlers of that block. (C++ [except.handle]p14)
17125 // Verify this.
17126 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
17128
17129 // Verify that gotos and switch cases don't jump into scopes illegally.
17130 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17132
17133 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
17134 if (!Destructor->getParent()->isDependentType())
17136
17138 Destructor->getParent());
17139 }
17140
17141 // If any errors have occurred, clear out any temporaries that may have
17142 // been leftover. This ensures that these temporaries won't be picked up
17143 // for deletion in some later function.
17146 getDiagnostics().getSuppressAllDiagnostics()) {
17148 }
17150 // Since the body is valid, issue any analysis-based warnings that are
17151 // enabled.
17152 ActivePolicy = &WP;
17153 }
17154
17155 if (!IsInstantiation && FD &&
17156 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17157 !FD->isInvalidDecl() &&
17159 FD->setInvalidDecl();
17160
17161 if (FD && FD->hasAttr<NakedAttr>()) {
17162 for (const Stmt *S : Body->children()) {
17163 // Allow local register variables without initializer as they don't
17164 // require prologue.
17165 bool RegisterVariables = false;
17166 if (auto *DS = dyn_cast<DeclStmt>(S)) {
17167 for (const auto *Decl : DS->decls()) {
17168 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
17169 RegisterVariables =
17170 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17171 if (!RegisterVariables)
17172 break;
17173 }
17174 }
17175 }
17176 if (RegisterVariables)
17177 continue;
17178 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
17179 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
17180 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
17181 FD->setInvalidDecl();
17182 break;
17183 }
17184 }
17185 }
17186
17187 assert(ExprCleanupObjects.size() ==
17188 ExprEvalContexts.back().NumCleanupObjects &&
17189 "Leftover temporaries in function");
17190 assert(!Cleanup.exprNeedsCleanups() &&
17191 "Unaccounted cleanups in function");
17192 assert(MaybeODRUseExprs.empty() &&
17193 "Leftover expressions for odr-use checking");
17194 }
17195 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17196 // the declaration context below. Otherwise, we're unable to transform
17197 // 'this' expressions when transforming immediate context functions.
17198
17199 if (FD)
17201
17202 if (!IsInstantiation)
17204
17205 if (!RetainFunctionScopeInfo)
17206 PopFunctionScopeInfo(ActivePolicy, dcl);
17207 // If any errors have occurred, clear out any temporaries that may have
17208 // been leftover. This ensures that these temporaries won't be picked up for
17209 // deletion in some later function.
17212 }
17213
17214 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17215 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17216 auto ES = getEmissionStatus(FD);
17220 }
17221
17222 if (FD && !FD->isDeleted())
17223 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
17224
17225 return dcl;
17226}
17227
17228/// When we finish delayed parsing of an attribute, we must attach it to the
17229/// relevant Decl.
17231 ParsedAttributes &Attrs) {
17232 // Always attach attributes to the underlying decl.
17233 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
17234 D = TD->getTemplatedDecl();
17235 ProcessDeclAttributeList(S, D, Attrs);
17236 ProcessAPINotes(D);
17237
17238 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
17239 if (Method->isStatic())
17241}
17242
17244 IdentifierInfo &II, Scope *S) {
17245 // It is not valid to implicitly define a function in C23.
17246 assert(LangOpts.implicitFunctionsAllowed() &&
17247 "Implicit function declarations aren't allowed in this language mode");
17248
17249 // Find the scope in which the identifier is injected and the corresponding
17250 // DeclContext.
17251 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17252 // In that case, we inject the declaration into the translation unit scope
17253 // instead.
17254 Scope *BlockScope = S;
17255 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17256 BlockScope = BlockScope->getParent();
17257
17258 // Loop until we find a DeclContext that is either a function/method or the
17259 // translation unit, which are the only two valid places to implicitly define
17260 // a function. This avoids accidentally defining the function within a tag
17261 // declaration, for example.
17262 Scope *ContextScope = BlockScope;
17263 while (!ContextScope->getEntity() ||
17264 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17265 !ContextScope->getEntity()->isTranslationUnit()))
17266 ContextScope = ContextScope->getParent();
17267 ContextRAII SavedContext(*this, ContextScope->getEntity());
17268
17269 // Before we produce a declaration for an implicitly defined
17270 // function, see whether there was a locally-scoped declaration of
17271 // this name as a function or variable. If so, use that
17272 // (non-visible) declaration, and complain about it.
17273 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
17274 if (ExternCPrev) {
17275 // We still need to inject the function into the enclosing block scope so
17276 // that later (non-call) uses can see it.
17277 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
17278
17279 // C89 footnote 38:
17280 // If in fact it is not defined as having type "function returning int",
17281 // the behavior is undefined.
17282 if (!isa<FunctionDecl>(ExternCPrev) ||
17283 !Context.typesAreCompatible(
17284 cast<FunctionDecl>(ExternCPrev)->getType(),
17285 Context.getFunctionNoProtoType(Context.IntTy))) {
17286 Diag(Loc, diag::ext_use_out_of_scope_declaration)
17287 << ExternCPrev << !getLangOpts().C99;
17288 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
17289 return ExternCPrev;
17290 }
17291 }
17292
17293 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17294 unsigned diag_id;
17295 if (II.getName().starts_with("__builtin_"))
17296 diag_id = diag::warn_builtin_unknown;
17297 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17298 else if (getLangOpts().C99)
17299 diag_id = diag::ext_implicit_function_decl_c99;
17300 else
17301 diag_id = diag::warn_implicit_function_decl;
17302
17303 TypoCorrection Corrected;
17304 // Because typo correction is expensive, only do it if the implicit
17305 // function declaration is going to be treated as an error.
17306 //
17307 // Perform the correction before issuing the main diagnostic, as some
17308 // consumers use typo-correction callbacks to enhance the main diagnostic.
17309 if (S && !ExternCPrev &&
17310 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17312 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17313 S, nullptr, CCC, CorrectTypoKind::NonError);
17314 }
17315
17316 Diag(Loc, diag_id) << &II;
17317 if (Corrected) {
17318 // If the correction is going to suggest an implicitly defined function,
17319 // skip the correction as not being a particularly good idea.
17320 bool Diagnose = true;
17321 if (const auto *D = Corrected.getCorrectionDecl())
17322 Diagnose = !D->isImplicit();
17323 if (Diagnose)
17324 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17325 /*ErrorRecovery*/ false);
17326 }
17327
17328 // If we found a prior declaration of this function, don't bother building
17329 // another one. We've already pushed that one into scope, so there's nothing
17330 // more to do.
17331 if (ExternCPrev)
17332 return ExternCPrev;
17333
17334 // Set a Declarator for the implicit definition: int foo();
17335 const char *Dummy;
17336 AttributeFactory attrFactory;
17337 DeclSpec DS(attrFactory);
17338 unsigned DiagID;
17339 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17340 Context.getPrintingPolicy());
17341 (void)Error; // Silence warning.
17342 assert(!Error && "Error setting up implicit decl!");
17343 SourceLocation NoLoc;
17345 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17346 /*IsAmbiguous=*/false,
17347 /*LParenLoc=*/NoLoc,
17348 /*Params=*/nullptr,
17349 /*NumParams=*/0,
17350 /*EllipsisLoc=*/NoLoc,
17351 /*RParenLoc=*/NoLoc,
17352 /*RefQualifierIsLvalueRef=*/true,
17353 /*RefQualifierLoc=*/NoLoc,
17354 /*MutableLoc=*/NoLoc, EST_None,
17355 /*ESpecRange=*/SourceRange(),
17356 /*Exceptions=*/nullptr,
17357 /*ExceptionRanges=*/nullptr,
17358 /*NumExceptions=*/0,
17359 /*NoexceptExpr=*/nullptr,
17360 /*ExceptionSpecTokens=*/nullptr,
17361 /*DeclsInPrototype=*/{}, Loc, Loc,
17362 D),
17363 std::move(DS.getAttributes()), SourceLocation());
17364 D.SetIdentifier(&II, Loc);
17365
17366 // Insert this function into the enclosing block scope.
17367 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17368 FD->setImplicit();
17369
17371
17372 return FD;
17373}
17374
17376 FunctionDecl *FD) {
17377 if (FD->isInvalidDecl())
17378 return;
17379
17380 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17381 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17382 return;
17383
17384 UnsignedOrNone AlignmentParam = std::nullopt;
17385 bool IsNothrow = false;
17386 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17387 return;
17388
17389 // C++2a [basic.stc.dynamic.allocation]p4:
17390 // An allocation function that has a non-throwing exception specification
17391 // indicates failure by returning a null pointer value. Any other allocation
17392 // function never returns a null pointer value and indicates failure only by
17393 // throwing an exception [...]
17394 //
17395 // However, -fcheck-new invalidates this possible assumption, so don't add
17396 // NonNull when that is enabled.
17397 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17398 !getLangOpts().CheckNew)
17399 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17400
17401 // C++2a [basic.stc.dynamic.allocation]p2:
17402 // An allocation function attempts to allocate the requested amount of
17403 // storage. [...] If the request succeeds, the value returned by a
17404 // replaceable allocation function is a [...] pointer value p0 different
17405 // from any previously returned value p1 [...]
17406 //
17407 // However, this particular information is being added in codegen,
17408 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17409
17410 // C++2a [basic.stc.dynamic.allocation]p2:
17411 // An allocation function attempts to allocate the requested amount of
17412 // storage. If it is successful, it returns the address of the start of a
17413 // block of storage whose length in bytes is at least as large as the
17414 // requested size.
17415 if (!FD->hasAttr<AllocSizeAttr>()) {
17416 FD->addAttr(AllocSizeAttr::CreateImplicit(
17417 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17418 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17419 }
17420
17421 // C++2a [basic.stc.dynamic.allocation]p3:
17422 // For an allocation function [...], the pointer returned on a successful
17423 // call shall represent the address of storage that is aligned as follows:
17424 // (3.1) If the allocation function takes an argument of type
17425 // std​::​align_­val_­t, the storage will have the alignment
17426 // specified by the value of this argument.
17427 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17428 FD->addAttr(AllocAlignAttr::CreateImplicit(
17429 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17430 }
17431
17432 // FIXME:
17433 // C++2a [basic.stc.dynamic.allocation]p3:
17434 // For an allocation function [...], the pointer returned on a successful
17435 // call shall represent the address of storage that is aligned as follows:
17436 // (3.2) Otherwise, if the allocation function is named operator new[],
17437 // the storage is aligned for any object that does not have
17438 // new-extended alignment ([basic.align]) and is no larger than the
17439 // requested size.
17440 // (3.3) Otherwise, the storage is aligned for any object that does not
17441 // have new-extended alignment and is of the requested size.
17442}
17443
17445 if (FD->isInvalidDecl())
17446 return;
17447
17448 // If this is a built-in function, map its builtin attributes to
17449 // actual attributes.
17450 if (unsigned BuiltinID = FD->getBuiltinID()) {
17451 // Handle printf-formatting attributes.
17452 unsigned FormatIdx;
17453 bool HasVAListArg;
17454 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17455 if (!FD->hasAttr<FormatAttr>()) {
17456 const char *fmt = "printf";
17457 unsigned int NumParams = FD->getNumParams();
17458 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17459 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17460 fmt = "NSString";
17461 FD->addAttr(FormatAttr::CreateImplicit(Context,
17462 &Context.Idents.get(fmt),
17463 FormatIdx+1,
17464 HasVAListArg ? 0 : FormatIdx+2,
17465 FD->getLocation()));
17466 }
17467 }
17468 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17469 HasVAListArg)) {
17470 if (!FD->hasAttr<FormatAttr>())
17471 FD->addAttr(FormatAttr::CreateImplicit(Context,
17472 &Context.Idents.get("scanf"),
17473 FormatIdx+1,
17474 HasVAListArg ? 0 : FormatIdx+2,
17475 FD->getLocation()));
17476 }
17477
17478 // Handle automatically recognized callbacks.
17479 SmallVector<int, 4> Encoding;
17480 if (!FD->hasAttr<CallbackAttr>() &&
17481 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17482 FD->addAttr(CallbackAttr::CreateImplicit(
17483 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17484
17485 // Mark const if we don't care about errno and/or floating point exceptions
17486 // that are the only thing preventing the function from being const. This
17487 // allows IRgen to use LLVM intrinsics for such functions.
17488 bool NoExceptions =
17490 bool ConstWithoutErrnoAndExceptions =
17491 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17492 bool ConstWithoutExceptions =
17493 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17494 if (!FD->hasAttr<ConstAttr>() &&
17495 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17496 (!ConstWithoutErrnoAndExceptions ||
17497 (!getLangOpts().MathErrno && NoExceptions)) &&
17498 (!ConstWithoutExceptions || NoExceptions))
17499 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17500
17501 // We make "fma" on GNU or Windows const because we know it does not set
17502 // errno in those environments even though it could set errno based on the
17503 // C standard.
17504 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17505 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17506 !FD->hasAttr<ConstAttr>()) {
17507 switch (BuiltinID) {
17508 case Builtin::BI__builtin_fma:
17509 case Builtin::BI__builtin_fmaf:
17510 case Builtin::BI__builtin_fmal:
17511 case Builtin::BIfma:
17512 case Builtin::BIfmaf:
17513 case Builtin::BIfmal:
17514 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17515 break;
17516 default:
17517 break;
17518 }
17519 }
17520
17521 SmallVector<int, 4> Indxs;
17523 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17524 !FD->hasAttr<NonNullAttr>()) {
17526 for (int I : Indxs) {
17527 ParmVarDecl *PVD = FD->getParamDecl(I);
17528 QualType T = PVD->getType();
17529 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17530 PVD->setType(T);
17531 }
17532 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17534 for (int I : Indxs)
17535 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17536 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17537 ParamIndxs.size()));
17538 }
17539 }
17540 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17541 !FD->hasAttr<ReturnsTwiceAttr>())
17542 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17543 FD->getLocation()));
17544 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17545 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17546 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17547 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17548 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17549 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17550 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17551 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17552 // Add the appropriate attribute, depending on the CUDA compilation mode
17553 // and which target the builtin belongs to. For example, during host
17554 // compilation, aux builtins are __device__, while the rest are __host__.
17555 if (getLangOpts().CUDAIsDevice !=
17556 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17557 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17558 else
17559 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17560 }
17561
17562 // Add known guaranteed alignment for allocation functions.
17563 switch (BuiltinID) {
17564 case Builtin::BImemalign:
17565 case Builtin::BIaligned_alloc:
17566 if (!FD->hasAttr<AllocAlignAttr>())
17567 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17568 FD->getLocation()));
17569 break;
17570 default:
17571 break;
17572 }
17573
17574 // Add allocsize attribute for allocation functions.
17575 switch (BuiltinID) {
17576 case Builtin::BIcalloc:
17577 FD->addAttr(AllocSizeAttr::CreateImplicit(
17578 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17579 break;
17580 case Builtin::BImemalign:
17581 case Builtin::BIaligned_alloc:
17582 case Builtin::BIrealloc:
17583 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17584 ParamIdx(), FD->getLocation()));
17585 break;
17586 case Builtin::BImalloc:
17587 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17588 ParamIdx(), FD->getLocation()));
17589 break;
17590 default:
17591 break;
17592 }
17593 }
17594
17599
17600 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17601 // throw, add an implicit nothrow attribute to any extern "C" function we come
17602 // across.
17603 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17604 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17605 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17606 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17607 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17608 }
17609
17610 IdentifierInfo *Name = FD->getIdentifier();
17611 if (!Name)
17612 return;
17615 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17617 // Okay: this could be a libc/libm/Objective-C function we know
17618 // about.
17619 } else
17620 return;
17621
17622 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17623 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17624 // target-specific builtins, perhaps?
17625 if (!FD->hasAttr<FormatAttr>())
17626 FD->addAttr(FormatAttr::CreateImplicit(Context,
17627 &Context.Idents.get("printf"), 2,
17628 Name->isStr("vasprintf") ? 0 : 3,
17629 FD->getLocation()));
17630 }
17631
17632 if (Name->isStr("__CFStringMakeConstantString")) {
17633 // We already have a __builtin___CFStringMakeConstantString,
17634 // but builds that use -fno-constant-cfstrings don't go through that.
17635 if (!FD->hasAttr<FormatArgAttr>())
17636 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17637 FD->getLocation()));
17638 }
17639}
17640
17642 TypeSourceInfo *TInfo) {
17643 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17644 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17645
17646 if (!TInfo) {
17647 assert(D.isInvalidType() && "no declarator info for valid type");
17648 TInfo = Context.getTrivialTypeSourceInfo(T);
17649 }
17650
17651 // Scope manipulation handled by caller.
17652 TypedefDecl *NewTD =
17654 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17655
17656 // Bail out immediately if we have an invalid declaration.
17657 if (D.isInvalidType()) {
17658 NewTD->setInvalidDecl();
17659 return NewTD;
17660 }
17661
17663 if (CurContext->isFunctionOrMethod())
17664 Diag(NewTD->getLocation(), diag::err_module_private_local)
17665 << 2 << NewTD
17669 else
17670 NewTD->setModulePrivate();
17671 }
17672
17673 // C++ [dcl.typedef]p8:
17674 // If the typedef declaration defines an unnamed class (or
17675 // enum), the first typedef-name declared by the declaration
17676 // to be that class type (or enum type) is used to denote the
17677 // class type (or enum type) for linkage purposes only.
17678 // We need to check whether the type was declared in the declaration.
17679 switch (D.getDeclSpec().getTypeSpecType()) {
17680 case TST_enum:
17681 case TST_struct:
17682 case TST_interface:
17683 case TST_union:
17684 case TST_class: {
17685 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17686 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17687 break;
17688 }
17689
17690 default:
17691 break;
17692 }
17693
17694 return NewTD;
17695}
17696
17698 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17699 QualType T = TI->getType();
17700
17701 if (T->isDependentType())
17702 return false;
17703
17704 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17705 // integral type; any cv-qualification is ignored.
17706 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17707 // non-atomic version of the type specified by the type specifiers in the
17708 // specifier qualifier list.
17709 // Because of how odd C's rule is, we'll let the user know that operations
17710 // involving the enumeration type will be non-atomic.
17711 if (T->isAtomicType())
17712 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17713
17714 Qualifiers Q = T.getQualifiers();
17715 std::optional<unsigned> QualSelect;
17716 if (Q.hasConst() && Q.hasVolatile())
17717 QualSelect = diag::CVQualList::Both;
17718 else if (Q.hasConst())
17719 QualSelect = diag::CVQualList::Const;
17720 else if (Q.hasVolatile())
17721 QualSelect = diag::CVQualList::Volatile;
17722
17723 if (QualSelect)
17724 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17725
17726 T = T.getAtomicUnqualifiedType();
17727
17728 // This doesn't use 'isIntegralType' despite the error message mentioning
17729 // integral type because isIntegralType would also allow enum types in C.
17730 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17731 if (BT->isInteger())
17732 return false;
17733
17734 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17735 << T << T->isBitIntType();
17736}
17737
17739 QualType EnumUnderlyingTy, bool IsFixed,
17740 const EnumDecl *Prev) {
17741 if (IsScoped != Prev->isScoped()) {
17742 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17743 << Prev->isScoped();
17744 Diag(Prev->getLocation(), diag::note_previous_declaration);
17745 return true;
17746 }
17747
17748 if (IsFixed && Prev->isFixed()) {
17749 if (!EnumUnderlyingTy->isDependentType() &&
17750 !Prev->getIntegerType()->isDependentType() &&
17751 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17752 Prev->getIntegerType())) {
17753 // TODO: Highlight the underlying type of the redeclaration.
17754 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17755 << EnumUnderlyingTy << Prev->getIntegerType();
17756 Diag(Prev->getLocation(), diag::note_previous_declaration)
17757 << Prev->getIntegerTypeRange();
17758 return true;
17759 }
17760 } else if (IsFixed != Prev->isFixed()) {
17761 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17762 << Prev->isFixed();
17763 Diag(Prev->getLocation(), diag::note_previous_declaration);
17764 return true;
17765 }
17766
17767 return false;
17768}
17769
17770/// Get diagnostic %select index for tag kind for
17771/// redeclaration diagnostic message.
17772/// WARNING: Indexes apply to particular diagnostics only!
17773///
17774/// \returns diagnostic %select index.
17776 switch (Tag) {
17778 return 0;
17780 return 1;
17781 case TagTypeKind::Class:
17782 return 2;
17783 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17784 }
17785}
17786
17787/// Determine if tag kind is a class-key compatible with
17788/// class for redeclaration (class, struct, or __interface).
17789///
17790/// \returns true iff the tag kind is compatible.
17792{
17793 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17795}
17796
17798 if (isa<TypedefDecl>(PrevDecl))
17799 return NonTagKind::Typedef;
17800 else if (isa<TypeAliasDecl>(PrevDecl))
17801 return NonTagKind::TypeAlias;
17802 else if (isa<ClassTemplateDecl>(PrevDecl))
17803 return NonTagKind::Template;
17804 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17806 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17808 switch (TTK) {
17811 case TagTypeKind::Class:
17812 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17814 case TagTypeKind::Union:
17815 return NonTagKind::NonUnion;
17816 case TagTypeKind::Enum:
17817 return NonTagKind::NonEnum;
17818 }
17819 llvm_unreachable("invalid TTK");
17820}
17821
17823 TagTypeKind NewTag, bool isDefinition,
17824 SourceLocation NewTagLoc,
17825 const IdentifierInfo *Name) {
17826 // C++ [dcl.type.elab]p3:
17827 // The class-key or enum keyword present in the
17828 // elaborated-type-specifier shall agree in kind with the
17829 // declaration to which the name in the elaborated-type-specifier
17830 // refers. This rule also applies to the form of
17831 // elaborated-type-specifier that declares a class-name or
17832 // friend class since it can be construed as referring to the
17833 // definition of the class. Thus, in any
17834 // elaborated-type-specifier, the enum keyword shall be used to
17835 // refer to an enumeration (7.2), the union class-key shall be
17836 // used to refer to a union (clause 9), and either the class or
17837 // struct class-key shall be used to refer to a class (clause 9)
17838 // declared using the class or struct class-key.
17839 TagTypeKind OldTag = Previous->getTagKind();
17840 if (OldTag != NewTag &&
17842 return false;
17843
17844 // Tags are compatible, but we might still want to warn on mismatched tags.
17845 // Non-class tags can't be mismatched at this point.
17847 return true;
17848
17849 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17850 // by our warning analysis. We don't want to warn about mismatches with (eg)
17851 // declarations in system headers that are designed to be specialized, but if
17852 // a user asks us to warn, we should warn if their code contains mismatched
17853 // declarations.
17854 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17855 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17856 Loc);
17857 };
17858 if (IsIgnoredLoc(NewTagLoc))
17859 return true;
17860
17861 auto IsIgnored = [&](const TagDecl *Tag) {
17862 return IsIgnoredLoc(Tag->getLocation());
17863 };
17864 while (IsIgnored(Previous)) {
17865 Previous = Previous->getPreviousDecl();
17866 if (!Previous)
17867 return true;
17868 OldTag = Previous->getTagKind();
17869 }
17870
17871 bool isTemplate = false;
17872 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17873 isTemplate = Record->getDescribedClassTemplate();
17874
17876 if (OldTag != NewTag) {
17877 // In a template instantiation, do not offer fix-its for tag mismatches
17878 // since they usually mess up the template instead of fixing the problem.
17879 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17881 << getRedeclDiagFromTagKind(OldTag);
17882 // FIXME: Note previous location?
17883 }
17884 return true;
17885 }
17886
17887 if (isDefinition) {
17888 // On definitions, check all previous tags and issue a fix-it for each
17889 // one that doesn't match the current tag.
17890 if (Previous->getDefinition()) {
17891 // Don't suggest fix-its for redefinitions.
17892 return true;
17893 }
17894
17895 bool previousMismatch = false;
17896 for (const TagDecl *I : Previous->redecls()) {
17897 if (I->getTagKind() != NewTag) {
17898 // Ignore previous declarations for which the warning was disabled.
17899 if (IsIgnored(I))
17900 continue;
17901
17902 if (!previousMismatch) {
17903 previousMismatch = true;
17904 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17906 << getRedeclDiagFromTagKind(I->getTagKind());
17907 }
17908 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17910 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17912 }
17913 }
17914 return true;
17915 }
17916
17917 // Identify the prevailing tag kind: this is the kind of the definition (if
17918 // there is a non-ignored definition), or otherwise the kind of the prior
17919 // (non-ignored) declaration.
17920 const TagDecl *PrevDef = Previous->getDefinition();
17921 if (PrevDef && IsIgnored(PrevDef))
17922 PrevDef = nullptr;
17923 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17924 if (Redecl->getTagKind() != NewTag) {
17925 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17927 << getRedeclDiagFromTagKind(OldTag);
17928 Diag(Redecl->getLocation(), diag::note_previous_use);
17929
17930 // If there is a previous definition, suggest a fix-it.
17931 if (PrevDef) {
17932 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17936 }
17937 }
17938
17939 return true;
17940}
17941
17942/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17943/// from an outer enclosing namespace or file scope inside a friend declaration.
17944/// This should provide the commented out code in the following snippet:
17945/// namespace N {
17946/// struct X;
17947/// namespace M {
17948/// struct Y { friend struct /*N::*/ X; };
17949/// }
17950/// }
17952 SourceLocation NameLoc) {
17953 // While the decl is in a namespace, do repeated lookup of that name and see
17954 // if we get the same namespace back. If we do not, continue until
17955 // translation unit scope, at which point we have a fully qualified NNS.
17958 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17959 // This tag should be declared in a namespace, which can only be enclosed by
17960 // other namespaces. Bail if there's an anonymous namespace in the chain.
17961 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17962 if (!Namespace || Namespace->isAnonymousNamespace())
17963 return FixItHint();
17964 IdentifierInfo *II = Namespace->getIdentifier();
17965 Namespaces.push_back(II);
17966 NamedDecl *Lookup = SemaRef.LookupSingleName(
17967 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17968 if (Lookup == Namespace)
17969 break;
17970 }
17971
17972 // Once we have all the namespaces, reverse them to go outermost first, and
17973 // build an NNS.
17974 SmallString<64> Insertion;
17975 llvm::raw_svector_ostream OS(Insertion);
17976 if (DC->isTranslationUnit())
17977 OS << "::";
17978 std::reverse(Namespaces.begin(), Namespaces.end());
17979 for (auto *II : Namespaces)
17980 OS << II->getName() << "::";
17981 return FixItHint::CreateInsertion(NameLoc, Insertion);
17982}
17983
17984/// Determine whether a tag originally declared in context \p OldDC can
17985/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17986/// found a declaration in \p OldDC as a previous decl, perhaps through a
17987/// using-declaration).
17989 DeclContext *NewDC) {
17990 OldDC = OldDC->getRedeclContext();
17991 NewDC = NewDC->getRedeclContext();
17992
17993 if (OldDC->Equals(NewDC))
17994 return true;
17995
17996 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17997 // encloses the other).
17998 if (S.getLangOpts().MSVCCompat &&
17999 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
18000 return true;
18001
18002 return false;
18003}
18004
18006Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
18007 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18008 const ParsedAttributesView &Attrs, AccessSpecifier AS,
18009 SourceLocation ModulePrivateLoc,
18010 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
18011 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
18012 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
18013 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
18014 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
18015 // If this is not a definition, it must have a name.
18016 IdentifierInfo *OrigName = Name;
18017 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
18018 "Nameless record must be a definition!");
18019 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
18020
18021 OwnedDecl = false;
18023 bool ScopedEnum = ScopedEnumKWLoc.isValid();
18024
18025 // FIXME: Check member specializations more carefully.
18026 bool isMemberSpecialization = false;
18027 bool IsInjectedClassName = false;
18028 bool Invalid = false;
18029
18030 // We only need to do this matching if we have template parameters
18031 // or a scope specifier, which also conveniently avoids this work
18032 // for non-C++ cases.
18033 if (TemplateParameterLists.size() > 0 ||
18034 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
18035 TemplateParameterList *TemplateParams =
18037 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
18038 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
18039
18040 // C++23 [dcl.type.elab] p2:
18041 // If an elaborated-type-specifier is the sole constituent of a
18042 // declaration, the declaration is ill-formed unless it is an explicit
18043 // specialization, an explicit instantiation or it has one of the
18044 // following forms: [...]
18045 // C++23 [dcl.enum] p1:
18046 // If the enum-head-name of an opaque-enum-declaration contains a
18047 // nested-name-specifier, the declaration shall be an explicit
18048 // specialization.
18049 //
18050 // FIXME: Class template partial specializations can be forward declared
18051 // per CWG2213, but the resolution failed to allow qualified forward
18052 // declarations. This is almost certainly unintentional, so we allow them.
18053 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18054 !isMemberSpecialization)
18055 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
18057
18058 if (TemplateParams) {
18059 if (Kind == TagTypeKind::Enum) {
18060 Diag(KWLoc, diag::err_enum_template);
18061 return true;
18062 }
18063
18064 if (TemplateParams->size() > 0) {
18065 // This is a declaration or definition of a class template (which may
18066 // be a member of another template).
18067
18068 if (Invalid)
18069 return true;
18070
18071 OwnedDecl = false;
18073 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
18074 AS, ModulePrivateLoc,
18075 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
18076 TemplateParameterLists.data(), isMemberSpecialization, SkipBody);
18077 return Result.get();
18078 } else {
18079 // The "template<>" header is extraneous.
18080 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18081 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18082 isMemberSpecialization = true;
18083 }
18084 }
18085
18086 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18087 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
18088 return true;
18089 }
18090
18091 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18092 // C++23 [dcl.type.elab]p4:
18093 // If an elaborated-type-specifier appears with the friend specifier as
18094 // an entire member-declaration, the member-declaration shall have one
18095 // of the following forms:
18096 // friend class-key nested-name-specifier(opt) identifier ;
18097 // friend class-key simple-template-id ;
18098 // friend class-key nested-name-specifier template(opt)
18099 // simple-template-id ;
18100 //
18101 // Since enum is not a class-key, so declarations like "friend enum E;"
18102 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18103 // invalid, most implementations accept so we issue a pedantic warning.
18104 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
18105 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18106 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18107 Diag(KWLoc, diag::note_enum_friend)
18108 << (ScopedEnum + ScopedEnumUsesClassTag);
18109 }
18110
18111 // Figure out the underlying type if this a enum declaration. We need to do
18112 // this early, because it's needed to detect if this is an incompatible
18113 // redeclaration.
18114 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18115 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18116
18117 if (Kind == TagTypeKind::Enum) {
18118 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18119 Invalid) {
18120 // No underlying type explicitly specified, or we failed to parse the
18121 // type, default to int.
18122 EnumUnderlying = Context.IntTy.getTypePtr();
18123 } else if (UnderlyingType.get()) {
18124 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18125 // integral type; any cv-qualification is ignored.
18126 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18127 // unqualified, non-atomic version of the type specified by the type
18128 // specifiers in the specifier qualifier list.
18129 TypeSourceInfo *TI = nullptr;
18130 GetTypeFromParser(UnderlyingType.get(), &TI);
18131 EnumUnderlying = TI;
18132
18134 // Recover by falling back to int.
18135 EnumUnderlying = Context.IntTy.getTypePtr();
18136
18139 EnumUnderlying = Context.IntTy.getTypePtr();
18140
18141 // If the underlying type is atomic, we need to adjust the type before
18142 // continuing. This only happens in the case we stored a TypeSourceInfo
18143 // into EnumUnderlying because the other cases are error recovery up to
18144 // this point. But because it's not possible to gin up a TypeSourceInfo
18145 // for a non-atomic type from an atomic one, we'll store into the Type
18146 // field instead. FIXME: it would be nice to have an easy way to get a
18147 // derived TypeSourceInfo which strips qualifiers including the weird
18148 // ones like _Atomic where it forms a different type.
18149 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
18150 TI && TI->getType()->isAtomicType())
18151 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18152
18153 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18154 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18155 // of 'int'. However, if this is an unfixed forward declaration, don't set
18156 // the underlying type unless the user enables -fms-compatibility. This
18157 // makes unfixed forward declared enums incomplete and is more conforming.
18158 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18159 EnumUnderlying = Context.IntTy.getTypePtr();
18160 }
18161 }
18162
18163 DeclContext *SearchDC = CurContext;
18164 DeclContext *DC = CurContext;
18165 bool isStdBadAlloc = false;
18166 bool isStdAlignValT = false;
18167
18169 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18171
18172 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18173 /// implemented asks for structural equivalence checking, the returned decl
18174 /// here is passed back to the parser, allowing the tag body to be parsed.
18175 auto createTagFromNewDecl = [&]() -> TagDecl * {
18176 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18177 // If there is an identifier, use the location of the identifier as the
18178 // location of the decl, otherwise use the location of the struct/union
18179 // keyword.
18180 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18181 TagDecl *New = nullptr;
18182
18183 if (Kind == TagTypeKind::Enum) {
18184 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
18185 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
18186 // If this is an undefined enum, bail.
18187 if (TUK != TagUseKind::Definition && !Invalid)
18188 return nullptr;
18189 if (EnumUnderlying) {
18191 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18193 else
18194 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18195 QualType EnumTy = ED->getIntegerType();
18196 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18197 ? Context.getPromotedIntegerType(EnumTy)
18198 : EnumTy);
18199 }
18200 } else { // struct/union
18201 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18202 nullptr);
18203 }
18204
18205 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18206 // Add alignment attributes if necessary; these attributes are checked
18207 // when the ASTContext lays out the structure.
18208 //
18209 // It is important for implementing the correct semantics that this
18210 // happen here (in ActOnTag). The #pragma pack stack is
18211 // maintained as a result of parser callbacks which can occur at
18212 // many points during the parsing of a struct declaration (because
18213 // the #pragma tokens are effectively skipped over during the
18214 // parsing of the struct).
18215 if (TUK == TagUseKind::Definition &&
18216 (!SkipBody || !SkipBody->ShouldSkip)) {
18217 if (LangOpts.HLSL)
18218 RD->addAttr(PackedAttr::CreateImplicit(Context));
18221 }
18222 }
18223 New->setLexicalDeclContext(CurContext);
18224 return New;
18225 };
18226
18227 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18228 if (Name && SS.isNotEmpty()) {
18229 // We have a nested-name tag ('struct foo::bar').
18230
18231 // Check for invalid 'foo::'.
18232 if (SS.isInvalid()) {
18233 Name = nullptr;
18234 goto CreateNewDecl;
18235 }
18236
18237 // If this is a friend or a reference to a class in a dependent
18238 // context, don't try to make a decl for it.
18239 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18240 DC = computeDeclContext(SS, false);
18241 if (!DC) {
18242 IsDependent = true;
18243 return true;
18244 }
18245 } else {
18246 DC = computeDeclContext(SS, true);
18247 if (!DC) {
18248 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
18249 << SS.getRange();
18250 return true;
18251 }
18252 }
18253
18254 if (RequireCompleteDeclContext(SS, DC))
18255 return true;
18256
18257 SearchDC = DC;
18258 // Look-up name inside 'foo::'.
18260
18261 if (Previous.isAmbiguous())
18262 return true;
18263
18264 if (Previous.empty()) {
18265 // Name lookup did not find anything. However, if the
18266 // nested-name-specifier refers to the current instantiation,
18267 // and that current instantiation has any dependent base
18268 // classes, we might find something at instantiation time: treat
18269 // this as a dependent elaborated-type-specifier.
18270 // But this only makes any sense for reference-like lookups.
18271 if (Previous.wasNotFoundInCurrentInstantiation() &&
18272 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18273 IsDependent = true;
18274 return true;
18275 }
18276
18277 // A tag 'foo::bar' must already exist.
18278 Diag(NameLoc, diag::err_not_tag_in_scope)
18279 << Kind << Name << DC << SS.getRange();
18280 Name = nullptr;
18281 Invalid = true;
18282 goto CreateNewDecl;
18283 }
18284 } else if (Name) {
18285 // C++14 [class.mem]p14:
18286 // If T is the name of a class, then each of the following shall have a
18287 // name different from T:
18288 // -- every member of class T that is itself a type
18289 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18290 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
18291 return true;
18292
18293 // If this is a named struct, check to see if there was a previous forward
18294 // declaration or definition.
18295 // FIXME: We're looking into outer scopes here, even when we
18296 // shouldn't be. Doing so can result in ambiguities that we
18297 // shouldn't be diagnosing.
18298 LookupName(Previous, S);
18299
18300 // When declaring or defining a tag, ignore ambiguities introduced
18301 // by types using'ed into this scope.
18302 if (Previous.isAmbiguous() &&
18304 LookupResult::Filter F = Previous.makeFilter();
18305 while (F.hasNext()) {
18306 NamedDecl *ND = F.next();
18307 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18308 SearchDC->getRedeclContext()))
18309 F.erase();
18310 }
18311 F.done();
18312 }
18313
18314 // C++11 [namespace.memdef]p3:
18315 // If the name in a friend declaration is neither qualified nor
18316 // a template-id and the declaration is a function or an
18317 // elaborated-type-specifier, the lookup to determine whether
18318 // the entity has been previously declared shall not consider
18319 // any scopes outside the innermost enclosing namespace.
18320 //
18321 // MSVC doesn't implement the above rule for types, so a friend tag
18322 // declaration may be a redeclaration of a type declared in an enclosing
18323 // scope. They do implement this rule for friend functions.
18324 //
18325 // Does it matter that this should be by scope instead of by
18326 // semantic context?
18327 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18328 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18329 LookupResult::Filter F = Previous.makeFilter();
18330 bool FriendSawTagOutsideEnclosingNamespace = false;
18331 while (F.hasNext()) {
18332 NamedDecl *ND = F.next();
18334 if (DC->isFileContext() &&
18335 !EnclosingNS->Encloses(ND->getDeclContext())) {
18336 if (getLangOpts().MSVCCompat)
18337 FriendSawTagOutsideEnclosingNamespace = true;
18338 else
18339 F.erase();
18340 }
18341 }
18342 F.done();
18343
18344 // Diagnose this MSVC extension in the easy case where lookup would have
18345 // unambiguously found something outside the enclosing namespace.
18346 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18347 NamedDecl *ND = Previous.getFoundDecl();
18348 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18349 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18350 }
18351 }
18352
18353 // Note: there used to be some attempt at recovery here.
18354 if (Previous.isAmbiguous())
18355 return true;
18356
18357 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18358 // FIXME: This makes sure that we ignore the contexts associated
18359 // with C structs, unions, and enums when looking for a matching
18360 // tag declaration or definition. See the similar lookup tweak
18361 // in Sema::LookupName; is there a better way to deal with this?
18363 SearchDC = SearchDC->getParent();
18364 } else if (getLangOpts().CPlusPlus) {
18365 // Inside ObjCContainer want to keep it as a lexical decl context but go
18366 // past it (most often to TranslationUnit) to find the semantic decl
18367 // context.
18368 while (isa<ObjCContainerDecl>(SearchDC))
18369 SearchDC = SearchDC->getParent();
18370 }
18371 } else if (getLangOpts().CPlusPlus) {
18372 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18373 // TagDecl the same way as we skip it for named TagDecl.
18374 while (isa<ObjCContainerDecl>(SearchDC))
18375 SearchDC = SearchDC->getParent();
18376 }
18377
18378 if (Previous.isSingleResult() &&
18379 Previous.getFoundDecl()->isTemplateParameter()) {
18380 // Maybe we will complain about the shadowed template parameter.
18381 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18382 // Just pretend that we didn't see the previous declaration.
18383 Previous.clear();
18384 }
18385
18386 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18387 DC->Equals(getStdNamespace())) {
18388 if (Name->isStr("bad_alloc")) {
18389 // This is a declaration of or a reference to "std::bad_alloc".
18390 isStdBadAlloc = true;
18391
18392 // If std::bad_alloc has been implicitly declared (but made invisible to
18393 // name lookup), fill in this implicit declaration as the previous
18394 // declaration, so that the declarations get chained appropriately.
18395 if (Previous.empty() && StdBadAlloc)
18396 Previous.addDecl(getStdBadAlloc());
18397 } else if (Name->isStr("align_val_t")) {
18398 isStdAlignValT = true;
18399 if (Previous.empty() && StdAlignValT)
18400 Previous.addDecl(getStdAlignValT());
18401 }
18402 }
18403
18404 // If we didn't find a previous declaration, and this is a reference
18405 // (or friend reference), move to the correct scope. In C++, we
18406 // also need to do a redeclaration lookup there, just in case
18407 // there's a shadow friend decl.
18408 if (Name && Previous.empty() &&
18409 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18410 IsTemplateParamOrArg)) {
18411 if (Invalid) goto CreateNewDecl;
18412 assert(SS.isEmpty());
18413
18414 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18415 // C++ [basic.scope.pdecl]p5:
18416 // -- for an elaborated-type-specifier of the form
18417 //
18418 // class-key identifier
18419 //
18420 // if the elaborated-type-specifier is used in the
18421 // decl-specifier-seq or parameter-declaration-clause of a
18422 // function defined in namespace scope, the identifier is
18423 // declared as a class-name in the namespace that contains
18424 // the declaration; otherwise, except as a friend
18425 // declaration, the identifier is declared in the smallest
18426 // non-class, non-function-prototype scope that contains the
18427 // declaration.
18428 //
18429 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18430 // C structs and unions.
18431 //
18432 // It is an error in C++ to declare (rather than define) an enum
18433 // type, including via an elaborated type specifier. We'll
18434 // diagnose that later; for now, declare the enum in the same
18435 // scope as we would have picked for any other tag type.
18436 //
18437 // GNU C also supports this behavior as part of its incomplete
18438 // enum types extension, while GNU C++ does not.
18439 //
18440 // Find the context where we'll be declaring the tag.
18441 // FIXME: We would like to maintain the current DeclContext as the
18442 // lexical context,
18443 SearchDC = getTagInjectionContext(SearchDC);
18444
18445 // Find the scope where we'll be declaring the tag.
18447 } else {
18448 assert(TUK == TagUseKind::Friend);
18449 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18450
18451 // C++ [namespace.memdef]p3:
18452 // If a friend declaration in a non-local class first declares a
18453 // class or function, the friend class or function is a member of
18454 // the innermost enclosing namespace.
18455 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18456 : SearchDC->getEnclosingNamespaceContext();
18457 }
18458
18459 // In C++, we need to do a redeclaration lookup to properly
18460 // diagnose some problems.
18461 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18462 // hidden declaration so that we don't get ambiguity errors when using a
18463 // type declared by an elaborated-type-specifier. In C that is not correct
18464 // and we should instead merge compatible types found by lookup.
18465 if (getLangOpts().CPlusPlus) {
18466 // FIXME: This can perform qualified lookups into function contexts,
18467 // which are meaningless.
18468 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18469 LookupQualifiedName(Previous, SearchDC);
18470 } else {
18471 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18472 LookupName(Previous, S);
18473 }
18474 }
18475
18476 // If we have a known previous declaration to use, then use it.
18477 if (Previous.empty() && SkipBody && SkipBody->Previous)
18478 Previous.addDecl(SkipBody->Previous);
18479
18480 if (!Previous.empty()) {
18481 NamedDecl *PrevDecl = Previous.getFoundDecl();
18482 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18483
18484 // It's okay to have a tag decl in the same scope as a typedef
18485 // which hides a tag decl in the same scope. Finding this
18486 // with a redeclaration lookup can only actually happen in C++.
18487 //
18488 // This is also okay for elaborated-type-specifiers, which is
18489 // technically forbidden by the current standard but which is
18490 // okay according to the likely resolution of an open issue;
18491 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18492 if (getLangOpts().CPlusPlus) {
18493 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18494 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18495 if (Tag->getDeclName() == Name &&
18496 Tag->getDeclContext()->getRedeclContext()
18497 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18498 PrevDecl = Tag;
18499 Previous.clear();
18500 Previous.addDecl(Tag);
18501 Previous.resolveKind();
18502 }
18503 }
18504 }
18505 }
18506
18507 // If this is a redeclaration of a using shadow declaration, it must
18508 // declare a tag in the same context. In MSVC mode, we allow a
18509 // redefinition if either context is within the other.
18510 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18511 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18512 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18513 TUK != TagUseKind::Friend &&
18514 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18515 !(OldTag && isAcceptableTagRedeclContext(
18516 *this, OldTag->getDeclContext(), SearchDC))) {
18517 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18518 Diag(Shadow->getTargetDecl()->getLocation(),
18519 diag::note_using_decl_target);
18520 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18521 << 0;
18522 // Recover by ignoring the old declaration.
18523 Previous.clear();
18524 goto CreateNewDecl;
18525 }
18526 }
18527
18528 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18529 // If this is a use of a previous tag, or if the tag is already declared
18530 // in the same scope (so that the definition/declaration completes or
18531 // rementions the tag), reuse the decl.
18532 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18533 isDeclInScope(DirectPrevDecl, SearchDC, S,
18534 SS.isNotEmpty() || isMemberSpecialization)) {
18535
18536 if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18537 RD && RD->isInjectedClassName()) {
18538 // If lookup found the injected class name, the previous declaration
18539 // is the class being injected into.
18540 Previous.clear();
18541 PrevDecl = PrevTagDecl = cast<CXXRecordDecl>(RD->getDeclContext());
18542 Previous.addDecl(PrevDecl);
18543 Previous.resolveKind();
18544 IsInjectedClassName = true;
18545 }
18546
18547 // Make sure that this wasn't declared as an enum and now used as a
18548 // struct or something similar.
18549 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18550 TUK == TagUseKind::Definition, KWLoc,
18551 Name)) {
18552 bool SafeToContinue =
18553 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18554 Kind != TagTypeKind::Enum);
18555 if (SafeToContinue)
18556 Diag(KWLoc, diag::err_use_with_wrong_tag)
18557 << Name
18559 PrevTagDecl->getKindName());
18560 else
18561 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18562 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18563
18564 if (SafeToContinue)
18565 Kind = PrevTagDecl->getTagKind();
18566 else {
18567 // Recover by making this an anonymous redefinition.
18568 Name = nullptr;
18569 Previous.clear();
18570 Invalid = true;
18571 }
18572 }
18573
18574 if (Kind == TagTypeKind::Enum &&
18575 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18576 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18577 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18578 return PrevTagDecl;
18579
18580 QualType EnumUnderlyingTy;
18581 if (TypeSourceInfo *TI =
18582 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18583 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18584 else if (const Type *T =
18585 dyn_cast_if_present<const Type *>(EnumUnderlying))
18586 EnumUnderlyingTy = QualType(T, 0);
18587
18588 // All conflicts with previous declarations are recovered by
18589 // returning the previous declaration, unless this is a definition,
18590 // in which case we want the caller to bail out.
18591 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18592 ScopedEnum, EnumUnderlyingTy,
18593 IsFixed, PrevEnum))
18594 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18595 }
18596
18597 // C++11 [class.mem]p1:
18598 // A member shall not be declared twice in the member-specification,
18599 // except that a nested class or member class template can be declared
18600 // and then later defined.
18601 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18602 S->isDeclScope(PrevDecl)) {
18603 Diag(NameLoc, diag::ext_member_redeclared);
18604 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18605 }
18606
18607 // C++ [class.local]p3:
18608 // A class nested within a local class is a local class. A member of
18609 // a local class X shall be declared only in the definition of X or,
18610 // if the member is a nested class, in the nearest enclosing block
18611 // scope of X.
18612 if (TUK == TagUseKind::Definition && SS.isValid()) {
18613 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(PrevDecl)) {
18614 while (const auto *ParentClass =
18615 dyn_cast<CXXRecordDecl>(OutermostClass->getParent()))
18616 OutermostClass = ParentClass;
18617
18618 if (OutermostClass->isLocalClass() &&
18619 !S->isDeclScope(OutermostClass)) {
18620 Diag(NameLoc, diag::err_local_nested_class_invalid_scope)
18621 << Name << OutermostClass;
18622 Diag(OutermostClass->getLocation(), diag::note_defined_here)
18623 << OutermostClass;
18624 }
18625 }
18626 }
18627
18628 if (!Invalid) {
18629 // If this is a use, just return the declaration we found, unless
18630 // we have attributes.
18631 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18632 if (!Attrs.empty()) {
18633 // FIXME: Diagnose these attributes. For now, we create a new
18634 // declaration to hold them.
18635 } else if (TUK == TagUseKind::Reference &&
18636 (PrevTagDecl->getFriendObjectKind() ==
18638 PrevDecl->getOwningModule() != getCurrentModule()) &&
18639 SS.isEmpty()) {
18640 // This declaration is a reference to an existing entity, but
18641 // has different visibility from that entity: it either makes
18642 // a friend visible or it makes a type visible in a new module.
18643 // In either case, create a new declaration. We only do this if
18644 // the declaration would have meant the same thing if no prior
18645 // declaration were found, that is, if it was found in the same
18646 // scope where we would have injected a declaration.
18647 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18648 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18649 return PrevTagDecl;
18650 // This is in the injected scope, create a new declaration in
18651 // that scope.
18653 } else {
18654 return PrevTagDecl;
18655 }
18656 }
18657
18658 // Diagnose attempts to redefine a tag.
18659 if (TUK == TagUseKind::Definition) {
18660 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18661 // If the type is currently being defined, complain
18662 // about a nested redefinition.
18663 if (Def->isBeingDefined()) {
18664 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18665 Diag(PrevTagDecl->getLocation(),
18666 diag::note_previous_definition);
18667 Name = nullptr;
18668 Previous.clear();
18669 Invalid = true;
18670 } else {
18671 // If we're defining a specialization and the previous
18672 // definition is from an implicit instantiation, don't emit an
18673 // error here; we'll catch this in the general case below.
18674 bool IsExplicitSpecializationAfterInstantiation = false;
18675 if (isMemberSpecialization) {
18676 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18677 IsExplicitSpecializationAfterInstantiation =
18678 RD->getTemplateSpecializationKind() !=
18680 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18681 IsExplicitSpecializationAfterInstantiation =
18682 ED->getTemplateSpecializationKind() !=
18684 }
18685
18686 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18687 // do not keep more that one definition around (merge them).
18688 // However, ensure the decl passes the structural compatibility
18689 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18690 NamedDecl *Hidden = nullptr;
18691 bool HiddenDefVisible = false;
18692 if (SkipBody &&
18693 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18694 getLangOpts().C23)) {
18695 // There is a definition of this tag, but it is not visible.
18696 // We explicitly make use of C++'s one definition rule here,
18697 // and assume that this definition is identical to the hidden
18698 // one we already have. Make the existing definition visible
18699 // and use it in place of this one.
18700 if (!getLangOpts().CPlusPlus) {
18701 // Postpone making the old definition visible until after we
18702 // complete parsing the new one and do the structural
18703 // comparison.
18704 SkipBody->CheckSameAsPrevious = true;
18705 SkipBody->New = createTagFromNewDecl();
18706 SkipBody->Previous = Def;
18707
18708 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18709 return Def;
18710 }
18711
18712 SkipBody->ShouldSkip = true;
18713 SkipBody->Previous = Def;
18714 if (!HiddenDefVisible && Hidden)
18716 // Carry on and handle it like a normal definition. We'll
18717 // skip starting the definition later.
18718
18719 } else if (!IsExplicitSpecializationAfterInstantiation) {
18720 // A redeclaration in function prototype scope in C isn't
18721 // visible elsewhere, so merely issue a warning.
18722 if (!getLangOpts().CPlusPlus &&
18724 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18725 << Name;
18726 else
18727 Diag(NameLoc, diag::err_redefinition) << Name;
18729 NameLoc.isValid() ? NameLoc : KWLoc);
18730 // If this is a redefinition, recover by making this
18731 // struct be anonymous, which will make any later
18732 // references get the previous definition.
18733 Name = nullptr;
18734 Previous.clear();
18735 Invalid = true;
18736 }
18737 }
18738 }
18739
18740 // Okay, this is definition of a previously declared or referenced
18741 // tag. We're going to create a new Decl for it.
18742 }
18743
18744 // Okay, we're going to make a redeclaration. If this is some kind
18745 // of reference, make sure we build the redeclaration in the same DC
18746 // as the original, and ignore the current access specifier.
18747 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference ||
18748 IsInjectedClassName) {
18749 SearchDC = PrevTagDecl->getDeclContext();
18750 AS = AS_none;
18751 }
18752 }
18753 // If we get here we have (another) forward declaration or we
18754 // have a definition. Just create a new decl.
18755
18756 } else {
18757 // If we get here, this is a definition of a new tag type in a nested
18758 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18759 // new decl/type. We set PrevDecl to NULL so that the entities
18760 // have distinct types.
18761 Previous.clear();
18762 }
18763 // If we get here, we're going to create a new Decl. If PrevDecl
18764 // is non-NULL, it's a definition of the tag declared by
18765 // PrevDecl. If it's NULL, we have a new definition.
18766
18767 // Otherwise, PrevDecl is not a tag, but was found with tag
18768 // lookup. This is only actually possible in C++, where a few
18769 // things like templates still live in the tag namespace.
18770 } else {
18771 // Use a better diagnostic if an elaborated-type-specifier
18772 // found the wrong kind of type on the first
18773 // (non-redeclaration) lookup.
18774 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18775 !Previous.isForRedeclaration()) {
18776 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18777 Diag(NameLoc, diag::err_tag_reference_non_tag)
18778 << PrevDecl << NTK << Kind;
18779 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18780 Invalid = true;
18781
18782 // Otherwise, only diagnose if the declaration is in scope.
18783 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18784 SS.isNotEmpty() || isMemberSpecialization)) {
18785 // do nothing
18786
18787 // Diagnose implicit declarations introduced by elaborated types.
18788 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18789 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18790 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18791 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18792 Invalid = true;
18793
18794 // Otherwise it's a declaration. Call out a particularly common
18795 // case here.
18796 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18797 unsigned Kind = 0;
18798 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18799 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18800 << Name << Kind << TND->getUnderlyingType();
18801 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18802 Invalid = true;
18803
18804 // Otherwise, diagnose.
18805 } else {
18806 // The tag name clashes with something else in the target scope,
18807 // issue an error and recover by making this tag be anonymous.
18808 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18809 notePreviousDefinition(PrevDecl, NameLoc);
18810 Name = nullptr;
18811 Invalid = true;
18812 }
18813
18814 // The existing declaration isn't relevant to us; we're in a
18815 // new scope, so clear out the previous declaration.
18816 Previous.clear();
18817 }
18818 }
18819
18820CreateNewDecl:
18821
18822 TagDecl *PrevDecl = nullptr;
18823 if (Previous.isSingleResult())
18824 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18825
18826 // If there is an identifier, use the location of the identifier as the
18827 // location of the decl, otherwise use the location of the struct/union
18828 // keyword.
18829 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18830
18831 // Otherwise, create a new declaration. If there is a previous
18832 // declaration of the same entity, the two will be linked via
18833 // PrevDecl.
18834 TagDecl *New;
18835
18836 if (Kind == TagTypeKind::Enum) {
18837 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18838 // enum X { A, B, C } D; D should chain to X.
18839 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18840 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18841 ScopedEnumUsesClassTag, IsFixed);
18842
18845 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18846
18847 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18849
18850 // If this is an undefined enum, warn.
18851 if (TUK != TagUseKind::Definition && !Invalid) {
18852 TagDecl *Def;
18853 if (IsFixed && ED->isFixed()) {
18854 // C++0x: 7.2p2: opaque-enum-declaration.
18855 // Conflicts are diagnosed above. Do nothing.
18856 } else if (PrevDecl &&
18857 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18858 Diag(Loc, diag::ext_forward_ref_enum_def)
18859 << New;
18860 Diag(Def->getLocation(), diag::note_previous_definition);
18861 } else {
18862 unsigned DiagID = diag::ext_forward_ref_enum;
18863 if (getLangOpts().MSVCCompat)
18864 DiagID = diag::ext_ms_forward_ref_enum;
18865 else if (getLangOpts().CPlusPlus)
18866 DiagID = diag::err_forward_ref_enum;
18867 Diag(Loc, DiagID);
18868 }
18869 }
18870
18871 if (EnumUnderlying) {
18873 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18875 else
18876 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18877 QualType EnumTy = ED->getIntegerType();
18878 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18879 ? Context.getPromotedIntegerType(EnumTy)
18880 : EnumTy);
18881 assert(ED->isComplete() && "enum with type should be complete");
18882 }
18883 } else {
18884 // struct/union/class
18885
18886 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18887 // struct X { int A; } D; D should chain to X.
18888 if (getLangOpts().CPlusPlus) {
18889 // FIXME: Look for a way to use RecordDecl for simple structs.
18890 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18891 cast_or_null<CXXRecordDecl>(PrevDecl));
18892
18893 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18895 } else
18896 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18897 cast_or_null<RecordDecl>(PrevDecl));
18898 }
18899
18900 // Only C23 and later allow defining new types in 'offsetof()'.
18901 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18903 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18904 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18905
18906 // C++11 [dcl.type]p3:
18907 // A type-specifier-seq shall not define a class or enumeration [...].
18908 if (!Invalid && getLangOpts().CPlusPlus &&
18909 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18910 TUK == TagUseKind::Definition) {
18911 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18912 << Context.getCanonicalTagType(New);
18913 Invalid = true;
18914 }
18915
18917 DC->getDeclKind() == Decl::Enum) {
18918 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18919 << Context.getCanonicalTagType(New);
18920 Invalid = true;
18921 }
18922
18923 // Maybe add qualifier info.
18924 if (SS.isNotEmpty()) {
18925 if (SS.isSet()) {
18926 // If this is either a declaration or a definition, check the
18927 // nested-name-specifier against the current context.
18928 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18929 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18930 /*TemplateId=*/nullptr,
18931 isMemberSpecialization))
18932 Invalid = true;
18933
18934 New->setQualifierInfo(SS.getWithLocInContext(Context));
18935 if (TemplateParameterLists.size() > 0) {
18936 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18937 }
18938 }
18939 else
18940 Invalid = true;
18941 }
18942
18943 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18944 // Add alignment attributes if necessary; these attributes are checked when
18945 // the ASTContext lays out the structure.
18946 //
18947 // It is important for implementing the correct semantics that this
18948 // happen here (in ActOnTag). The #pragma pack stack is
18949 // maintained as a result of parser callbacks which can occur at
18950 // many points during the parsing of a struct declaration (because
18951 // the #pragma tokens are effectively skipped over during the
18952 // parsing of the struct).
18953 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18954 if (LangOpts.HLSL)
18955 RD->addAttr(PackedAttr::CreateImplicit(Context));
18958 }
18959 }
18960
18961 if (ModulePrivateLoc.isValid()) {
18962 if (isMemberSpecialization)
18963 Diag(New->getLocation(), diag::err_module_private_specialization)
18964 << 2
18965 << FixItHint::CreateRemoval(ModulePrivateLoc);
18966 // __module_private__ does not apply to local classes. However, we only
18967 // diagnose this as an error when the declaration specifiers are
18968 // freestanding. Here, we just ignore the __module_private__.
18969 else if (!SearchDC->isFunctionOrMethod())
18970 New->setModulePrivate();
18971 }
18972
18973 // If this is a specialization of a member class (of a class template),
18974 // check the specialization.
18975 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18976 Invalid = true;
18977
18978 // If we're declaring or defining a tag in function prototype scope in C,
18979 // note that this type can only be used within the function and add it to
18980 // the list of decls to inject into the function definition scope. However,
18981 // in C23 and later, while the type is only visible within the function, the
18982 // function can be called with a compatible type defined in the same TU, so
18983 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18984 if ((Name || Kind == TagTypeKind::Enum) &&
18985 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18986 if (getLangOpts().CPlusPlus) {
18987 // C++ [dcl.fct]p6:
18988 // Types shall not be defined in return or parameter types.
18989 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18990 Diag(Loc, diag::err_type_defined_in_param_type)
18991 << Name;
18992 Invalid = true;
18993 }
18994 if (TUK == TagUseKind::Declaration)
18995 Invalid = true;
18996 } else if (!PrevDecl) {
18997 // In C23 mode, if the declaration is complete, we do not want to
18998 // diagnose.
18999 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
19000 Diag(Loc, diag::warn_decl_in_param_list)
19001 << Context.getCanonicalTagType(New);
19002 }
19003 }
19004
19005 if (Invalid)
19006 New->setInvalidDecl();
19007
19008 // Set the lexical context. If the tag has a C++ scope specifier, the
19009 // lexical context will be different from the semantic context.
19010 New->setLexicalDeclContext(CurContext);
19011
19012 // Mark this as a friend decl if applicable.
19013 // In Microsoft mode, a friend declaration also acts as a forward
19014 // declaration so we always pass true to setObjectOfFriendDecl to make
19015 // the tag name visible.
19016 if (TUK == TagUseKind::Friend)
19017 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
19018
19019 // Set the access specifier.
19020 if (!Invalid && SearchDC->isRecord())
19021 SetMemberAccessSpecifier(New, PrevDecl, AS);
19022
19023 if (PrevDecl)
19025
19026 if (TUK == TagUseKind::Definition) {
19027 if (!SkipBody || !SkipBody->ShouldSkip) {
19028 New->startDefinition();
19029 } else {
19030 New->setCompleteDefinition();
19031 New->demoteThisDefinitionToDeclaration();
19032 }
19033 }
19034
19035 ProcessDeclAttributeList(S, New, Attrs);
19037
19038 // If this has an identifier, add it to the scope stack.
19039 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
19040 // We might be replacing an existing declaration in the lookup tables;
19041 // if so, borrow its access specifier.
19042 if (PrevDecl)
19043 New->setAccess(PrevDecl->getAccess());
19044
19045 DeclContext *DC = New->getDeclContext()->getRedeclContext();
19047 if (Name) // can be null along some error paths
19048 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19049 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
19050 } else if (Name) {
19051 S = getNonFieldDeclScope(S);
19052 PushOnScopeChains(New, S, true);
19053 } else {
19054 CurContext->addDecl(New);
19055 }
19056
19057 // If this is the C FILE type, notify the AST context.
19058 if (IdentifierInfo *II = New->getIdentifier())
19059 if (!New->isInvalidDecl() &&
19060 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19061 II->isStr("FILE"))
19062 Context.setFILEDecl(New);
19063
19064 if (PrevDecl)
19065 mergeDeclAttributes(New, PrevDecl);
19066
19067 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
19070 }
19071
19072 // If there's a #pragma GCC visibility in scope, set the visibility of this
19073 // record.
19075
19076 // If this is not a definition, process API notes for it now.
19077 if (TUK != TagUseKind::Definition)
19079
19080 if (isMemberSpecialization && !New->isInvalidDecl())
19082
19083 OwnedDecl = true;
19084 // In C++, don't return an invalid declaration. We can't recover well from
19085 // the cases where we make the type anonymous.
19086 if (Invalid && getLangOpts().CPlusPlus) {
19087 if (New->isBeingDefined())
19088 if (auto RD = dyn_cast<RecordDecl>(New))
19089 RD->completeDefinition();
19090 return true;
19091 } else if (SkipBody && SkipBody->ShouldSkip) {
19092 return SkipBody->Previous;
19093 } else {
19094 return New;
19095 }
19096}
19097
19100 TagDecl *Tag = cast<TagDecl>(TagD);
19101
19102 // Enter the tag context.
19103 PushDeclContext(S, Tag);
19104
19106
19107 // If there's a #pragma GCC visibility in scope, set the visibility of this
19108 // record.
19110}
19111
19113 SkipBodyInfo &SkipBody) {
19114 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
19115 return false;
19116
19117 // Make the previous decl visible.
19119 CleanupMergedEnum(S, SkipBody.New);
19120 return true;
19121}
19122
19124 SourceLocation FinalLoc,
19125 bool IsFinalSpelledSealed,
19126 bool IsAbstract,
19127 SourceLocation LBraceLoc) {
19130
19131 FieldCollector->StartClass();
19132
19133 if (!Record->getIdentifier())
19134 return;
19135
19136 if (IsAbstract)
19137 Record->markAbstract();
19138
19139 if (FinalLoc.isValid()) {
19140 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
19141 IsFinalSpelledSealed
19142 ? FinalAttr::Keyword_sealed
19143 : FinalAttr::Keyword_final));
19144 }
19145
19146 // C++ [class]p2:
19147 // [...] The class-name is also inserted into the scope of the
19148 // class itself; this is known as the injected-class-name. For
19149 // purposes of access checking, the injected-class-name is treated
19150 // as if it were a public member name.
19151 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19152 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
19153 Record->getLocation(), Record->getIdentifier());
19154 InjectedClassName->setImplicit();
19155 InjectedClassName->setAccess(AS_public);
19156 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19157 InjectedClassName->setDescribedClassTemplate(Template);
19158
19159 PushOnScopeChains(InjectedClassName, S);
19160 assert(InjectedClassName->isInjectedClassName() &&
19161 "Broken injected-class-name");
19162}
19163
19165 SourceRange BraceRange) {
19167 TagDecl *Tag = cast<TagDecl>(TagD);
19168 Tag->setBraceRange(BraceRange);
19169
19170 // Make sure we "complete" the definition even it is invalid.
19171 if (Tag->isBeingDefined()) {
19172 assert(Tag->isInvalidDecl() && "We should already have completed it");
19173 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19174 RD->completeDefinition();
19175 }
19176
19177 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
19178 FieldCollector->FinishClass();
19179 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19180 auto *Def = RD->getDefinition();
19181 assert(Def && "The record is expected to have a completed definition");
19182 unsigned NumInitMethods = 0;
19183 for (auto *Method : Def->methods()) {
19184 if (!Method->getIdentifier())
19185 continue;
19186 if (Method->getName() == "__init")
19187 NumInitMethods++;
19188 }
19189 if (NumInitMethods > 1 || !Def->hasInitMethod())
19190 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
19191 }
19192
19193 // If we're defining a dynamic class in a module interface unit, we always
19194 // need to produce the vtable for it, even if the vtable is not used in the
19195 // current TU.
19196 //
19197 // The case where the current class is not dynamic is handled in
19198 // MarkVTableUsed.
19199 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19200 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
19201 }
19202
19203 // Exit this scope of this tag's definition.
19205
19206 if (getCurLexicalContext()->isObjCContainer() &&
19207 Tag->getDeclContext()->isFileContext())
19208 Tag->setTopLevelDeclInObjCContainer();
19209
19210 // Notify the consumer that we've defined a tag.
19211 if (!Tag->isInvalidDecl())
19212 Consumer.HandleTagDeclDefinition(Tag);
19213
19214 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19215 // from XLs and instead matches the XL #pragma pack(1) behavior.
19216 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19217 AlignPackStack.hasValue()) {
19218 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19219 // Only diagnose #pragma align(packed).
19220 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19221 return;
19222 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
19223 if (!RD)
19224 return;
19225 // Only warn if there is at least 1 bitfield member.
19226 if (llvm::any_of(RD->fields(),
19227 [](const FieldDecl *FD) { return FD->isBitField(); }))
19228 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
19229 }
19230}
19231
19234 TagDecl *Tag = cast<TagDecl>(TagD);
19235 Tag->setInvalidDecl();
19236
19237 // Make sure we "complete" the definition even it is invalid.
19238 if (Tag->isBeingDefined()) {
19239 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19240 RD->completeDefinition();
19241 }
19242
19243 // We're undoing ActOnTagStartDefinition here, not
19244 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19245 // the FieldCollector.
19246
19248}
19249
19250// Note that FieldName may be null for anonymous bitfields.
19252 const IdentifierInfo *FieldName,
19253 QualType FieldTy, bool IsMsStruct,
19254 Expr *BitWidth) {
19255 assert(BitWidth);
19256 if (BitWidth->containsErrors())
19257 return ExprError();
19258
19259 // C99 6.7.2.1p4 - verify the field type.
19260 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19261 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19262 // Handle incomplete and sizeless types with a specific error.
19263 if (RequireCompleteSizedType(FieldLoc, FieldTy,
19264 diag::err_field_incomplete_or_sizeless))
19265 return ExprError();
19266 if (FieldName)
19267 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
19268 << FieldName << FieldTy << BitWidth->getSourceRange();
19269 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
19270 << FieldTy << BitWidth->getSourceRange();
19272 return ExprError();
19273
19274 // If the bit-width is type- or value-dependent, don't try to check
19275 // it now.
19276 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19277 return BitWidth;
19278
19279 llvm::APSInt Value;
19280 ExprResult ICE =
19282 if (ICE.isInvalid())
19283 return ICE;
19284 BitWidth = ICE.get();
19285
19286 // Zero-width bitfield is ok for anonymous field.
19287 if (Value == 0 && FieldName)
19288 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
19289 << FieldName << BitWidth->getSourceRange();
19290
19291 if (Value.isSigned() && Value.isNegative()) {
19292 if (FieldName)
19293 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
19294 << FieldName << toString(Value, 10);
19295 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
19296 << toString(Value, 10);
19297 }
19298
19299 // The size of the bit-field must not exceed our maximum permitted object
19300 // size.
19301 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19302 return Diag(FieldLoc, diag::err_bitfield_too_wide)
19303 << !FieldName << FieldName << toString(Value, 10);
19304 }
19305
19306 if (!FieldTy->isDependentType()) {
19307 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
19308 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
19309 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
19310
19311 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19312 // ABI.
19313 bool CStdConstraintViolation =
19314 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19315 bool MSBitfieldViolation = Value.ugt(TypeStorageSize) && IsMsStruct;
19316 if (CStdConstraintViolation || MSBitfieldViolation) {
19317 unsigned DiagWidth =
19318 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19319 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
19320 << (bool)FieldName << FieldName << toString(Value, 10)
19321 << !CStdConstraintViolation << DiagWidth;
19322 }
19323
19324 // Warn on types where the user might conceivably expect to get all
19325 // specified bits as value bits: that's all integral types other than
19326 // 'bool'.
19327 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19328 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
19329 << FieldName << Value << (unsigned)TypeWidth;
19330 }
19331 }
19332
19333 if (isa<ConstantExpr>(BitWidth))
19334 return BitWidth;
19335 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
19336}
19337
19339 Declarator &D, Expr *BitfieldWidth) {
19340 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
19341 D, BitfieldWidth,
19342 /*InitStyle=*/ICIS_NoInit, AS_public);
19343 return Res;
19344}
19345
19347 SourceLocation DeclStart,
19348 Declarator &D, Expr *BitWidth,
19349 InClassInitStyle InitStyle,
19350 AccessSpecifier AS) {
19351 if (D.isDecompositionDeclarator()) {
19353 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19354 << Decomp.getSourceRange();
19355 return nullptr;
19356 }
19357
19358 const IdentifierInfo *II = D.getIdentifier();
19359 SourceLocation Loc = DeclStart;
19360 if (II) Loc = D.getIdentifierLoc();
19361
19363 QualType T = TInfo->getType();
19364 if (getLangOpts().CPlusPlus) {
19366
19369 D.setInvalidType();
19370 T = Context.IntTy;
19371 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19372 }
19373 }
19374
19376
19378 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19379 << getLangOpts().CPlusPlus17;
19382 diag::err_invalid_thread)
19384
19385 // Check to see if this name was declared as a member previously
19386 NamedDecl *PrevDecl = nullptr;
19387 LookupResult Previous(*this, II, Loc, LookupMemberName,
19389 LookupName(Previous, S);
19390 switch (Previous.getResultKind()) {
19393 PrevDecl = Previous.getAsSingle<NamedDecl>();
19394 break;
19395
19397 PrevDecl = Previous.getRepresentativeDecl();
19398 break;
19399
19403 break;
19404 }
19405 Previous.suppressDiagnostics();
19406
19407 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19408 // Maybe we will complain about the shadowed template parameter.
19410 // Just pretend that we didn't see the previous declaration.
19411 PrevDecl = nullptr;
19412 }
19413
19414 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19415 PrevDecl = nullptr;
19416
19417 bool Mutable
19418 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19419 SourceLocation TSSL = D.getBeginLoc();
19420 FieldDecl *NewFD
19421 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19422 TSSL, AS, PrevDecl, &D);
19423
19424 if (NewFD->isInvalidDecl())
19425 Record->setInvalidDecl();
19426
19428 NewFD->setModulePrivate();
19429
19430 if (NewFD->isInvalidDecl() && PrevDecl) {
19431 // Don't introduce NewFD into scope; there's already something
19432 // with the same name in the same scope.
19433 } else if (II) {
19434 PushOnScopeChains(NewFD, S);
19435 } else
19436 Record->addDecl(NewFD);
19437
19438 return NewFD;
19439}
19440
19442 TypeSourceInfo *TInfo,
19444 bool Mutable, Expr *BitWidth,
19445 InClassInitStyle InitStyle,
19446 SourceLocation TSSL,
19447 AccessSpecifier AS, NamedDecl *PrevDecl,
19448 Declarator *D) {
19449 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19450 bool InvalidDecl = false;
19451 if (D) InvalidDecl = D->isInvalidType();
19452
19453 // If we receive a broken type, recover by assuming 'int' and
19454 // marking this declaration as invalid.
19455 if (T.isNull() || T->containsErrors()) {
19456 InvalidDecl = true;
19457 T = Context.IntTy;
19458 }
19459
19460 QualType EltTy = Context.getBaseElementType(T);
19461 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19462 bool isIncomplete =
19463 LangOpts.HLSL // HLSL allows sizeless builtin types
19464 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19465 : RequireCompleteSizedType(Loc, EltTy,
19466 diag::err_field_incomplete_or_sizeless);
19467 if (isIncomplete) {
19468 // Fields of incomplete type force their record to be invalid.
19469 Record->setInvalidDecl();
19470 InvalidDecl = true;
19471 } else {
19472 NamedDecl *Def;
19473 EltTy->isIncompleteType(&Def);
19474 if (Def && Def->isInvalidDecl()) {
19475 Record->setInvalidDecl();
19476 InvalidDecl = true;
19477 }
19478 }
19479 }
19480
19481 // TR 18037 does not allow fields to be declared with address space
19482 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19483 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19484 Diag(Loc, diag::err_field_with_address_space);
19485 Record->setInvalidDecl();
19486 InvalidDecl = true;
19487 }
19488
19489 if (LangOpts.OpenCL) {
19490 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19491 // used as structure or union field: image, sampler, event or block types.
19492 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19493 T->isBlockPointerType()) {
19494 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19495 Record->setInvalidDecl();
19496 InvalidDecl = true;
19497 }
19498 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19499 // is enabled.
19500 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19501 "__cl_clang_bitfields", LangOpts)) {
19502 Diag(Loc, diag::err_opencl_bitfields);
19503 InvalidDecl = true;
19504 }
19505 }
19506
19507 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19508 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19509 T.hasQualifiers()) {
19510 InvalidDecl = true;
19511 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19512 }
19513
19514 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19515 // than a variably modified type.
19516 if (!InvalidDecl && T->isVariablyModifiedType()) {
19518 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19519 InvalidDecl = true;
19520 }
19521
19522 // Fields can not have abstract class types
19523 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19524 diag::err_abstract_type_in_decl,
19526 InvalidDecl = true;
19527
19528 if (InvalidDecl)
19529 BitWidth = nullptr;
19530 // If this is declared as a bit-field, check the bit-field.
19531 if (BitWidth) {
19532 BitWidth =
19533 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19534 if (!BitWidth) {
19535 InvalidDecl = true;
19536 BitWidth = nullptr;
19537 }
19538 }
19539
19540 // Check that 'mutable' is consistent with the type of the declaration.
19541 if (!InvalidDecl && Mutable) {
19542 unsigned DiagID = 0;
19543 if (T->isReferenceType())
19544 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19545 : diag::err_mutable_reference;
19546 else if (T.isConstQualified())
19547 DiagID = diag::err_mutable_const;
19548
19549 if (DiagID) {
19550 SourceLocation ErrLoc = Loc;
19551 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19552 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19553 Diag(ErrLoc, DiagID);
19554 if (DiagID != diag::ext_mutable_reference) {
19555 Mutable = false;
19556 InvalidDecl = true;
19557 }
19558 }
19559 }
19560
19561 // C++11 [class.union]p8 (DR1460):
19562 // At most one variant member of a union may have a
19563 // brace-or-equal-initializer.
19564 if (InitStyle != ICIS_NoInit)
19566
19567 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19568 BitWidth, Mutable, InitStyle);
19569 if (InvalidDecl)
19570 NewFD->setInvalidDecl();
19571
19572 if (!InvalidDecl)
19574
19575 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19576 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19577 Diag(Loc, diag::err_duplicate_member) << II;
19578 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19579 NewFD->setInvalidDecl();
19580 }
19581
19582 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19583 if (Record->isUnion()) {
19584 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19585 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19586
19587 // C++ [class.union]p1: An object of a class with a non-trivial
19588 // constructor, a non-trivial copy constructor, a non-trivial
19589 // destructor, or a non-trivial copy assignment operator
19590 // cannot be a member of a union, nor can an array of such
19591 // objects.
19592 if (CheckNontrivialField(NewFD))
19593 NewFD->setInvalidDecl();
19594 }
19595
19596 // C++ [class.union]p1: If a union contains a member of reference type,
19597 // the program is ill-formed, except when compiling with MSVC extensions
19598 // enabled.
19599 if (EltTy->isReferenceType()) {
19600 const bool HaveMSExt =
19601 getLangOpts().MicrosoftExt &&
19603
19604 Diag(NewFD->getLocation(),
19605 HaveMSExt ? diag::ext_union_member_of_reference_type
19606 : diag::err_union_member_of_reference_type)
19607 << NewFD->getDeclName() << EltTy;
19608 if (!HaveMSExt)
19609 NewFD->setInvalidDecl();
19610 }
19611 }
19612 }
19613
19614 // FIXME: We need to pass in the attributes given an AST
19615 // representation, not a parser representation.
19616 if (D) {
19617 // FIXME: The current scope is almost... but not entirely... correct here.
19618 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19619
19620 if (NewFD->hasAttrs())
19622 }
19623
19624 // In auto-retain/release, infer strong retension for fields of
19625 // retainable type.
19626 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19627 NewFD->setInvalidDecl();
19628
19629 if (T.isObjCGCWeak())
19630 Diag(Loc, diag::warn_attribute_weak_on_field);
19631
19632 // PPC MMA non-pointer types are not allowed as field types.
19633 if (Context.getTargetInfo().getTriple().isPPC64() &&
19634 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19635 NewFD->setInvalidDecl();
19636
19637 NewFD->setAccess(AS);
19638 return NewFD;
19639}
19640
19642 assert(FD);
19643 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19644
19645 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19646 return false;
19647
19648 QualType EltTy = Context.getBaseElementType(FD->getType());
19649 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19650 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19651 // We check for copy constructors before constructors
19652 // because otherwise we'll never get complaints about
19653 // copy constructors.
19654
19656 // We're required to check for any non-trivial constructors. Since the
19657 // implicit default constructor is suppressed if there are any
19658 // user-declared constructors, we just need to check that there is a
19659 // trivial default constructor and a trivial copy constructor. (We don't
19660 // worry about move constructors here, since this is a C++98 check.)
19661 if (RDecl->hasNonTrivialCopyConstructor())
19663 else if (!RDecl->hasTrivialDefaultConstructor())
19665 else if (RDecl->hasNonTrivialCopyAssignment())
19667 else if (RDecl->hasNonTrivialDestructor())
19669
19670 if (member != CXXSpecialMemberKind::Invalid) {
19671 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19672 RDecl->hasObjectMember()) {
19673 // Objective-C++ ARC: it is an error to have a non-trivial field of
19674 // a union. However, system headers in Objective-C programs
19675 // occasionally have Objective-C lifetime objects within unions,
19676 // and rather than cause the program to fail, we make those
19677 // members unavailable.
19678 SourceLocation Loc = FD->getLocation();
19679 if (getSourceManager().isInSystemHeader(Loc)) {
19680 if (!FD->hasAttr<UnavailableAttr>())
19681 FD->addAttr(UnavailableAttr::CreateImplicit(
19682 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19683 return false;
19684 }
19685 }
19686
19687 Diag(FD->getLocation(),
19689 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19690 : diag::err_illegal_union_or_anon_struct_member)
19691 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19692 DiagnoseNontrivial(RDecl, member);
19693 return !getLangOpts().CPlusPlus11;
19694 }
19695 }
19696
19697 return false;
19698}
19699
19701 SmallVectorImpl<Decl *> &AllIvarDecls) {
19702 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19703 return;
19704
19705 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19706 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19707
19708 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19709 return;
19710 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19711 if (!ID) {
19712 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19713 if (!CD->IsClassExtension())
19714 return;
19715 }
19716 // No need to add this to end of @implementation.
19717 else
19718 return;
19719 }
19720 // All conditions are met. Add a new bitfield to the tail end of ivars.
19721 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19722 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19723 Expr *BitWidth =
19724 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19725
19726 Ivar = ObjCIvarDecl::Create(
19727 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19728 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19729 ObjCIvarDecl::Private, BitWidth, true);
19730 AllIvarDecls.push_back(Ivar);
19731}
19732
19733/// [class.dtor]p4:
19734/// At the end of the definition of a class, overload resolution is
19735/// performed among the prospective destructors declared in that class with
19736/// an empty argument list to select the destructor for the class, also
19737/// known as the selected destructor.
19738///
19739/// We do the overload resolution here, then mark the selected constructor in the AST.
19740/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19742 if (!Record->hasUserDeclaredDestructor()) {
19743 return;
19744 }
19745
19746 SourceLocation Loc = Record->getLocation();
19748
19749 for (auto *Decl : Record->decls()) {
19750 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19751 if (DD->isInvalidDecl())
19752 continue;
19753 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19754 OCS);
19755 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19756 }
19757 }
19758
19759 if (OCS.empty()) {
19760 return;
19761 }
19763 unsigned Msg = 0;
19764 OverloadCandidateDisplayKind DisplayKind;
19765
19766 switch (OCS.BestViableFunction(S, Loc, Best)) {
19767 case OR_Success:
19768 case OR_Deleted:
19769 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19770 break;
19771
19772 case OR_Ambiguous:
19773 Msg = diag::err_ambiguous_destructor;
19774 DisplayKind = OCD_AmbiguousCandidates;
19775 break;
19776
19778 Msg = diag::err_no_viable_destructor;
19779 DisplayKind = OCD_AllCandidates;
19780 break;
19781 }
19782
19783 if (Msg) {
19784 // OpenCL have got their own thing going with destructors. It's slightly broken,
19785 // but we allow it.
19786 if (!S.LangOpts.OpenCL) {
19787 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19788 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19789 Record->setInvalidDecl();
19790 }
19791 // It's a bit hacky: At this point we've raised an error but we want the
19792 // rest of the compiler to continue somehow working. However almost
19793 // everything we'll try to do with the class will depend on there being a
19794 // destructor. So let's pretend the first one is selected and hope for the
19795 // best.
19796 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19797 }
19798}
19799
19800/// [class.mem.special]p5
19801/// Two special member functions are of the same kind if:
19802/// - they are both default constructors,
19803/// - they are both copy or move constructors with the same first parameter
19804/// type, or
19805/// - they are both copy or move assignment operators with the same first
19806/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19808 CXXMethodDecl *M1,
19809 CXXMethodDecl *M2,
19811 // We don't want to compare templates to non-templates: See
19812 // https://github.com/llvm/llvm-project/issues/59206
19814 return bool(M1->getDescribedFunctionTemplate()) ==
19816 // FIXME: better resolve CWG
19817 // https://cplusplus.github.io/CWG/issues/2787.html
19818 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19819 M2->getNonObjectParameter(0)->getType()))
19820 return false;
19821 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
19823 return false;
19824
19825 return true;
19826}
19827
19828/// [class.mem.special]p6:
19829/// An eligible special member function is a special member function for which:
19830/// - the function is not deleted,
19831/// - the associated constraints, if any, are satisfied, and
19832/// - no special member function of the same kind whose associated constraints
19833/// [CWG2595], if any, are satisfied is more constrained.
19837 SmallVector<bool, 4> SatisfactionStatus;
19838
19839 for (CXXMethodDecl *Method : Methods) {
19840 if (!Method->getTrailingRequiresClause())
19841 SatisfactionStatus.push_back(true);
19842 else {
19843 ConstraintSatisfaction Satisfaction;
19844 if (S.CheckFunctionConstraints(Method, Satisfaction))
19845 SatisfactionStatus.push_back(false);
19846 else
19847 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19848 }
19849 }
19850
19851 for (size_t i = 0; i < Methods.size(); i++) {
19852 if (!SatisfactionStatus[i])
19853 continue;
19854 CXXMethodDecl *Method = Methods[i];
19855 CXXMethodDecl *OrigMethod = Method;
19856 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19857 OrigMethod = cast<CXXMethodDecl>(MF);
19858
19860 bool AnotherMethodIsMoreConstrained = false;
19861 for (size_t j = 0; j < Methods.size(); j++) {
19862 if (i == j || !SatisfactionStatus[j])
19863 continue;
19864 CXXMethodDecl *OtherMethod = Methods[j];
19865 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19866 OtherMethod = cast<CXXMethodDecl>(MF);
19867
19868 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19869 CSM))
19870 continue;
19871
19873 if (!Other)
19874 continue;
19875 if (!Orig) {
19876 AnotherMethodIsMoreConstrained = true;
19877 break;
19878 }
19879 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19880 AnotherMethodIsMoreConstrained)) {
19881 // There was an error with the constraints comparison. Exit the loop
19882 // and don't consider this function eligible.
19883 AnotherMethodIsMoreConstrained = true;
19884 }
19885 if (AnotherMethodIsMoreConstrained)
19886 break;
19887 }
19888 // FIXME: Do not consider deleted methods as eligible after implementing
19889 // DR1734 and DR1496.
19890 if (!AnotherMethodIsMoreConstrained) {
19891 Method->setIneligibleOrNotSelected(false);
19892 Record->addedEligibleSpecialMemberFunction(Method,
19893 1 << llvm::to_underlying(CSM));
19894 }
19895 }
19896}
19897
19900 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19901 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19902 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19903 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19904 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19905
19906 for (auto *Decl : Record->decls()) {
19907 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19908 if (!MD) {
19909 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19910 if (FTD)
19911 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19912 }
19913 if (!MD)
19914 continue;
19915 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19916 if (CD->isInvalidDecl())
19917 continue;
19918 if (CD->isDefaultConstructor())
19919 DefaultConstructors.push_back(MD);
19920 else if (CD->isCopyConstructor())
19921 CopyConstructors.push_back(MD);
19922 else if (CD->isMoveConstructor())
19923 MoveConstructors.push_back(MD);
19924 } else if (MD->isCopyAssignmentOperator()) {
19925 CopyAssignmentOperators.push_back(MD);
19926 } else if (MD->isMoveAssignmentOperator()) {
19927 MoveAssignmentOperators.push_back(MD);
19928 }
19929 }
19930
19931 SetEligibleMethods(S, Record, DefaultConstructors,
19933 SetEligibleMethods(S, Record, CopyConstructors,
19935 SetEligibleMethods(S, Record, MoveConstructors,
19937 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19939 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19941}
19942
19943bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19944 // Check to see if a FieldDecl is a pointer to a function.
19945 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19946 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19947 if (!FD) {
19948 // Check whether this is a forward declaration that was inserted by
19949 // Clang. This happens when a non-forward declared / defined type is
19950 // used, e.g.:
19951 //
19952 // struct foo {
19953 // struct bar *(*f)();
19954 // struct bar *(*g)();
19955 // };
19956 //
19957 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19958 // incomplete definition.
19959 if (const auto *TD = dyn_cast<TagDecl>(D))
19960 return !TD->isCompleteDefinition();
19961 return false;
19962 }
19963 QualType FieldType = FD->getType().getDesugaredType(Context);
19964 if (isa<PointerType>(FieldType)) {
19965 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19966 return PointeeType.getDesugaredType(Context)->isFunctionType();
19967 }
19968 // If a member is a struct entirely of function pointers, that counts too.
19969 if (const auto *Record = FieldType->getAsRecordDecl();
19970 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19971 return true;
19972 return false;
19973 };
19974
19975 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19976}
19977
19978void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19979 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19980 SourceLocation RBrac,
19981 const ParsedAttributesView &Attrs) {
19982 assert(EnclosingDecl && "missing record or interface decl");
19983
19984 // If this is an Objective-C @implementation or category and we have
19985 // new fields here we should reset the layout of the interface since
19986 // it will now change.
19987 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19988 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19989 switch (DC->getKind()) {
19990 default: break;
19991 case Decl::ObjCCategory:
19992 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19993 break;
19994 case Decl::ObjCImplementation:
19995 Context.
19996 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19997 break;
19998 }
19999 }
20000
20001 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
20002 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
20003
20004 // Start counting up the number of named members; make sure to include
20005 // members of anonymous structs and unions in the total.
20006 unsigned NumNamedMembers = 0;
20007 if (Record) {
20008 for (const auto *I : Record->decls()) {
20009 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
20010 if (IFD->getDeclName())
20011 ++NumNamedMembers;
20012 }
20013 }
20014
20015 // Verify that all the fields are okay.
20017 const FieldDecl *PreviousField = nullptr;
20018 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
20019 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
20020 FieldDecl *FD = cast<FieldDecl>(*i);
20021
20022 // Get the type for the field.
20023 const Type *FDTy = FD->getType().getTypePtr();
20024
20025 if (!FD->isAnonymousStructOrUnion()) {
20026 // Remember all fields written by the user.
20027 RecFields.push_back(FD);
20028 }
20029
20030 // If the field is already invalid for some reason, don't emit more
20031 // diagnostics about it.
20032 if (FD->isInvalidDecl()) {
20033 EnclosingDecl->setInvalidDecl();
20034 continue;
20035 }
20036
20037 // C99 6.7.2.1p2:
20038 // A structure or union shall not contain a member with
20039 // incomplete or function type (hence, a structure shall not
20040 // contain an instance of itself, but may contain a pointer to
20041 // an instance of itself), except that the last member of a
20042 // structure with more than one named member may have incomplete
20043 // array type; such a structure (and any union containing,
20044 // possibly recursively, a member that is such a structure)
20045 // shall not be a member of a structure or an element of an
20046 // array.
20047 bool IsLastField = (i + 1 == Fields.end());
20048 if (FDTy->isFunctionType()) {
20049 // Field declared as a function.
20050 Diag(FD->getLocation(), diag::err_field_declared_as_function)
20051 << FD->getDeclName();
20052 FD->setInvalidDecl();
20053 EnclosingDecl->setInvalidDecl();
20054 continue;
20055 } else if (FDTy->isIncompleteArrayType() &&
20056 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
20057 if (Record) {
20058 // Flexible array member.
20059 // Microsoft and g++ is more permissive regarding flexible array.
20060 // It will accept flexible array in union and also
20061 // as the sole element of a struct/class.
20062 unsigned DiagID = 0;
20063 if (!Record->isUnion() && !IsLastField) {
20064 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
20065 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20066 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
20067 FD->setInvalidDecl();
20068 EnclosingDecl->setInvalidDecl();
20069 continue;
20070 } else if (Record->isUnion())
20071 DiagID = getLangOpts().MicrosoftExt
20072 ? diag::ext_flexible_array_union_ms
20073 : diag::ext_flexible_array_union_gnu;
20074 else if (NumNamedMembers < 1)
20075 DiagID = getLangOpts().MicrosoftExt
20076 ? diag::ext_flexible_array_empty_aggregate_ms
20077 : diag::ext_flexible_array_empty_aggregate_gnu;
20078
20079 if (DiagID)
20080 Diag(FD->getLocation(), DiagID)
20081 << FD->getDeclName() << Record->getTagKind();
20082 // While the layout of types that contain virtual bases is not specified
20083 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20084 // virtual bases after the derived members. This would make a flexible
20085 // array member declared at the end of an object not adjacent to the end
20086 // of the type.
20087 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20088 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
20089 << FD->getDeclName() << Record->getTagKind();
20090 if (!getLangOpts().C99)
20091 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
20092 << FD->getDeclName() << Record->getTagKind();
20093
20094 // If the element type has a non-trivial destructor, we would not
20095 // implicitly destroy the elements, so disallow it for now.
20096 //
20097 // FIXME: GCC allows this. We should probably either implicitly delete
20098 // the destructor of the containing class, or just allow this.
20099 QualType BaseElem = Context.getBaseElementType(FD->getType());
20100 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20101 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
20102 << FD->getDeclName() << FD->getType();
20103 FD->setInvalidDecl();
20104 EnclosingDecl->setInvalidDecl();
20105 continue;
20106 }
20107 // Okay, we have a legal flexible array member at the end of the struct.
20108 Record->setHasFlexibleArrayMember(true);
20109 } else {
20110 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20111 // unless they are followed by another ivar. That check is done
20112 // elsewhere, after synthesized ivars are known.
20113 }
20114 } else if (!FDTy->isDependentType() &&
20115 (LangOpts.HLSL // HLSL allows sizeless builtin types
20117 diag::err_incomplete_type)
20119 FD->getLocation(), FD->getType(),
20120 diag::err_field_incomplete_or_sizeless))) {
20121 // Incomplete type
20122 FD->setInvalidDecl();
20123 EnclosingDecl->setInvalidDecl();
20124 continue;
20125 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20126 if (Record && RD->hasFlexibleArrayMember()) {
20127 // A type which contains a flexible array member is considered to be a
20128 // flexible array member.
20129 Record->setHasFlexibleArrayMember(true);
20130 if (!Record->isUnion()) {
20131 // If this is a struct/class and this is not the last element, reject
20132 // it. Note that GCC supports variable sized arrays in the middle of
20133 // structures.
20134 if (!IsLastField)
20135 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
20136 << FD->getDeclName() << FD->getType();
20137 else {
20138 // We support flexible arrays at the end of structs in
20139 // other structs as an extension.
20140 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
20141 << FD->getDeclName();
20142 }
20143 }
20144 }
20145 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
20147 diag::err_abstract_type_in_decl,
20149 // Ivars can not have abstract class types
20150 FD->setInvalidDecl();
20151 }
20152 if (Record && RD->hasObjectMember())
20153 Record->setHasObjectMember(true);
20154 if (Record && RD->hasVolatileMember())
20155 Record->setHasVolatileMember(true);
20156 } else if (FDTy->isObjCObjectType()) {
20157 /// A field cannot be an Objective-c object
20158 Diag(FD->getLocation(), diag::err_statically_allocated_object)
20160 QualType T = Context.getObjCObjectPointerType(FD->getType());
20161 FD->setType(T);
20162 } else if (Record && Record->isUnion() &&
20164 getSourceManager().isInSystemHeader(FD->getLocation()) &&
20165 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20167 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
20168 // For backward compatibility, fields of C unions declared in system
20169 // headers that have non-trivial ObjC ownership qualifications are marked
20170 // as unavailable unless the qualifier is explicit and __strong. This can
20171 // break ABI compatibility between programs compiled with ARC and MRR, but
20172 // is a better option than rejecting programs using those unions under
20173 // ARC.
20174 FD->addAttr(UnavailableAttr::CreateImplicit(
20175 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
20176 FD->getLocation()));
20177 } else if (getLangOpts().ObjC &&
20178 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20179 !Record->hasObjectMember()) {
20180 if (FD->getType()->isObjCObjectPointerType() ||
20181 FD->getType().isObjCGCStrong())
20182 Record->setHasObjectMember(true);
20183 else if (Context.getAsArrayType(FD->getType())) {
20184 QualType BaseType = Context.getBaseElementType(FD->getType());
20185 if (const auto *RD = BaseType->getAsRecordDecl();
20186 RD && RD->hasObjectMember())
20187 Record->setHasObjectMember(true);
20188 else if (BaseType->isObjCObjectPointerType() ||
20189 BaseType.isObjCGCStrong())
20190 Record->setHasObjectMember(true);
20191 }
20192 }
20193
20194 if (Record && !getLangOpts().CPlusPlus &&
20195 !shouldIgnoreForRecordTriviality(FD)) {
20196 QualType FT = FD->getType();
20198 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20200 Record->isUnion())
20201 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20202 }
20205 Record->setNonTrivialToPrimitiveCopy(true);
20206 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20207 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20208 }
20209 if (FD->hasAttr<ExplicitInitAttr>())
20210 Record->setHasUninitializedExplicitInitFields(true);
20211 if (FT.isDestructedType()) {
20212 Record->setNonTrivialToPrimitiveDestroy(true);
20213 Record->setParamDestroyedInCallee(true);
20214 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20215 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20216 }
20217
20218 if (const auto *RD = FT->getAsRecordDecl()) {
20219 if (RD->getArgPassingRestrictions() ==
20221 Record->setArgPassingRestrictions(
20223 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20224 Record->setArgPassingRestrictions(
20226 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20227 Q && Q.isAddressDiscriminated()) {
20228 Record->setArgPassingRestrictions(
20230 Record->setNonTrivialToPrimitiveCopy(true);
20231 }
20232 }
20233
20234 if (Record && FD->getType().isVolatileQualified())
20235 Record->setHasVolatileMember(true);
20236 bool ReportMSBitfieldStoragePacking =
20237 Record && PreviousField &&
20238 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
20239 Record->getLocation());
20240 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20241 return FD->isBitField() && !FD->getType()->isDependentType();
20242 };
20243
20244 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20245 IsNonDependentBitField(PreviousField)) {
20246 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
20247 CharUnits PreviousFieldStorageSize =
20248 Context.getTypeSizeInChars(PreviousField->getType());
20249 if (FDStorageSize != PreviousFieldStorageSize) {
20250 Diag(FD->getLocation(),
20251 diag::warn_ms_bitfield_mismatched_storage_packing)
20252 << FD << FD->getType() << FDStorageSize.getQuantity()
20253 << PreviousFieldStorageSize.getQuantity();
20254 Diag(PreviousField->getLocation(),
20255 diag::note_ms_bitfield_mismatched_storage_size_previous)
20256 << PreviousField << PreviousField->getType();
20257 }
20258 }
20259 // Keep track of the number of named members.
20260 if (FD->getIdentifier())
20261 ++NumNamedMembers;
20262 }
20263
20264 // Okay, we successfully defined 'Record'.
20265 if (Record) {
20266 bool Completed = false;
20267 if (S) {
20268 Scope *Parent = S->getParent();
20269 if (Parent && Parent->isTypeAliasScope() &&
20270 Parent->isTemplateParamScope())
20271 Record->setInvalidDecl();
20272 }
20273
20274 if (CXXRecord) {
20275 if (!CXXRecord->isInvalidDecl()) {
20276 // Set access bits correctly on the directly-declared conversions.
20278 I = CXXRecord->conversion_begin(),
20279 E = CXXRecord->conversion_end(); I != E; ++I)
20280 I.setAccess((*I)->getAccess());
20281 }
20282
20283 // Add any implicitly-declared members to this class.
20285
20286 if (!CXXRecord->isDependentType()) {
20287 if (!CXXRecord->isInvalidDecl()) {
20288 // If we have virtual base classes, we may end up finding multiple
20289 // final overriders for a given virtual function. Check for this
20290 // problem now.
20291 if (CXXRecord->getNumVBases()) {
20292 CXXFinalOverriderMap FinalOverriders;
20293 CXXRecord->getFinalOverriders(FinalOverriders);
20294
20295 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20296 MEnd = FinalOverriders.end();
20297 M != MEnd; ++M) {
20298 for (OverridingMethods::iterator SO = M->second.begin(),
20299 SOEnd = M->second.end();
20300 SO != SOEnd; ++SO) {
20301 assert(SO->second.size() > 0 &&
20302 "Virtual function without overriding functions?");
20303 if (SO->second.size() == 1)
20304 continue;
20305
20306 // C++ [class.virtual]p2:
20307 // In a derived class, if a virtual member function of a base
20308 // class subobject has more than one final overrider the
20309 // program is ill-formed.
20310 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
20311 << (const NamedDecl *)M->first << Record;
20312 Diag(M->first->getLocation(),
20313 diag::note_overridden_virtual_function);
20315 OM = SO->second.begin(),
20316 OMEnd = SO->second.end();
20317 OM != OMEnd; ++OM)
20318 Diag(OM->Method->getLocation(), diag::note_final_overrider)
20319 << (const NamedDecl *)M->first << OM->Method->getParent();
20320
20321 Record->setInvalidDecl();
20322 }
20323 }
20324 CXXRecord->completeDefinition(&FinalOverriders);
20325 Completed = true;
20326 }
20327 }
20328 ComputeSelectedDestructor(*this, CXXRecord);
20330 }
20331 }
20332
20333 if (!Completed)
20334 Record->completeDefinition();
20335
20336 // Handle attributes before checking the layout.
20338
20339 // Maybe randomize the record's decls. We automatically randomize a record
20340 // of function pointers, unless it has the "no_randomize_layout" attribute.
20341 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20342 !Record->isRandomized() && !Record->isUnion() &&
20343 (Record->hasAttr<RandomizeLayoutAttr>() ||
20344 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20345 EntirelyFunctionPointers(Record)))) {
20346 SmallVector<Decl *, 32> NewDeclOrdering;
20348 NewDeclOrdering))
20349 Record->reorderDecls(NewDeclOrdering);
20350 }
20351
20352 // We may have deferred checking for a deleted destructor. Check now.
20353 if (CXXRecord) {
20354 auto *Dtor = CXXRecord->getDestructor();
20355 if (Dtor && Dtor->isImplicit() &&
20357 CXXRecord->setImplicitDestructorIsDeleted();
20358 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20359 }
20360 }
20361
20362 if (Record->hasAttrs()) {
20364
20365 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20367 IA->getRange(), IA->getBestCase(),
20368 IA->getInheritanceModel());
20369 }
20370
20371 // Check if the structure/union declaration is a type that can have zero
20372 // size in C. For C this is a language extension, for C++ it may cause
20373 // compatibility problems.
20374 bool CheckForZeroSize;
20375 if (!getLangOpts().CPlusPlus) {
20376 CheckForZeroSize = true;
20377 } else {
20378 // For C++ filter out types that cannot be referenced in C code.
20380 CheckForZeroSize =
20381 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20382 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20383 CXXRecord->isCLike();
20384 }
20385 if (CheckForZeroSize) {
20386 bool ZeroSize = true;
20387 bool IsEmpty = true;
20388 unsigned NonBitFields = 0;
20389 for (RecordDecl::field_iterator I = Record->field_begin(),
20390 E = Record->field_end();
20391 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20392 IsEmpty = false;
20393 if (I->isUnnamedBitField()) {
20394 if (!I->isZeroLengthBitField())
20395 ZeroSize = false;
20396 } else {
20397 ++NonBitFields;
20398 QualType FieldType = I->getType();
20399 if (FieldType->isIncompleteType() ||
20400 !Context.getTypeSizeInChars(FieldType).isZero())
20401 ZeroSize = false;
20402 }
20403 }
20404
20405 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20406 // allowed in C++, but warn if its declaration is inside
20407 // extern "C" block.
20408 if (ZeroSize) {
20409 Diag(RecLoc, getLangOpts().CPlusPlus ?
20410 diag::warn_zero_size_struct_union_in_extern_c :
20411 diag::warn_zero_size_struct_union_compat)
20412 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20413 }
20414
20415 // Structs without named members are extension in C (C99 6.7.2.1p7),
20416 // but are accepted by GCC. In C2y, this became implementation-defined
20417 // (C2y 6.7.3.2p10).
20418 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20419 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20420 : diag::ext_no_named_members_in_struct_union)
20421 << Record->isUnion();
20422 }
20423 }
20424 } else {
20425 ObjCIvarDecl **ClsFields =
20426 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20427 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20428 ID->setEndOfDefinitionLoc(RBrac);
20429 // Add ivar's to class's DeclContext.
20430 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20431 ClsFields[i]->setLexicalDeclContext(ID);
20432 ID->addDecl(ClsFields[i]);
20433 }
20434 // Must enforce the rule that ivars in the base classes may not be
20435 // duplicates.
20436 if (ID->getSuperClass())
20437 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20438 } else if (ObjCImplementationDecl *IMPDecl =
20439 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20440 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20441 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20442 // Ivar declared in @implementation never belongs to the implementation.
20443 // Only it is in implementation's lexical context.
20444 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20445 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20446 RBrac);
20447 IMPDecl->setIvarLBraceLoc(LBrac);
20448 IMPDecl->setIvarRBraceLoc(RBrac);
20449 } else if (ObjCCategoryDecl *CDecl =
20450 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20451 // case of ivars in class extension; all other cases have been
20452 // reported as errors elsewhere.
20453 // FIXME. Class extension does not have a LocEnd field.
20454 // CDecl->setLocEnd(RBrac);
20455 // Add ivar's to class extension's DeclContext.
20456 // Diagnose redeclaration of private ivars.
20457 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20458 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20459 if (IDecl) {
20460 if (const ObjCIvarDecl *ClsIvar =
20461 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20462 Diag(ClsFields[i]->getLocation(),
20463 diag::err_duplicate_ivar_declaration);
20464 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20465 continue;
20466 }
20467 for (const auto *Ext : IDecl->known_extensions()) {
20468 if (const ObjCIvarDecl *ClsExtIvar
20469 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20470 Diag(ClsFields[i]->getLocation(),
20471 diag::err_duplicate_ivar_declaration);
20472 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20473 continue;
20474 }
20475 }
20476 }
20477 ClsFields[i]->setLexicalDeclContext(CDecl);
20478 CDecl->addDecl(ClsFields[i]);
20479 }
20480 CDecl->setIvarLBraceLoc(LBrac);
20481 CDecl->setIvarRBraceLoc(RBrac);
20482 }
20483 }
20486}
20487
20488// Given an integral type, return the next larger integral type
20489// (or a NULL type of no such type exists).
20491 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20492 // enum checking below.
20493 assert((T->isIntegralType(Context) ||
20494 T->isEnumeralType()) && "Integral type required!");
20495 const unsigned NumTypes = 4;
20496 QualType SignedIntegralTypes[NumTypes] = {
20497 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20498 };
20499 QualType UnsignedIntegralTypes[NumTypes] = {
20500 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20501 Context.UnsignedLongLongTy
20502 };
20503
20504 // Compare value widths, not storage sizes: a _BitInt(33) is stored in 64
20505 // bits but a 64-bit standard type can still represent its incremented
20506 // value. C23 6.7.3.3p12 does not allow the widened type to be a
20507 // bit-precise type either.
20508 unsigned BitWidth = Context.getIntWidth(T);
20509 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20510 : UnsignedIntegralTypes;
20511 for (unsigned I = 0; I != NumTypes; ++I)
20512 if (Context.getTypeSize(Types[I]) > BitWidth)
20513 return Types[I];
20514
20515 return QualType();
20516}
20517
20519 EnumConstantDecl *LastEnumConst,
20520 SourceLocation IdLoc,
20521 IdentifierInfo *Id,
20522 Expr *Val) {
20523 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20524 llvm::APSInt EnumVal(IntWidth);
20525 QualType EltTy;
20526
20528 Val = nullptr;
20529
20530 if (Val)
20531 Val = DefaultLvalueConversion(Val).get();
20532
20533 if (Val) {
20534 if (Enum->isDependentType() || Val->isTypeDependent() ||
20535 Val->containsErrors())
20536 EltTy = Context.DependentTy;
20537 else {
20538 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20539 // underlying type, but do allow it in all other contexts.
20540 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20541 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20542 // constant-expression in the enumerator-definition shall be a converted
20543 // constant expression of the underlying type.
20544 EltTy = Enum->getIntegerType();
20546 Val, EltTy, EnumVal, CCEKind::Enumerator);
20547 if (Converted.isInvalid())
20548 Val = nullptr;
20549 else
20550 Val = Converted.get();
20551 } else if (!Val->isValueDependent() &&
20552 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20554 .get())) {
20555 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20556 } else {
20557 if (Enum->isComplete()) {
20558 EltTy = Enum->getIntegerType();
20559
20560 // In Obj-C and Microsoft mode, require the enumeration value to be
20561 // representable in the underlying type of the enumeration. In C++11,
20562 // we perform a non-narrowing conversion as part of converted constant
20563 // expression checking.
20564 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20565 if (Context.getTargetInfo()
20566 .getTriple()
20567 .isWindowsMSVCEnvironment()) {
20568 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20569 } else {
20570 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20571 }
20572 }
20573
20574 // Cast to the underlying type.
20575 Val = ImpCastExprToType(Val, EltTy,
20576 EltTy->isBooleanType() ? CK_IntegralToBoolean
20577 : CK_IntegralCast)
20578 .get();
20579 } else if (getLangOpts().CPlusPlus) {
20580 // C++11 [dcl.enum]p5:
20581 // If the underlying type is not fixed, the type of each enumerator
20582 // is the type of its initializing value:
20583 // - If an initializer is specified for an enumerator, the
20584 // initializing value has the same type as the expression.
20585 EltTy = Val->getType();
20586 } else {
20587 // C99 6.7.2.2p2:
20588 // The expression that defines the value of an enumeration constant
20589 // shall be an integer constant expression that has a value
20590 // representable as an int.
20591
20592 // Complain if the value is not representable in an int.
20593 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20594 Diag(IdLoc, getLangOpts().C23
20595 ? diag::warn_c17_compat_enum_value_not_int
20596 : diag::ext_c23_enum_value_not_int)
20597 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20598 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20599 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20600 // Force the type of the expression to 'int'.
20601 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20602 }
20603 EltTy = Val->getType();
20604 }
20605 }
20606 }
20607 }
20608
20609 if (!Val) {
20610 if (Enum->isDependentType())
20611 EltTy = Context.DependentTy;
20612 else if (!LastEnumConst) {
20613 // C++0x [dcl.enum]p5:
20614 // If the underlying type is not fixed, the type of each enumerator
20615 // is the type of its initializing value:
20616 // - If no initializer is specified for the first enumerator, the
20617 // initializing value has an unspecified integral type.
20618 //
20619 // GCC uses 'int' for its unspecified integral type, as does
20620 // C99 6.7.2.2p3.
20621 if (Enum->isFixed()) {
20622 EltTy = Enum->getIntegerType();
20623 }
20624 else {
20625 EltTy = Context.IntTy;
20626 }
20627 } else {
20628 // Assign the last value + 1.
20629 EnumVal = LastEnumConst->getInitVal();
20630 ++EnumVal;
20631 EltTy = LastEnumConst->getType();
20632
20633 // Check for overflow on increment.
20634 if (EnumVal < LastEnumConst->getInitVal()) {
20635 // C++0x [dcl.enum]p5:
20636 // If the underlying type is not fixed, the type of each enumerator
20637 // is the type of its initializing value:
20638 //
20639 // - Otherwise the type of the initializing value is the same as
20640 // the type of the initializing value of the preceding enumerator
20641 // unless the incremented value is not representable in that type,
20642 // in which case the type is an unspecified integral type
20643 // sufficient to contain the incremented value. If no such type
20644 // exists, the program is ill-formed.
20646 if (T.isNull() || Enum->isFixed()) {
20647 // There is no integral type larger enough to represent this
20648 // value. Complain, then allow the value to wrap around.
20649 EnumVal = LastEnumConst->getInitVal();
20650 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20651 ++EnumVal;
20652 if (Enum->isFixed())
20653 // When the underlying type is fixed, this is ill-formed.
20654 Diag(IdLoc, diag::err_enumerator_wrapped)
20655 << toString(EnumVal, 10)
20656 << EltTy;
20657 else
20658 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20659 << toString(EnumVal, 10);
20660 } else {
20661 EltTy = T;
20662 }
20663
20664 // Retrieve the last enumerator's value, extent that type to the
20665 // type that is supposed to be large enough to represent the incremented
20666 // value, then increment.
20667 EnumVal = LastEnumConst->getInitVal();
20668 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20669 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20670 ++EnumVal;
20671
20672 // If we're not in C++, diagnose the overflow of enumerator values,
20673 // which in C99 means that the enumerator value is not representable in
20674 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20675 // are representable in some larger integral type and we allow it in
20676 // older language modes as an extension.
20677 // Exclude fixed enumerators since they are diagnosed with an error for
20678 // this case.
20679 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20680 Diag(IdLoc, getLangOpts().C23
20681 ? diag::warn_c17_compat_enum_value_not_int
20682 : diag::ext_c23_enum_value_not_int)
20683 << 1 << toString(EnumVal, 10) << 1;
20684 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20685 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20686 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20687 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20688 : diag::ext_c23_enum_value_not_int)
20689 << 1 << toString(EnumVal, 10) << 1;
20690 }
20691 }
20692 }
20693
20694 if (!EltTy->isDependentType()) {
20695 // Make the enumerator value match the signedness and size of the
20696 // enumerator's type.
20697 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20698 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20699 }
20700
20701 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20702 Val, EnumVal);
20703}
20704
20706 SourceLocation IILoc) {
20707 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20709 return SkipBodyInfo();
20710
20711 // We have an anonymous enum definition. Look up the first enumerator to
20712 // determine if we should merge the definition with an existing one and
20713 // skip the body.
20714 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20716 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20717 if (!PrevECD)
20718 return SkipBodyInfo();
20719
20720 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20721 NamedDecl *Hidden;
20722 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20724 Skip.Previous = Hidden;
20725 return Skip;
20726 }
20727
20728 return SkipBodyInfo();
20729}
20730
20731Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20732 SourceLocation IdLoc, IdentifierInfo *Id,
20733 const ParsedAttributesView &Attrs,
20734 SourceLocation EqualLoc, Expr *Val,
20735 SkipBodyInfo *SkipBody) {
20736 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20737 EnumConstantDecl *LastEnumConst =
20738 cast_or_null<EnumConstantDecl>(lastEnumConst);
20739
20740 // The scope passed in may not be a decl scope. Zip up the scope tree until
20741 // we find one that is.
20742 S = getNonFieldDeclScope(S);
20743
20744 // Verify that there isn't already something declared with this name in this
20745 // scope.
20746 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20748 LookupName(R, S);
20749 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20750
20751 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20752 // Maybe we will complain about the shadowed template parameter.
20753 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20754 // Just pretend that we didn't see the previous declaration.
20755 PrevDecl = nullptr;
20756 }
20757
20758 // C++ [class.mem]p15:
20759 // If T is the name of a class, then each of the following shall have a name
20760 // different from T:
20761 // - every enumerator of every member of class T that is an unscoped
20762 // enumerated type
20763 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20765 DeclarationNameInfo(Id, IdLoc)))
20766 return nullptr;
20767
20769 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20770 if (!New)
20771 return nullptr;
20772
20773 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20774 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20775 // Check for other kinds of shadowing not already handled.
20776 CheckShadow(New, PrevDecl, R);
20777 }
20778
20779 // When in C++, we may get a TagDecl with the same name; in this case the
20780 // enum constant will 'hide' the tag.
20781 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20782 "Received TagDecl when not in C++!");
20783 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20784 if (isa<EnumConstantDecl>(PrevDecl))
20785 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20786 else
20787 Diag(IdLoc, diag::err_redefinition) << Id;
20788 notePreviousDefinition(PrevDecl, IdLoc);
20789 return nullptr;
20790 }
20791 }
20792
20793 // Process attributes.
20794 ProcessDeclAttributeList(S, New, Attrs);
20797
20798 // Register this decl in the current scope stack.
20799 New->setAccess(TheEnumDecl->getAccess());
20801
20803
20804 return New;
20805}
20806
20807// Returns true when the enum initial expression does not trigger the
20808// duplicate enum warning. A few common cases are exempted as follows:
20809// Element2 = Element1
20810// Element2 = Element1 + 1
20811// Element2 = Element1 - 1
20812// Where Element2 and Element1 are from the same enum.
20814 Expr *InitExpr = ECD->getInitExpr();
20815 if (!InitExpr)
20816 return true;
20817 InitExpr = InitExpr->IgnoreImpCasts();
20818
20819 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20820 if (!BO->isAdditiveOp())
20821 return true;
20822 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20823 if (!IL)
20824 return true;
20825 if (IL->getValue() != 1)
20826 return true;
20827
20828 InitExpr = BO->getLHS();
20829 }
20830
20831 // This checks if the elements are from the same enum.
20832 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20833 if (!DRE)
20834 return true;
20835
20836 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20837 if (!EnumConstant)
20838 return true;
20839
20841 Enum)
20842 return true;
20843
20844 return false;
20845}
20846
20847// Emits a warning when an element is implicitly set a value that
20848// a previous element has already been set to.
20850 EnumDecl *Enum, QualType EnumType) {
20851 // Avoid anonymous enums
20852 if (!Enum->getIdentifier())
20853 return;
20854
20855 // Only check for small enums.
20856 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20857 return;
20858
20859 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20860 return;
20861
20862 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20863 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20864
20865 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20866
20867 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20868 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20869
20870 // Use int64_t as a key to avoid needing special handling for map keys.
20871 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20872 llvm::APSInt Val = D->getInitVal();
20873 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20874 };
20875
20876 DuplicatesVector DupVector;
20877 ValueToVectorMap EnumMap;
20878
20879 // Populate the EnumMap with all values represented by enum constants without
20880 // an initializer.
20881 for (auto *Element : Elements) {
20882 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20883
20884 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20885 // this constant. Skip this enum since it may be ill-formed.
20886 if (!ECD) {
20887 return;
20888 }
20889
20890 // Constants with initializers are handled in the next loop.
20891 if (ECD->getInitExpr())
20892 continue;
20893
20894 // Duplicate values are handled in the next loop.
20895 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20896 }
20897
20898 if (EnumMap.size() == 0)
20899 return;
20900
20901 // Create vectors for any values that has duplicates.
20902 for (auto *Element : Elements) {
20903 // The last loop returned if any constant was null.
20905 if (!ValidDuplicateEnum(ECD, Enum))
20906 continue;
20907
20908 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20909 if (Iter == EnumMap.end())
20910 continue;
20911
20912 DeclOrVector& Entry = Iter->second;
20913 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20914 // Ensure constants are different.
20915 if (D == ECD)
20916 continue;
20917
20918 // Create new vector and push values onto it.
20919 auto Vec = std::make_unique<ECDVector>();
20920 Vec->push_back(D);
20921 Vec->push_back(ECD);
20922
20923 // Update entry to point to the duplicates vector.
20924 Entry = Vec.get();
20925
20926 // Store the vector somewhere we can consult later for quick emission of
20927 // diagnostics.
20928 DupVector.emplace_back(std::move(Vec));
20929 continue;
20930 }
20931
20932 ECDVector *Vec = cast<ECDVector *>(Entry);
20933 // Make sure constants are not added more than once.
20934 if (*Vec->begin() == ECD)
20935 continue;
20936
20937 Vec->push_back(ECD);
20938 }
20939
20940 // Emit diagnostics.
20941 for (const auto &Vec : DupVector) {
20942 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20943
20944 // Emit warning for one enum constant.
20945 auto *FirstECD = Vec->front();
20946 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20947 << FirstECD << toString(FirstECD->getInitVal(), 10)
20948 << FirstECD->getSourceRange();
20949
20950 // Emit one note for each of the remaining enum constants with
20951 // the same value.
20952 for (auto *ECD : llvm::drop_begin(*Vec))
20953 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20954 << ECD << toString(ECD->getInitVal(), 10)
20955 << ECD->getSourceRange();
20956 }
20957}
20958
20959bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20960 bool AllowMask) const {
20961 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20962 assert(ED->isCompleteDefinition() && "expected enum definition");
20963
20964 auto R = FlagBitsCache.try_emplace(ED);
20965 llvm::APInt &FlagBits = R.first->second;
20966
20967 if (R.second) {
20968 for (auto *E : ED->enumerators()) {
20969 const auto &EVal = E->getInitVal();
20970 // Only single-bit enumerators introduce new flag values.
20971 if (EVal.isPowerOf2())
20972 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20973 }
20974 }
20975
20976 // A value is in a flag enum if either its bits are a subset of the enum's
20977 // flag bits (the first condition) or we are allowing masks and the same is
20978 // true of its complement (the second condition). When masks are allowed, we
20979 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20980 //
20981 // While it's true that any value could be used as a mask, the assumption is
20982 // that a mask will have all of the insignificant bits set. Anything else is
20983 // likely a logic error.
20984 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20985 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20986}
20987
20988// Emits a warning when a suspicious comparison operator is used along side
20989// binary operators in enum initializers.
20991 const EnumDecl *Enum) {
20992 bool HasBitwiseOp = false;
20993 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20994
20995 // Iterate over all the enum values, gather suspisious comparison ops and
20996 // whether any enum initialisers contain a binary operator.
20997 for (const auto *ECD : Enum->enumerators()) {
20998 const Expr *InitExpr = ECD->getInitExpr();
20999 if (!InitExpr)
21000 continue;
21001
21002 const Expr *E = InitExpr->IgnoreParenImpCasts();
21003
21004 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
21005 BinaryOperatorKind Op = BinOp->getOpcode();
21006
21007 // Check for bitwise ops (<<, >>, &, |)
21008 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
21009 HasBitwiseOp = true;
21010 } else if (Op == BO_LT || Op == BO_GT) {
21011 // Check for the typo pattern (Comparison < or >)
21012 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
21013 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
21014 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
21015 if (IntLiteral->getValue() == 1)
21016 SuspiciousCompares.push_back(BinOp);
21017 }
21018 }
21019 }
21020 }
21021
21022 // If we found a bitwise op and some sus compares, iterate over the compares
21023 // and warn.
21024 if (HasBitwiseOp) {
21025 for (const auto *BinOp : SuspiciousCompares) {
21026 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
21029 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
21030
21031 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
21032 << BinOp->getOpcodeStr() << SuggestedOp;
21033
21034 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
21035 << SuggestedOp
21036 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
21037 }
21038 }
21039}
21040
21042 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
21043 const ParsedAttributesView &Attrs) {
21044 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
21045 CanQualType EnumType = Context.getCanonicalTagType(Enum);
21046
21047 ProcessDeclAttributeList(S, Enum, Attrs);
21049
21050 if (Enum->isDependentType()) {
21051 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
21052 EnumConstantDecl *ECD =
21053 cast_or_null<EnumConstantDecl>(Elements[i]);
21054 if (!ECD) continue;
21055
21056 ECD->setType(EnumType);
21057 }
21058
21059 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
21060 return;
21061 }
21062
21063 // Verify that all the values are okay, compute the size of the values, and
21064 // reverse the list.
21065 unsigned NumNegativeBits = 0;
21066 unsigned NumPositiveBits = 0;
21067 bool MembersRepresentableByInt =
21068 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
21069
21070 // Figure out the type that should be used for this enum.
21071 QualType BestType;
21072 unsigned BestWidth;
21073
21074 // C++0x N3000 [conv.prom]p3:
21075 // An rvalue of an unscoped enumeration type whose underlying
21076 // type is not fixed can be converted to an rvalue of the first
21077 // of the following types that can represent all the values of
21078 // the enumeration: int, unsigned int, long int, unsigned long
21079 // int, long long int, or unsigned long long int.
21080 // C99 6.4.4.3p2:
21081 // An identifier declared as an enumeration constant has type int.
21082 // The C99 rule is modified by C23.
21083 QualType BestPromotionType;
21084
21085 bool Packed = Enum->hasAttr<PackedAttr>();
21086 // -fshort-enums is the equivalent to specifying the packed attribute on all
21087 // enum definitions.
21088 if (LangOpts.ShortEnums)
21089 Packed = true;
21090
21091 // If the enum already has a type because it is fixed or dictated by the
21092 // target, promote that type instead of analyzing the enumerators.
21093 if (Enum->isComplete()) {
21094 BestType = Enum->getIntegerType();
21095 if (Context.isPromotableIntegerType(BestType))
21096 BestPromotionType = Context.getPromotedIntegerType(BestType);
21097 else
21098 BestPromotionType = BestType;
21099
21100 BestWidth = Context.getIntWidth(BestType);
21101 } else {
21102 bool EnumTooLarge = Context.computeBestEnumTypes(
21103 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21104 BestWidth = Context.getIntWidth(BestType);
21105 if (EnumTooLarge)
21106 Diag(Enum->getLocation(), diag::ext_enum_too_large);
21107 }
21108
21109 // Loop over all of the enumerator constants, changing their types to match
21110 // the type of the enum if needed.
21111 for (auto *D : Elements) {
21112 auto *ECD = cast_or_null<EnumConstantDecl>(D);
21113 if (!ECD) continue; // Already issued a diagnostic.
21114
21115 // C99 says the enumerators have int type, but we allow, as an
21116 // extension, the enumerators to be larger than int size. If each
21117 // enumerator value fits in an int, type it as an int, otherwise type it the
21118 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21119 // that X has type 'int', not 'unsigned'.
21120
21121 // Determine whether the value fits into an int.
21122 llvm::APSInt InitVal = ECD->getInitVal();
21123
21124 // If it fits into an integer type, force it. Otherwise force it to match
21125 // the enum decl type.
21126 QualType NewTy;
21127 unsigned NewWidth;
21128 bool NewSign;
21129 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21130 MembersRepresentableByInt) {
21131 // C23 6.7.3.3.3p15:
21132 // The enumeration member type for an enumerated type without fixed
21133 // underlying type upon completion is:
21134 // - int if all the values of the enumeration are representable as an
21135 // int; or,
21136 // - the enumerated type
21137 NewTy = Context.IntTy;
21138 NewWidth = Context.getTargetInfo().getIntWidth();
21139 NewSign = true;
21140 } else if (ECD->getType() == BestType) {
21141 // Already the right type!
21142 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21143 // C++ [dcl.enum]p4: Following the closing brace of an
21144 // enum-specifier, each enumerator has the type of its
21145 // enumeration.
21146 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21147 // with fixed underlying type is the enumerated type.
21148 ECD->setType(EnumType);
21149 continue;
21150 } else {
21151 NewTy = BestType;
21152 NewWidth = BestWidth;
21153 NewSign = BestType->isSignedIntegerOrEnumerationType();
21154 }
21155
21156 // Adjust the APSInt value.
21157 InitVal = InitVal.extOrTrunc(NewWidth);
21158 InitVal.setIsSigned(NewSign);
21159 ECD->setInitVal(Context, InitVal);
21160
21161 // Adjust the Expr initializer and type.
21162 if (ECD->getInitExpr() &&
21163 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
21164 ECD->setInitExpr(ImplicitCastExpr::Create(
21165 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
21166 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
21167 if (getLangOpts().CPlusPlus ||
21168 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21169 // C++ [dcl.enum]p4: Following the closing brace of an
21170 // enum-specifier, each enumerator has the type of its
21171 // enumeration.
21172 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21173 // with fixed underlying type is the enumerated type.
21174 ECD->setType(EnumType);
21175 else
21176 ECD->setType(NewTy);
21177 }
21178
21179 Enum->completeDefinition(BestType, BestPromotionType,
21180 NumPositiveBits, NumNegativeBits);
21181
21182 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
21184
21185 if (Enum->isClosedFlag()) {
21186 for (Decl *D : Elements) {
21187 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
21188 if (!ECD) continue; // Already issued a diagnostic.
21189
21190 llvm::APSInt InitVal = ECD->getInitVal();
21191 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21192 !IsValueInFlagEnum(Enum, InitVal, true))
21193 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
21194 << ECD << Enum;
21195 }
21196 }
21197
21198 // Now that the enum type is defined, ensure it's not been underaligned.
21199 if (Enum->hasAttrs())
21201}
21202
21204 SourceLocation EndLoc) {
21205
21207 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
21208 CurContext->addDecl(New);
21209 return New;
21210}
21211
21213 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
21214 CurContext->addDecl(New);
21215 PushDeclContext(S, New);
21217 PushCompoundScope(false);
21218 return New;
21219}
21220
21222 if (Statement)
21223 D->setStmt(Statement);
21227}
21228
21230 IdentifierInfo* AliasName,
21231 SourceLocation PragmaLoc,
21232 SourceLocation NameLoc,
21233 SourceLocation AliasNameLoc) {
21234 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
21236 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21238 AsmLabelAttr *Attr =
21239 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
21240
21241 // If a declaration that:
21242 // 1) declares a function or a variable
21243 // 2) has external linkage
21244 // already exists, add a label attribute to it.
21245 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21246 if (isDeclExternC(PrevDecl))
21247 PrevDecl->addAttr(Attr);
21248 else
21249 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
21250 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
21251 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21252 } else
21253 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
21254}
21255
21257 SourceLocation PragmaLoc,
21258 SourceLocation NameLoc) {
21259 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
21260
21261 if (PrevDecl) {
21262 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
21263 } else {
21264 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
21265 }
21266}
21267
21269 IdentifierInfo* AliasName,
21270 SourceLocation PragmaLoc,
21271 SourceLocation NameLoc,
21272 SourceLocation AliasNameLoc) {
21273 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
21275 WeakInfo W = WeakInfo(Name, NameLoc);
21276
21277 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21278 if (!PrevDecl->hasAttr<AliasAttr>())
21279 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
21281 } else {
21282 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
21283 }
21284}
21285
21287 bool Final) {
21288 assert(FD && "Expected non-null FunctionDecl");
21289
21290 // Templates are emitted when they're instantiated.
21291 if (FD->isDependentContext())
21293
21294 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21295 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21296 FD->hasAttr<SYCLExternalAttr>()))
21298
21299 // Check whether this function is an externally visible definition.
21300 auto IsEmittedForExternalSymbol = [this, FD]() {
21301 // We have to check the GVA linkage of the function's *definition* -- if we
21302 // only have a declaration, we don't know whether or not the function will
21303 // be emitted, because (say) the definition could include "inline".
21304 const FunctionDecl *Def = FD->getDefinition();
21305
21306 // We can't compute linkage when we skip function bodies.
21307 return Def && !Def->hasSkippedBody() &&
21309 getASTContext().GetGVALinkageForFunction(Def));
21310 };
21311
21312 if (LangOpts.OpenMPIsTargetDevice) {
21313 // In OpenMP device mode we will not emit host only functions, or functions
21314 // we don't need due to their linkage.
21315 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21316 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21317 // DevTy may be changed later by
21318 // #pragma omp declare target to(*) device_type(*).
21319 // Therefore DevTy having no value does not imply host. The emission status
21320 // will be checked again at the end of compilation unit with Final = true.
21321 if (DevTy)
21322 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21324 // If we have an explicit value for the device type, or we are in a target
21325 // declare context, we need to emit all extern and used symbols.
21326 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21327 if (IsEmittedForExternalSymbol())
21329 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21330 // we'll omit it.
21331 if (Final)
21333 } else if (LangOpts.OpenMP > 45) {
21334 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21335 // function. In 5.0, no_host was introduced which might cause a function to
21336 // be omitted.
21337 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21338 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21339 if (DevTy)
21340 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21342 }
21343
21344 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21346
21347 if (LangOpts.CUDA) {
21348 // When compiling for device, host functions are never emitted. Similarly,
21349 // when compiling for host, device and global functions are never emitted.
21350 // (Technically, we do emit a host-side stub for global functions, but this
21351 // doesn't count for our purposes here.)
21353 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21355 if (!LangOpts.CUDAIsDevice &&
21358
21359 if (IsEmittedForExternalSymbol())
21361 }
21362
21363 // Otherwise, the function is known-emitted if it's in our set of
21364 // known-emitted functions.
21366}
21367
21369 // Host-side references to a __global__ function refer to the stub, so the
21370 // function itself is never emitted and therefore should not be marked.
21371 // If we have host fn calls kernel fn calls host+device, the HD function
21372 // does not get instantiated on the host. We model this by omitting at the
21373 // call to the kernel from the callgraph. This ensures that, when compiling
21374 // for host, only HD functions actually called from the host get marked as
21375 // known-emitted.
21376 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21378}
21379
21381 bool &Visible) {
21382 Visible = hasVisibleDefinition(D, Suggested);
21383 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21384 // for declaratins which is attached to named modules.
21385 // We only did this if the current module is named module as we have better
21386 // diagnostics for declarations in global module and named modules.
21387 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21388 D->isInNamedModule())
21389 return false;
21390 // The redefinition of D in the **current** TU is allowed if D is invisible or
21391 // D is defined in the global module of other module units.
21392 return D->isInAnotherModuleUnit() || !Visible;
21393}
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:2208
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.
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
#define SM(sm)
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:183
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:181
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:236
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:848
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:612
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 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:631
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:863
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 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:122
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:223
SourceManager & getSourceManager()
Definition ASTContext.h:869
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:808
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
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:927
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:3553
Wrapper for source info for arrays.
Definition TypeLoc.h:1777
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1779
Expr * getSizeExpr() const
Definition TypeLoc.h:1799
TypeLoc getElementLoc() const
Definition TypeLoc.h:1807
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1787
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3798
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
bool isInherited() const
Definition Attr.h:101
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:622
AttributeFactory & getFactory() const
Definition ParsedAttr.h:718
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:4513
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4501
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
Expr * getLHS() const
Definition Expr.h:4094
StringRef getOpcodeStr() const
Definition Expr.h:4110
Expr * getRHS() const
Definition Expr.h:4096
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
A binding in a decomposition declaration.
Definition DeclCXX.h:4206
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4716
bool doesNotEscape() const
Definition Decl.h:4867
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:236
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:383
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:1695
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
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:2968
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:2898
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:2145
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:2200
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:2284
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2319
bool isConst() const
Definition DeclCXX.h:2197
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:2254
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:617
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1377
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1573
base_class_range bases()
Definition DeclCXX.h:608
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
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:615
capture_const_range captures() const
Definition DeclCXX.h:1102
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1153
bool hasDefinition() const
Definition DeclCXX.h:561
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:1064
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1124
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2058
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
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:3153
bool isCallToStdMove() const
Definition Expr.cpp:3651
Expr * getCallee()
Definition Expr.h:3096
arg_range arguments()
Definition Expr.h:3201
CastKind getCastKind() const
Definition Expr.h:3726
Expr * getSubExpr()
Definition Expr.h:3732
static CharSourceRange getCharRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Declaration of a class template.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
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:251
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:291
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
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:2259
bool isFileContext() const
Definition DeclBase.h:2197
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2607
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:2219
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:2202
bool isRecord() const
Definition DeclBase.h:2206
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:2403
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
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()
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:1276
ValueDecl * getDecl()
Definition Expr.h:1344
SourceLocation getBeginLoc() const
Definition Expr.h:1355
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:704
bool isModulePrivateSpecified() const
Definition DeclSpec.h:885
static const TST TST_typeof_unqualType
Definition DeclSpec.h:282
bool hasAutoTypeSpec() const
Definition DeclSpec.h:629
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:631
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:237
void ClearStorageClassSpecs()
Definition DeclSpec.h:546
bool isNoreturnSpecified() const
Definition DeclSpec.h:717
TST getTypeSpecType() const
Definition DeclSpec.h:568
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:541
SCS getStorageClassSpec() const
Definition DeclSpec.h:532
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:849
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:609
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:608
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:765
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:651
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:764
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:718
bool isExternInLinkageSpec() const
Definition DeclSpec.h:536
static const TST TST_union
Definition DeclSpec.h:275
SCS
storage-class-specifier
Definition DeclSpec.h:224
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:710
static const TST TST_int
Definition DeclSpec.h:258
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:886
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:581
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:844
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:533
ParsedAttributes & getAttributes()
Definition DeclSpec.h:929
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:680
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:652
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:711
Expr * getRepAsExpr() const
Definition DeclSpec.h:589
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:497
bool isInlineSpecified() const
Definition DeclSpec.h:693
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:653
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:897
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:532
static const TST TST_atomic
Definition DeclSpec.h:294
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:542
Decl * getRepAsDecl() const
Definition DeclSpec.h:585
static const TST TST_unspecified
Definition DeclSpec.h:251
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:655
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:705
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:892
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:616
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:848
static const TSCS TSCS_thread_local
Definition DeclSpec.h:240
static const TST TST_error
Definition DeclSpec.h:301
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclSpec.h:700
bool isTypeSpecOwned() const
Definition DeclSpec.h:575
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:696
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:656
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:654
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:877
bool hasExplicitSpecifier() const
Definition DeclSpec.h:707
bool hasConstexprSpecifier() const
Definition DeclSpec.h:893
static const TST TST_typeofType
Definition DeclSpec.h:280
static const TST TST_auto
Definition DeclSpec.h:291
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:888
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:99
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:2823
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:1637
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:780
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:822
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition Decl.cpp:2065
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2069
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2003
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2015
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:837
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:2049
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:2001
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2557
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2499
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2148
Expr * getAsmLabel() const
Definition DeclSpec.h:2803
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2842
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2784
void setRedeclaration(bool Val)
Definition DeclSpec.h:2865
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2437
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2440
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2185
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2734
void takeAttributesAppending(ParsedAttributes &attrs)
takeAttributesAppending - Takes attributes from the given ParsedAttributes set and add them to this d...
Definition DeclSpec.h:2777
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2814
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2764
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2495
bool isRedeclaration() const
Definition DeclSpec.h:2866
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2787
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2169
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2184
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:410
bool isFunctionDefinition() const
Definition DeclSpec.h:2838
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2167
bool hasInitializer() const
Definition DeclSpec.h:2847
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2834
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2163
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2454
bool isInvalidType() const
Definition DeclSpec.h:2815
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2183
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2427
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2850
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2155
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2588
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2431
A decomposition declaration.
Definition DeclCXX.h:4270
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:1889
SourceRange getSourceRange() const
Definition DeclSpec.h:1937
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1935
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2513
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2601
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2590
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:961
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3467
llvm::APSInt getInitVal() const
Definition Decl.h:3487
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5714
const Expr * getInitExpr() const
Definition Decl.h:3485
Represents an enum.
Definition Decl.h:4055
enumerator_range enumerators() const
Definition Decl.h:4201
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4273
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4237
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4240
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4287
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5072
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5111
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4282
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5086
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4223
void setEnumKeyRange(SourceRange Range)
Definition Decl.h:4135
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4228
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
This represents one expression.
Definition Expr.h:112
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:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
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:3356
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) 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:3079
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:144
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3204
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3307
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4713
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3440
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:4698
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4759
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5847
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
Represents a function declaration or definition.
Definition Decl.h:2029
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2729
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:2225
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2837
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2512
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4183
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3711
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4176
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4171
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3276
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2350
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2741
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2720
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4002
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3740
param_iterator param_end()
Definition Decl.h:2827
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2961
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2735
QualType getReturnType() const
Definition Decl.h:2885
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2814
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3684
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2425
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2413
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3592
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4291
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2484
void setWillHaveBody(bool V=true)
Definition Decl.h:2726
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions:
Definition Decl.h:2632
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2479
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4301
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3725
param_iterator param_begin()
Definition Decl.h:2826
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2863
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2362
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2576
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3178
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3353
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4235
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2928
bool isStatic() const
Definition Decl.h:2969
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4524
void setTrivial(bool IT)
Definition Decl.h:2414
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4122
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:2506
bool isDeletedAsWritten() const
Definition Decl.h:2580
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2389
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3596
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2393
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:2464
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2385
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2719
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2318
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3346
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2956
bool param_empty() const
Definition Decl.h:2825
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3201
void setRangeEnd(SourceLocation E)
Definition Decl.h:2254
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3680
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2421
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2457
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4547
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2973
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4116
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2509
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4395
void setDefaulted(bool D=true)
Definition Decl.h:2422
bool isConsteval() const
Definition Decl.h:2518
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:2902
void setBody(Stmt *B)
Definition Decl.cpp:3269
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3610
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3147
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2495
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4143
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3804
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2247
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3177
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2471
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:3224
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:2939
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3666
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2725
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5307
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5339
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5896
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5171
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
unsigned getNumParams() const
Definition TypeBase.h:5649
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5868
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5684
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
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:1644
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4678
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4790
CallingConv getCC() const
Definition TypeBase.h:4737
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4756
unsigned getRegParm() const
Definition TypeBase.h:4730
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4726
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4749
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4770
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4784
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
ExtInfo getExtInfo() const
Definition TypeBase.h:4923
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3708
unsigned getRegParmType() const
Definition TypeBase.h:4910
CallingConv getCallConv() const
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4907
bool getCmseNSCallAttr() const
Definition TypeBase.h:4921
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:2079
Represents a C array with an unspecified size.
Definition TypeBase.h:3973
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3511
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5741
void setInherited(bool I)
Definition Attr.h:163
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2604
child_range children()
Definition Expr.h:5510
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:981
Represents the declaration of a label.
Definition Decl.h:524
bool isResolvedMSAsmLabel() const
Definition Decl.h:559
LabelStmt * getStmt() const
Definition Decl.h:548
bool isMSAsmLabel() const
Definition Decl.h:558
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
Definition ExprCXX.h:2087
@ 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:1431
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:1375
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3036
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:3453
Expr * getBase() const
Definition Expr.h:3447
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
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:448
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:866
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:882
bool isModulePartition() const
Is this a module partition.
Definition Module.h:871
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:240
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:423
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:940
@ ClassId_NSObject
Definition NSAPI.h:30
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isLinkageValid() const
True if the computed linkage is valid.
Definition Decl.cpp:1085
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:444
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition Decl.h:479
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:429
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
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:1871
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
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:1943
bool isExternallyVisible() const
Definition Decl.h:433
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition Decl.cpp:1132
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:397
Represent a C++ namespace.
Definition Decl.h:592
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:643
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:2329
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition DeclObjC.h:2775
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:948
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:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
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:1952
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:358
param_const_iterator param_begin() const
Definition DeclObjC.h:354
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:349
bool isOptional() const
Definition DeclObjC.h:505
ParmVarDecl *const * param_iterator
Definition DeclObjC.h:350
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:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
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:1415
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1428
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1411
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3366
Represents a parameter to a function.
Definition Decl.h:1819
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1879
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1883
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1852
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1911
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:2934
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2957
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
static const ParsedAttributesView & none()
Definition ParsedAttr.h:817
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:937
AttributePool & getPool() const
Definition ParsedAttr.h:944
PipeType - OpenCL20.
Definition TypeBase.h:8265
Pointer-authentication qualifiers.
Definition TypeBase.h:152
bool isAddressDiscriminated() const
Definition TypeBase.h:265
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1494
Wrapper for source info for pointers.
Definition TypeLoc.h:1513
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1519
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
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:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8525
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:1468
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:3027
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:111
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1229
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1311
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
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:3093
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
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:8487
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:3077
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition TypeBase.h:1448
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8568
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
bool isCanonical() const
Definition TypeBase.h:8504
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1324
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1457
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2792
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition TypeBase.h:1508
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition TypeBase.h:1513
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:8387
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8394
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4796
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasConst() const
Definition TypeBase.h:457
bool hasVolatile() const
Definition TypeBase.h:467
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
bool empty() const
Definition TypeBase.h:647
Represents a struct/union/class.
Definition Decl.h:4369
field_range fields() const
Definition Decl.h:4572
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5230
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4569
field_iterator field_begin() const
Definition Decl.cpp:5273
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7515
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:5374
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3637
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3170
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3213
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 CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1446
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:741
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:208
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:829
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:894
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:984
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:748
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:714
void deduceAddressSpace(VarDecl *Decl)
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:817
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:784
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:728
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
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition SemaWasm.cpp:340
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition SemaWasm.cpp:319
bool IsAlignAttr() const
Definition Sema.h:1921
Mode getAlignMode() const
Definition Sema.h:1923
A RAII object to temporarily push a declaration context.
Definition Sema.h:3532
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1388
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1400
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3758
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3768
static NameClassification Unknown()
Definition Sema.h:3738
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3742
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3786
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3774
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3748
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3780
static NameClassification UndeclaredNonType()
Definition Sema.h:3754
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3762
static NameClassification Error()
Definition Sema.h:3734
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12595
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12629
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
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:1450
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:3636
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13191
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2679
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1143
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:8331
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6400
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9417
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9421
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9440
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9456
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9453
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9429
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9424
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:1535
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:4808
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1847
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:6592
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:1475
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:940
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2078
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2072
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:4211
@ Delete
deleted-function-body
Definition Sema.h:4217
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:1560
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:1749
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:689
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:1310
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:227
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2360
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:938
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void * SkippedDefinitionContext
Definition Sema.h:4435
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1520
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1375
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:81
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2075
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:3626
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:941
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:2071
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:770
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:713
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition SemaAttr.cpp:112
void mergeVisibilityType(Decl *D, SourceLocation Loc, VisibilityAttr::VisibilityType Type)
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1214
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1754
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
void CheckAttributesOnDeducedType(Decl *D)
CheckAttributesOnDeducedType - Calls Sema functions for attributes that requires the type to be deduc...
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12293
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8449
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:838
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2470
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
llvm::function_ref< void(SourceLocation Loc, PartialDiagnostic PD)> DiagReceiverTy
Definition Sema.h:4646
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
FPOptions & getCurFPFeatures()
Definition Sema.h:936
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2488
void PopCompoundScope()
Definition Sema.cpp:2621
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
@ UPPC_FixedUnderlyingType
The fixed underlying type of an enumeration.
Definition Sema.h:14560
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14563
@ UPPC_Initializer
An initializer.
Definition Sema.h:14575
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14569
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14548
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14587
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14572
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14551
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14554
const LangOptions & getLangOpts() const
Definition Sema.h:934
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2582
SourceLocation CurInitSegLoc
Definition Sema.h:2114
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:238
ModularFormatAttr * mergeModularFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *ModularImplFn, StringRef ImplName, MutableArrayRef< StringRef > Aspects)
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3643
SemaOpenACC & OpenACC()
Definition Sema.h:1525
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1309
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor, bool IsCopy=false)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2260
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD)
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1308
bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock)
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2697
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15656
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1485
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
PragmaClangSection PragmaClangRelroSection
Definition Sema.h:1848
SemaRISCV & RISCV()
Definition Sema.h:1550
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:15833
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *RetExpr, const AutoType *AT)
Deduce the return type for a function from a returned expression, per C++1y [dcl.spec....
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:216
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
SemaSwift & Swift()
Definition Sema.h:1565
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:2060
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7059
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2070
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1147
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition SemaDecl.cpp:912
void ExitDeclaratorContext(Scope *S)
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4823
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1343
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2616
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
bool CheckNontrivialField(FieldDecl *FD)
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7056
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:647
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15650
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3609
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2113
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9949
bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl)
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1448
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1530
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
Decl * ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams, SourceLocation EllipsisLoc)
Handle a friend type declaration.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1728