clang 23.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 S->setEntity(DC);
1389}
1390
1392 assert(CurContext && "DeclContext imbalance!");
1393
1394 CurContext = CurContext->getLexicalParent();
1395 assert(CurContext && "Popped translation unit!");
1396}
1397
1399 Decl *D) {
1400 // Unlike PushDeclContext, the context to which we return is not necessarily
1401 // the containing DC of TD, because the new context will be some pre-existing
1402 // TagDecl definition instead of a fresh one.
1403 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1404 CurContext = cast<TagDecl>(D)->getDefinition();
1405 assert(CurContext && "skipping definition of undefined tag");
1406 // Start lookups from the parent of the current context; we don't want to look
1407 // into the pre-existing complete definition.
1408 S->setEntity(CurContext->getLookupParent());
1409 return Result;
1410}
1411
1415
1417 // C++0x [basic.lookup.unqual]p13:
1418 // A name used in the definition of a static data member of class
1419 // X (after the qualified-id of the static member) is looked up as
1420 // if the name was used in a member function of X.
1421 // C++0x [basic.lookup.unqual]p14:
1422 // If a variable member of a namespace is defined outside of the
1423 // scope of its namespace then any name used in the definition of
1424 // the variable member (after the declarator-id) is looked up as
1425 // if the definition of the variable member occurred in its
1426 // namespace.
1427 // Both of these imply that we should push a scope whose context
1428 // is the semantic context of the declaration. We can't use
1429 // PushDeclContext here because that context is not necessarily
1430 // lexically contained in the current context. Fortunately,
1431 // the containing scope should have the appropriate information.
1432
1433 assert(!S->getEntity() && "scope already has entity");
1434
1435#ifndef NDEBUG
1436 Scope *Ancestor = S->getParent();
1437 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1438 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1439#endif
1440
1441 CurContext = DC;
1442 S->setEntity(DC);
1443
1444 if (S->getParent()->isTemplateParamScope()) {
1445 // Also set the corresponding entities for all immediately-enclosing
1446 // template parameter scopes.
1448 }
1449}
1450
1452 assert(S->getEntity() == CurContext && "Context imbalance!");
1453
1454 // Switch back to the lexical context. The safety of this is
1455 // enforced by an assert in EnterDeclaratorContext.
1456 Scope *Ancestor = S->getParent();
1457 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1458 CurContext = Ancestor->getEntity();
1459
1460 // We don't need to do anything with the scope, which is going to
1461 // disappear.
1462}
1463
1465 assert(S->isTemplateParamScope() &&
1466 "expected to be initializing a template parameter scope");
1467
1468 // C++20 [temp.local]p7:
1469 // In the definition of a member of a class template that appears outside
1470 // of the class template definition, the name of a member of the class
1471 // template hides the name of a template-parameter of any enclosing class
1472 // templates (but not a template-parameter of the member if the member is a
1473 // class or function template).
1474 // C++20 [temp.local]p9:
1475 // In the definition of a class template or in the definition of a member
1476 // of such a template that appears outside of the template definition, for
1477 // each non-dependent base class (13.8.2.1), if the name of the base class
1478 // or the name of a member of the base class is the same as the name of a
1479 // template-parameter, the base class name or member name hides the
1480 // template-parameter name (6.4.10).
1481 //
1482 // This means that a template parameter scope should be searched immediately
1483 // after searching the DeclContext for which it is a template parameter
1484 // scope. For example, for
1485 // template<typename T> template<typename U> template<typename V>
1486 // void N::A<T>::B<U>::f(...)
1487 // we search V then B<U> (and base classes) then U then A<T> (and base
1488 // classes) then T then N then ::.
1489 unsigned ScopeDepth = getTemplateDepth(S);
1490 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1491 DeclContext *SearchDCAfterScope = DC;
1492 for (; DC; DC = DC->getLookupParent()) {
1493 if (const TemplateParameterList *TPL =
1494 cast<Decl>(DC)->getDescribedTemplateParams()) {
1495 unsigned DCDepth = TPL->getDepth() + 1;
1496 if (DCDepth > ScopeDepth)
1497 continue;
1498 if (ScopeDepth == DCDepth)
1499 SearchDCAfterScope = DC = DC->getLookupParent();
1500 break;
1501 }
1502 }
1503 S->setLookupEntity(SearchDCAfterScope);
1504 }
1505}
1506
1508 // We assume that the caller has already called
1509 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1510 FunctionDecl *FD = D->getAsFunction();
1511 if (!FD)
1512 return;
1513
1514 // Same implementation as PushDeclContext, but enters the context
1515 // from the lexical parent, rather than the top-level class.
1516 assert(CurContext == FD->getLexicalParent() &&
1517 "The next DeclContext should be lexically contained in the current one.");
1518 CurContext = FD;
1520
1521 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1522 ParmVarDecl *Param = FD->getParamDecl(P);
1523 // If the parameter has an identifier, then add it to the scope
1524 if (Param->getIdentifier()) {
1525 S->AddDecl(Param);
1526 IdResolver.AddDecl(Param);
1527 }
1528 }
1529}
1530
1532 // Same implementation as PopDeclContext, but returns to the lexical parent,
1533 // rather than the top-level class.
1534 assert(CurContext && "DeclContext imbalance!");
1535 CurContext = CurContext->getLexicalParent();
1536 assert(CurContext && "Popped translation unit!");
1537}
1538
1539/// Determine whether overloading is allowed for a new function
1540/// declaration considering prior declarations of the same name.
1541///
1542/// This routine determines whether overloading is possible, not
1543/// whether a new declaration actually overloads a previous one.
1544/// It will return true in C++ (where overloads are always permitted)
1545/// or, as a C extension, when either the new declaration or a
1546/// previous one is declared with the 'overloadable' attribute.
1548 ASTContext &Context,
1549 const FunctionDecl *New) {
1550 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1551 return true;
1552
1553 // Multiversion function declarations are not overloads in the
1554 // usual sense of that term, but lookup will report that an
1555 // overload set was found if more than one multiversion function
1556 // declaration is present for the same name. It is therefore
1557 // inadequate to assume that some prior declaration(s) had
1558 // the overloadable attribute; checking is required. Since one
1559 // declaration is permitted to omit the attribute, it is necessary
1560 // to check at least two; hence the 'any_of' check below. Note that
1561 // the overloadable attribute is implicitly added to declarations
1562 // that were required to have it but did not.
1563 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1564 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1565 return ND->hasAttr<OverloadableAttr>();
1566 });
1567 } else if (Previous.getResultKind() == LookupResultKind::Found)
1568 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1569
1570 return false;
1571}
1572
1573void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1574 // Move up the scope chain until we find the nearest enclosing
1575 // non-transparent context. The declaration will be introduced into this
1576 // scope.
1577 while (S->getEntity() && S->getEntity()->isTransparentContext())
1578 S = S->getParent();
1579
1580 // Add scoped declarations into their context, so that they can be
1581 // found later. Declarations without a context won't be inserted
1582 // into any context.
1583 if (AddToContext)
1584 CurContext->addDecl(D);
1585
1586 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1587 // are function-local declarations.
1588 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1589 return;
1590
1591 // Template instantiations should also not be pushed into scope.
1592 if (isa<FunctionDecl>(D) &&
1593 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1594 return;
1595
1596 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1597 S->AddDecl(D);
1598 return;
1599 }
1600 // If this replaces anything in the current scope,
1602 IEnd = IdResolver.end();
1603 for (; I != IEnd; ++I) {
1604 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1605 S->RemoveDecl(*I);
1606 IdResolver.RemoveDecl(*I);
1607
1608 // Should only need to replace one decl.
1609 break;
1610 }
1611 }
1612
1613 S->AddDecl(D);
1614
1615 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1616 // Implicitly-generated labels may end up getting generated in an order that
1617 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1618 // the label at the appropriate place in the identifier chain.
1619 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1620 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1621 if (IDC == CurContext) {
1622 if (!S->isDeclScope(*I))
1623 continue;
1624 } else if (IDC->Encloses(CurContext))
1625 break;
1626 }
1627
1628 IdResolver.InsertDeclAfter(I, D);
1629 } else {
1630 IdResolver.AddDecl(D);
1631 }
1633}
1634
1636 bool AllowInlineNamespace) const {
1637 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1638}
1639
1641 DeclContext *TargetDC = DC->getPrimaryContext();
1642 do {
1643 if (DeclContext *ScopeDC = S->getEntity())
1644 if (ScopeDC->getPrimaryContext() == TargetDC)
1645 return S;
1646 } while ((S = S->getParent()));
1647
1648 return nullptr;
1649}
1650
1652 DeclContext*,
1653 ASTContext&);
1654
1656 bool ConsiderLinkage,
1657 bool AllowInlineNamespace) {
1658 LookupResult::Filter F = R.makeFilter();
1659 while (F.hasNext()) {
1660 NamedDecl *D = F.next();
1661
1662 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1663 continue;
1664
1665 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1666 continue;
1667
1668 F.erase();
1669 }
1670
1671 F.done();
1672}
1673
1675 if (auto *VD = dyn_cast<VarDecl>(D))
1676 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1677 if (auto *FD = dyn_cast<FunctionDecl>(D))
1678 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1679 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1680 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1681
1682 return false;
1683}
1684
1686 // [module.interface]p7:
1687 // A declaration is attached to a module as follows:
1688 // - If the declaration is a non-dependent friend declaration that nominates a
1689 // function with a declarator-id that is a qualified-id or template-id or that
1690 // nominates a class other than with an elaborated-type-specifier with neither
1691 // a nested-name-specifier nor a simple-template-id, it is attached to the
1692 // module to which the friend is attached ([basic.link]).
1693 if (New->getFriendObjectKind() &&
1694 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1695 New->setLocalOwningModule(Old->getOwningModule());
1697 return false;
1698 }
1699
1700 // Although we have questions for the module ownership of implicit
1701 // instantiations, it should be sure that we shouldn't diagnose the
1702 // redeclaration of incorrect module ownership for different implicit
1703 // instantiations in different modules. We will diagnose the redeclaration of
1704 // incorrect module ownership for the template itself.
1706 return false;
1707
1708 Module *NewM = New->getOwningModule();
1709 Module *OldM = Old->getOwningModule();
1710
1711 if (NewM && NewM->isPrivateModule())
1712 NewM = NewM->Parent;
1713 if (OldM && OldM->isPrivateModule())
1714 OldM = OldM->Parent;
1715
1716 if (NewM == OldM)
1717 return false;
1718
1719 if (NewM && OldM) {
1720 // A module implementation unit has visibility of the decls in its
1721 // implicitly imported interface.
1722 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1723 return false;
1724
1725 // Partitions are part of the module, but a partition could import another
1726 // module, so verify that the PMIs agree.
1727 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1728 getASTContext().isInSameModule(NewM, OldM))
1729 return false;
1730 }
1731
1732 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1733 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1734 if (NewIsModuleInterface || OldIsModuleInterface) {
1735 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1736 // if a declaration of D [...] appears in the purview of a module, all
1737 // other such declarations shall appear in the purview of the same module
1738 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1739 << New
1740 << NewIsModuleInterface
1741 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1742 << OldIsModuleInterface
1743 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1744 Diag(Old->getLocation(), diag::note_previous_declaration);
1745 New->setInvalidDecl();
1746 return true;
1747 }
1748
1749 return false;
1750}
1751
1753 // [module.interface]p1:
1754 // An export-declaration shall inhabit a namespace scope.
1755 //
1756 // So it is meaningless to talk about redeclaration which is not at namespace
1757 // scope.
1758 if (!New->getLexicalDeclContext()
1759 ->getNonTransparentContext()
1760 ->isFileContext() ||
1761 !Old->getLexicalDeclContext()
1763 ->isFileContext())
1764 return false;
1765
1766 bool IsNewExported = New->isInExportDeclContext();
1767 bool IsOldExported = Old->isInExportDeclContext();
1768
1769 // It should be irrevelant if both of them are not exported.
1770 if (!IsNewExported && !IsOldExported)
1771 return false;
1772
1773 if (IsOldExported)
1774 return false;
1775
1776 // If the Old declaration are not attached to named modules
1777 // and the New declaration are attached to global module.
1778 // It should be fine to allow the export since it doesn't change
1779 // the linkage of declarations. See
1780 // https://github.com/llvm/llvm-project/issues/98583 for details.
1781 if (!Old->isInNamedModule() && New->getOwningModule() &&
1782 New->getOwningModule()->isImplicitGlobalModule())
1783 return false;
1784
1785 assert(IsNewExported);
1786
1787 auto Lk = Old->getFormalLinkage();
1788 int S = 0;
1789 if (Lk == Linkage::Internal)
1790 S = 1;
1791 else if (Lk == Linkage::Module)
1792 S = 2;
1793 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1794 Diag(Old->getLocation(), diag::note_previous_declaration);
1795 return true;
1796}
1797
1800 return true;
1801
1803 return true;
1804
1805 return false;
1806}
1807
1809 const NamedDecl *Old) const {
1810 assert(getASTContext().isSameEntity(New, Old) &&
1811 "New and Old are not the same definition, we should diagnostic it "
1812 "immediately instead of checking it.");
1813 assert(const_cast<Sema *>(this)->isReachable(New) &&
1814 const_cast<Sema *>(this)->isReachable(Old) &&
1815 "We shouldn't see unreachable definitions here.");
1816
1817 Module *NewM = New->getOwningModule();
1818 Module *OldM = Old->getOwningModule();
1819
1820 // We only checks for named modules here. The header like modules is skipped.
1821 // FIXME: This is not right if we import the header like modules in the module
1822 // purview.
1823 //
1824 // For example, assuming "header.h" provides definition for `D`.
1825 // ```C++
1826 // //--- M.cppm
1827 // export module M;
1828 // import "header.h"; // or #include "header.h" but import it by clang modules
1829 // actually.
1830 //
1831 // //--- Use.cpp
1832 // import M;
1833 // import "header.h"; // or uses clang modules.
1834 // ```
1835 //
1836 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1837 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1838 // reject it. But the current implementation couldn't detect the case since we
1839 // don't record the information about the importee modules.
1840 //
1841 // But this might not be painful in practice. Since the design of C++20 Named
1842 // Modules suggests us to use headers in global module fragment instead of
1843 // module purview.
1844 if (NewM && NewM->isHeaderLikeModule())
1845 NewM = nullptr;
1846 if (OldM && OldM->isHeaderLikeModule())
1847 OldM = nullptr;
1848
1849 if (!NewM && !OldM)
1850 return true;
1851
1852 // [basic.def.odr]p14.3
1853 // Each such definition shall not be attached to a named module
1854 // ([module.unit]).
1855 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1856 return true;
1857
1858 // Then New and Old lives in the same TU if their share one same module unit.
1859 if (NewM)
1860 NewM = NewM->getTopLevelModule();
1861 if (OldM)
1862 OldM = OldM->getTopLevelModule();
1863 return OldM == NewM;
1864}
1865
1867 if (D->getDeclContext()->isFileContext())
1868 return false;
1869
1870 return isa<UsingShadowDecl>(D) ||
1873}
1874
1875/// Removes using shadow declarations not at class scope from the lookup
1876/// results.
1878 LookupResult::Filter F = R.makeFilter();
1879 while (F.hasNext())
1881 F.erase();
1882
1883 F.done();
1884}
1885
1886/// Check for this common pattern:
1887/// @code
1888/// class S {
1889/// S(const S&); // DO NOT IMPLEMENT
1890/// void operator=(const S&); // DO NOT IMPLEMENT
1891/// };
1892/// @endcode
1894 // FIXME: Should check for private access too but access is set after we get
1895 // the decl here.
1897 return false;
1898
1899 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1900 return CD->isCopyConstructor();
1901 return D->isCopyAssignmentOperator();
1902}
1903
1904bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1905 const DeclContext *DC = D->getDeclContext();
1906 while (!DC->isTranslationUnit()) {
1907 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1908 if (!RD->hasNameForLinkage())
1909 return true;
1910 }
1911 DC = DC->getParent();
1912 }
1913
1914 return !D->isExternallyVisible();
1915}
1916
1918 assert(D);
1919
1920 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1921 return false;
1922
1923 // Ignore all entities declared within templates, and out-of-line definitions
1924 // of members of class templates.
1925 if (D->getDeclContext()->isDependentContext() ||
1927 return false;
1928
1929 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1930 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1931 return false;
1932 // A non-out-of-line declaration of a member specialization was implicitly
1933 // instantiated; it's the out-of-line declaration that we're interested in.
1934 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1935 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1936 return false;
1937
1938 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1939 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1940 return false;
1941 } else {
1942 // 'static inline' functions are defined in headers; don't warn.
1943 if (FD->isInlined() && !isMainFileLoc(FD->getLocation()))
1944 return false;
1945 }
1946
1947 if (FD->doesThisDeclarationHaveABody() &&
1948 Context.DeclMustBeEmitted(FD))
1949 return false;
1950 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1951 // Constants and utility variables are defined in headers with internal
1952 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1953 // like "inline".)
1954 if (!isMainFileLoc(VD->getLocation()))
1955 return false;
1956
1957 if (Context.DeclMustBeEmitted(VD))
1958 return false;
1959
1960 if (VD->isStaticDataMember() &&
1961 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1962 return false;
1963 if (VD->isStaticDataMember() &&
1964 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1965 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1966 return false;
1967
1968 if (VD->isInline() && !isMainFileLoc(VD->getLocation()))
1969 return false;
1970 } else {
1971 return false;
1972 }
1973
1974 // Only warn for unused decls internal to the translation unit.
1975 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1976 // for inline functions defined in the main source file, for instance.
1977 return mightHaveNonExternalLinkage(D);
1978}
1979
1981 if (!D)
1982 return;
1983
1984 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1985 const FunctionDecl *First = FD->getFirstDecl();
1987 return; // First should already be in the vector.
1988 }
1989
1990 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1991 const VarDecl *First = VD->getFirstDecl();
1993 return; // First should already be in the vector.
1994 }
1995
1997 UnusedFileScopedDecls.push_back(D);
1998}
1999
2000static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2001 const NamedDecl *D) {
2002 if (D->isInvalidDecl())
2003 return false;
2004
2005 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2006 // For a decomposition declaration, warn if none of the bindings are
2007 // referenced, instead of if the variable itself is referenced (which
2008 // it is, by the bindings' expressions).
2009 bool IsAllIgnored = true;
2010 for (const auto *BD : DD->bindings()) {
2011 if (BD->isReferenced())
2012 return false;
2013 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2014 BD->hasAttr<UnusedAttr>());
2015 }
2016 if (IsAllIgnored)
2017 return false;
2018 } else if (!D->getDeclName()) {
2019 return false;
2020 } else if (D->isReferenced() || D->isUsed()) {
2021 return false;
2022 }
2023
2024 if (D->isPlaceholderVar(LangOpts))
2025 return false;
2026
2027 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2028 D->hasAttr<CleanupAttr>())
2029 return false;
2030
2031 if (isa<LabelDecl>(D))
2032 return true;
2033
2034 // Except for labels, we only care about unused decls that are local to
2035 // functions.
2036 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2037 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2038 // For dependent types, the diagnostic is deferred.
2039 WithinFunction =
2040 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2041 if (!WithinFunction)
2042 return false;
2043
2044 if (isa<TypedefNameDecl>(D))
2045 return true;
2046
2047 // White-list anything that isn't a local variable.
2049 return false;
2050
2051 // Types of valid local variables should be complete, so this should succeed.
2052 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2053
2054 const Expr *Init = VD->getInit();
2055 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2056 Init = Cleanups->getSubExpr();
2057
2058 const auto *Ty = VD->getType().getTypePtr();
2059
2060 // Only look at the outermost level of typedef.
2061 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2062 // Allow anything marked with __attribute__((unused)).
2063 if (TT->getDecl()->hasAttr<UnusedAttr>())
2064 return false;
2065 }
2066
2067 // Warn for reference variables whose initializtion performs lifetime
2068 // extension.
2069 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2070 MTE && MTE->getExtendingDecl()) {
2071 Ty = VD->getType().getNonReferenceType().getTypePtr();
2072 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2073 }
2074
2075 // If we failed to complete the type for some reason, or if the type is
2076 // dependent, don't diagnose the variable.
2077 if (Ty->isIncompleteType() || Ty->isDependentType())
2078 return false;
2079
2080 // Look at the element type to ensure that the warning behaviour is
2081 // consistent for both scalars and arrays.
2082 Ty = Ty->getBaseElementTypeUnsafe();
2083
2084 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2085 if (Tag->hasAttr<UnusedAttr>())
2086 return false;
2087
2088 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2089 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2090 return false;
2091
2092 if (Init) {
2093 const auto *Construct =
2094 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2095 if (Construct && !Construct->isElidable()) {
2096 const CXXConstructorDecl *CD = Construct->getConstructor();
2097 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2098 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2099 return false;
2100 }
2101
2102 // Suppress the warning if we don't know how this is constructed, and
2103 // it could possibly be non-trivial constructor.
2104 if (Init->isTypeDependent()) {
2105 for (const CXXConstructorDecl *Ctor : RD->ctors())
2106 if (!Ctor->isTrivial())
2107 return false;
2108 }
2109
2110 // Suppress the warning if the constructor is unresolved because
2111 // its arguments are dependent.
2113 return false;
2114 }
2115 }
2116 }
2117
2118 // TODO: __attribute__((unused)) templates?
2119 }
2120
2121 return true;
2122}
2123
2125 FixItHint &Hint) {
2126 if (isa<LabelDecl>(D)) {
2128 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2129 /*SkipTrailingWhitespaceAndNewline=*/false);
2130 if (AfterColon.isInvalid())
2131 return;
2133 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2134 }
2135}
2136
2139 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2140}
2141
2143 DiagReceiverTy DiagReceiver) {
2144 if (D->isDependentType())
2145 return;
2146
2147 for (auto *TmpD : D->decls()) {
2148 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2149 DiagnoseUnusedDecl(T, DiagReceiver);
2150 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2151 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2152 }
2153}
2154
2157 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2158}
2159
2162 return;
2163
2164 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2165 // typedefs can be referenced later on, so the diagnostics are emitted
2166 // at end-of-translation-unit.
2168 return;
2169 }
2170
2171 FixItHint Hint;
2173
2174 unsigned DiagID;
2175 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2176 DiagID = diag::warn_unused_exception_param;
2177 else if (isa<LabelDecl>(D))
2178 DiagID = diag::warn_unused_label;
2179 else
2180 DiagID = diag::warn_unused_variable;
2181
2182 SourceLocation DiagLoc = D->getLocation();
2183 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2184}
2185
2187 DiagReceiverTy DiagReceiver) {
2188 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2189 // it's not really unused.
2190 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2191 return;
2192
2193 // In C++, `_` variables behave as if they were maybe_unused
2194 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2195 return;
2196
2197 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2198
2199 if (Ty->isReferenceType() || Ty->isDependentType())
2200 return;
2201
2202 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2203 if (Tag->hasAttr<UnusedAttr>())
2204 return;
2205 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2206 // mimic gcc's behavior.
2207 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2208 RD && !RD->hasAttr<WarnUnusedAttr>())
2209 return;
2210 }
2211
2212 // Don't warn on volatile file-scope variables. They are visible beyond their
2213 // declaring function and writes to them could be observable side effects.
2214 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2215 return;
2216
2217 // Don't warn about __block Objective-C pointer variables, as they might
2218 // be assigned in the block but not used elsewhere for the purpose of lifetime
2219 // extension.
2220 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2221 return;
2222
2223 // Don't warn about Objective-C pointer variables with precise lifetime
2224 // semantics; they can be used to ensure ARC releases the object at a known
2225 // time, which may mean assignment but no other references.
2226 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2227 return;
2228
2229 auto iter = RefsMinusAssignments.find(VD->getCanonicalDecl());
2230 if (iter == RefsMinusAssignments.end())
2231 return;
2232
2233 assert(iter->getSecond() >= 0 &&
2234 "Found a negative number of references to a VarDecl");
2235 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2236 // Assume the given VarDecl is "used" if its ref count stored in
2237 // `RefMinusAssignments` is positive, with one exception.
2238 //
2239 // For a C++ variable whose decl (with initializer) entirely consist the
2240 // condition expression of a if/while/for construct,
2241 // Clang creates a DeclRefExpr for the condition expression rather than a
2242 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2243 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2244 // used in the body of the if/while/for construct.
2245 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2246 if (!UnusedCXXCondDecl)
2247 return;
2248 }
2249
2250 unsigned DiagID;
2251 if (isa<ParmVarDecl>(VD))
2252 DiagID = diag::warn_unused_but_set_parameter;
2253 else if (VD->isFileVarDecl())
2254 DiagID = diag::warn_unused_but_set_global;
2255 else
2256 DiagID = diag::warn_unused_but_set_variable;
2257 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2258}
2259
2261 Sema::DiagReceiverTy DiagReceiver) {
2262 // Verify that we have no forward references left. If so, there was a goto
2263 // or address of a label taken, but no definition of it. Label fwd
2264 // definitions are indicated with a null substmt which is also not a resolved
2265 // MS inline assembly label name.
2266 bool Diagnose = false;
2267 if (L->isMSAsmLabel())
2268 Diagnose = !L->isResolvedMSAsmLabel();
2269 else
2270 Diagnose = L->getStmt() == nullptr;
2271 if (Diagnose)
2272 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2273 << L);
2274}
2275
2277 S->applyNRVO();
2278
2279 if (S->decl_empty()) return;
2281 "Scope shouldn't contain decls!");
2282
2283 /// We visit the decls in non-deterministic order, but we want diagnostics
2284 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2285 /// and sort the diagnostics before emitting them, after we visited all decls.
2286 struct LocAndDiag {
2287 SourceLocation Loc;
2288 std::optional<SourceLocation> PreviousDeclLoc;
2290 };
2292 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2293 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2294 };
2295 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2296 SourceLocation PreviousDeclLoc,
2297 PartialDiagnostic PD) {
2298 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2299 };
2300
2301 for (auto *TmpD : S->decls()) {
2302 assert(TmpD && "This decl didn't get pushed??");
2303
2304 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2305 NamedDecl *D = cast<NamedDecl>(TmpD);
2306
2307 // Diagnose unused variables in this scope.
2309 DiagnoseUnusedDecl(D, addDiag);
2310 if (const auto *RD = dyn_cast<RecordDecl>(D))
2311 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2312 // Wait until end of TU to diagnose internal linkage file vars.
2313 if (auto *VD = dyn_cast<VarDecl>(D);
2314 VD && !VD->isInternalLinkageFileVar()) {
2315 DiagnoseUnusedButSetDecl(VD, addDiag);
2316 RefsMinusAssignments.erase(VD->getCanonicalDecl());
2317 }
2318 }
2319
2320 if (!D->getDeclName()) continue;
2321
2322 // If this was a forward reference to a label, verify it was defined.
2323 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2324 CheckPoppedLabel(LD, *this, addDiag);
2325
2326 // Partial translation units that are created in incremental processing must
2327 // not clean up the IdResolver because PTUs should take into account the
2328 // declarations that came from previous PTUs.
2329 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2331 IdResolver.RemoveDecl(D);
2332
2333 // Warn on it if we are shadowing a declaration.
2334 auto ShadowI = ShadowingDecls.find(D);
2335 if (ShadowI != ShadowingDecls.end()) {
2336 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2337 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2338 PDiag(diag::warn_ctor_parm_shadows_field)
2339 << D << FD << FD->getParent());
2340 }
2341 ShadowingDecls.erase(ShadowI);
2342 }
2343 }
2344
2345 llvm::sort(DeclDiags,
2346 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2347 // The particular order for diagnostics is not important, as long
2348 // as the order is deterministic. Using the raw location is going
2349 // to generally be in source order unless there are macro
2350 // expansions involved.
2351 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2352 });
2353 for (const LocAndDiag &D : DeclDiags) {
2354 Diag(D.Loc, D.PD);
2355 if (D.PreviousDeclLoc)
2356 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2357 }
2358}
2359
2361 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2362 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2363 (S->isClassScope() && !getLangOpts().CPlusPlus))
2364 S = S->getParent();
2365 return S;
2366}
2367
2368static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2370 switch (Error) {
2372 return "";
2374 return BuiltinInfo.getHeaderName(ID);
2376 return "stdio.h";
2378 return "setjmp.h";
2380 return "ucontext.h";
2381 }
2382 llvm_unreachable("unhandled error kind");
2383}
2384
2386 unsigned ID, SourceLocation Loc) {
2387 DeclContext *Parent = Context.getTranslationUnitDecl();
2388
2389 if (getLangOpts().CPlusPlus) {
2391 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2392 CLinkageDecl->setImplicit();
2393 Parent->addDecl(CLinkageDecl);
2394 Parent = CLinkageDecl;
2395 }
2396
2398 if (Context.BuiltinInfo.isImmediate(ID)) {
2399 assert(getLangOpts().CPlusPlus20 &&
2400 "consteval builtins should only be available in C++20 mode");
2401 ConstexprKind = ConstexprSpecKind::Consteval;
2402 }
2403
2405 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2406 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2407 Type->isFunctionProtoType(), ConstexprKind);
2408 New->setImplicit();
2409 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2410
2411 // Create Decl objects for each parameter, adding them to the
2412 // FunctionDecl.
2413 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2415 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2417 Context, New, SourceLocation(), SourceLocation(), nullptr,
2418 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2419 parm->setScopeInfo(0, i);
2420 Params.push_back(parm);
2421 }
2422 New->setParams(Params);
2423 }
2424
2426 return New;
2427}
2428
2430 Scope *S, bool ForRedeclaration,
2431 SourceLocation Loc) {
2433
2435 QualType R = Context.GetBuiltinType(ID, Error);
2436 if (Error) {
2437 if (!ForRedeclaration)
2438 return nullptr;
2439
2440 // If we have a builtin without an associated type we should not emit a
2441 // warning when we were not able to find a type for it.
2443 Context.BuiltinInfo.allowTypeMismatch(ID))
2444 return nullptr;
2445
2446 // If we could not find a type for setjmp it is because the jmp_buf type was
2447 // not defined prior to the setjmp declaration.
2449 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2450 << Context.BuiltinInfo.getName(ID);
2451 return nullptr;
2452 }
2453
2454 // Generally, we emit a warning that the declaration requires the
2455 // appropriate header.
2456 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2457 << getHeaderName(Context.BuiltinInfo, ID, Error)
2458 << Context.BuiltinInfo.getName(ID);
2459 return nullptr;
2460 }
2461
2462 if (!ForRedeclaration &&
2463 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2464 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2465 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2466 : diag::ext_implicit_lib_function_decl)
2467 << Context.BuiltinInfo.getName(ID) << R;
2468 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2469 Diag(Loc, diag::note_include_header_or_declare)
2470 << Header << Context.BuiltinInfo.getName(ID);
2471 }
2472
2473 if (R.isNull())
2474 return nullptr;
2475
2476 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2478
2479 // TUScope is the translation-unit scope to insert this function into.
2480 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2481 // relate Scopes to DeclContexts, and probably eliminate CurContext
2482 // entirely, but we're not there yet.
2483 DeclContext *SavedContext = CurContext;
2484 CurContext = New->getDeclContext();
2486 CurContext = SavedContext;
2487 return New;
2488}
2489
2490/// Typedef declarations don't have linkage, but they still denote the same
2491/// entity if their types are the same.
2492/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2493/// isSameEntity.
2494static void
2497 // This is only interesting when modules are enabled.
2498 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2499 return;
2500
2501 // Empty sets are uninteresting.
2502 if (Previous.empty())
2503 return;
2504
2505 LookupResult::Filter Filter = Previous.makeFilter();
2506 while (Filter.hasNext()) {
2507 NamedDecl *Old = Filter.next();
2508
2509 // Non-hidden declarations are never ignored.
2510 if (S.isVisible(Old))
2511 continue;
2512
2513 // Declarations of the same entity are not ignored, even if they have
2514 // different linkages.
2515 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2516 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2517 Decl->getUnderlyingType()))
2518 continue;
2519
2520 // If both declarations give a tag declaration a typedef name for linkage
2521 // purposes, then they declare the same entity.
2522 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2523 Decl->getAnonDeclWithTypedefName())
2524 continue;
2525 }
2526
2527 Filter.erase();
2528 }
2529
2530 Filter.done();
2531}
2532
2534 QualType OldType;
2535 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2536 OldType = OldTypedef->getUnderlyingType();
2537 else
2538 OldType = Context.getTypeDeclType(Old);
2539 QualType NewType = New->getUnderlyingType();
2540
2541 if (NewType->isVariablyModifiedType()) {
2542 // Must not redefine a typedef with a variably-modified type.
2543 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2544 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2545 << Kind << NewType;
2546 if (Old->getLocation().isValid())
2547 notePreviousDefinition(Old, New->getLocation());
2548 New->setInvalidDecl();
2549 return true;
2550 }
2551
2552 if (OldType != NewType &&
2553 !OldType->isDependentType() &&
2554 !NewType->isDependentType() &&
2555 !Context.hasSameType(OldType, NewType)) {
2556 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2557 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2558 << Kind << NewType << OldType;
2559 if (Old->getLocation().isValid())
2560 notePreviousDefinition(Old, New->getLocation());
2561 New->setInvalidDecl();
2562 return true;
2563 }
2564 return false;
2565}
2566
2568 LookupResult &OldDecls) {
2569 // If the new decl is known invalid already, don't bother doing any
2570 // merging checks.
2571 if (New->isInvalidDecl()) return;
2572
2573 // Allow multiple definitions for ObjC built-in typedefs.
2574 // FIXME: Verify the underlying types are equivalent!
2575 if (getLangOpts().ObjC) {
2576 const IdentifierInfo *TypeID = New->getIdentifier();
2577 switch (TypeID->getLength()) {
2578 default: break;
2579 case 2:
2580 {
2581 if (!TypeID->isStr("id"))
2582 break;
2583 QualType T = New->getUnderlyingType();
2584 if (!T->isPointerType())
2585 break;
2586 if (!T->isVoidPointerType()) {
2588 if (!PT->isStructureType())
2589 break;
2590 }
2591 Context.setObjCIdRedefinitionType(T);
2592 // Install the built-in type for 'id', ignoring the current definition.
2593 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2594 Context.getObjCIdType());
2595 return;
2596 }
2597 case 5:
2598 if (!TypeID->isStr("Class"))
2599 break;
2600 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2601 // Install the built-in type for 'Class', ignoring the current definition.
2602 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2603 Context.getObjCClassType());
2604 return;
2605 case 3:
2606 if (!TypeID->isStr("SEL"))
2607 break;
2608 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2609 // Install the built-in type for 'SEL', ignoring the current definition.
2610 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2611 Context.getObjCSelType());
2612 return;
2613 }
2614 // Fall through - the typedef name was not a builtin type.
2615 }
2616
2617 // Verify the old decl was also a type.
2618 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2619 if (!Old) {
2620 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2621 << New->getDeclName();
2622
2623 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2624 if (OldD->getLocation().isValid())
2625 notePreviousDefinition(OldD, New->getLocation());
2626
2627 return New->setInvalidDecl();
2628 }
2629
2630 // If the old declaration is invalid, just give up here.
2631 if (Old->isInvalidDecl())
2632 return New->setInvalidDecl();
2633
2634 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2635 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2636 auto *NewTag = New->getAnonDeclWithTypedefName();
2637 NamedDecl *Hidden = nullptr;
2638 if (OldTag && NewTag &&
2639 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2640 !hasVisibleDefinition(OldTag, &Hidden)) {
2641 // There is a definition of this tag, but it is not visible. Use it
2642 // instead of our tag.
2643 if (OldTD->isModed())
2644 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2645 OldTD->getUnderlyingType());
2646 else
2647 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2648
2649 // Make the old tag definition visible.
2651
2653 }
2654 }
2655
2656 // If the typedef types are not identical, reject them in all languages and
2657 // with any extensions enabled.
2658 if (isIncompatibleTypedef(Old, New))
2659 return;
2660
2661 // The types match. Link up the redeclaration chain and merge attributes if
2662 // the old declaration was a typedef.
2663 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2664 New->setPreviousDecl(Typedef);
2666 }
2667
2668 if (getLangOpts().MicrosoftExt)
2669 return;
2670
2671 if (getLangOpts().CPlusPlus) {
2672 // C++ [dcl.typedef]p2:
2673 // In a given non-class scope, a typedef specifier can be used to
2674 // redefine the name of any type declared in that scope to refer
2675 // to the type to which it already refers.
2677 return;
2678
2679 // C++0x [dcl.typedef]p4:
2680 // In a given class scope, a typedef specifier can be used to redefine
2681 // any class-name declared in that scope that is not also a typedef-name
2682 // to refer to the type to which it already refers.
2683 //
2684 // This wording came in via DR424, which was a correction to the
2685 // wording in DR56, which accidentally banned code like:
2686 //
2687 // struct S {
2688 // typedef struct A { } A;
2689 // };
2690 //
2691 // in the C++03 standard. We implement the C++0x semantics, which
2692 // allow the above but disallow
2693 //
2694 // struct S {
2695 // typedef int I;
2696 // typedef int I;
2697 // };
2698 //
2699 // since that was the intent of DR56.
2700 if (!isa<TypedefNameDecl>(Old))
2701 return;
2702
2703 Diag(New->getLocation(), diag::err_redefinition)
2704 << New->getDeclName();
2705 notePreviousDefinition(Old, New->getLocation());
2706 return New->setInvalidDecl();
2707 }
2708
2709 // Modules always permit redefinition of typedefs, as does C11.
2710 if (getLangOpts().Modules || getLangOpts().C11)
2711 return;
2712
2713 // If we have a redefinition of a typedef in C, emit a warning. This warning
2714 // is normally mapped to an error, but can be controlled with
2715 // -Wtypedef-redefinition. If either the original or the redefinition is
2716 // in a system header, don't emit this for compatibility with GCC.
2717 if (getDiagnostics().getSuppressSystemWarnings() &&
2718 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2719 (Old->isImplicit() ||
2720 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2721 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2722 return;
2723
2724 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2725 << New->getDeclName();
2726 notePreviousDefinition(Old, New->getLocation());
2727}
2728
2730 // If this was an unscoped enumeration, yank all of its enumerators
2731 // out of the scope.
2732 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2733 Scope *EnumScope = getNonFieldDeclScope(S);
2734 for (auto *ECD : ED->enumerators()) {
2735 assert(EnumScope->isDeclScope(ECD));
2736 EnumScope->RemoveDecl(ECD);
2737 IdResolver.RemoveDecl(ECD);
2738 }
2739 }
2740}
2741
2742/// DeclhasAttr - returns true if decl Declaration already has the target
2743/// attribute.
2744static bool DeclHasAttr(const Decl *D, const Attr *A) {
2745 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2746 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2747 for (const auto *i : D->attrs())
2748 if (i->getKind() == A->getKind()) {
2749 if (Ann) {
2750 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2751 return true;
2752 continue;
2753 }
2754 // FIXME: Don't hardcode this check
2755 if (OA && isa<OwnershipAttr>(i))
2756 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2757 return true;
2758 }
2759
2760 return false;
2761}
2762
2764 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2765 return VD->isThisDeclarationADefinition();
2766 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2767 return TD->isCompleteDefinition() || TD->isBeingDefined();
2768 return true;
2769}
2770
2771/// Merge alignment attributes from \p Old to \p New, taking into account the
2772/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2773///
2774/// \return \c true if any attributes were added to \p New.
2775static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2776 // Look for alignas attributes on Old, and pick out whichever attribute
2777 // specifies the strictest alignment requirement.
2778 AlignedAttr *OldAlignasAttr = nullptr;
2779 AlignedAttr *OldStrictestAlignAttr = nullptr;
2780 unsigned OldAlign = 0;
2781 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2782 // FIXME: We have no way of representing inherited dependent alignments
2783 // in a case like:
2784 // template<int A, int B> struct alignas(A) X;
2785 // template<int A, int B> struct alignas(B) X {};
2786 // For now, we just ignore any alignas attributes which are not on the
2787 // definition in such a case.
2788 if (I->isAlignmentDependent())
2789 return false;
2790
2791 if (I->isAlignas())
2792 OldAlignasAttr = I;
2793
2794 unsigned Align = I->getAlignment(S.Context);
2795 if (Align > OldAlign) {
2796 OldAlign = Align;
2797 OldStrictestAlignAttr = I;
2798 }
2799 }
2800
2801 // Look for alignas attributes on New.
2802 AlignedAttr *NewAlignasAttr = nullptr;
2803 unsigned NewAlign = 0;
2804 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2805 if (I->isAlignmentDependent())
2806 return false;
2807
2808 if (I->isAlignas())
2809 NewAlignasAttr = I;
2810
2811 unsigned Align = I->getAlignment(S.Context);
2812 if (Align > NewAlign)
2813 NewAlign = Align;
2814 }
2815
2816 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2817 // Both declarations have 'alignas' attributes. We require them to match.
2818 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2819 // fall short. (If two declarations both have alignas, they must both match
2820 // every definition, and so must match each other if there is a definition.)
2821
2822 // If either declaration only contains 'alignas(0)' specifiers, then it
2823 // specifies the natural alignment for the type.
2824 if (OldAlign == 0 || NewAlign == 0) {
2825 QualType Ty;
2826 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2827 Ty = VD->getType();
2828 else
2830
2831 if (OldAlign == 0)
2832 OldAlign = S.Context.getTypeAlign(Ty);
2833 if (NewAlign == 0)
2834 NewAlign = S.Context.getTypeAlign(Ty);
2835 }
2836
2837 if (OldAlign != NewAlign) {
2838 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2841 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2842 }
2843 }
2844
2845 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2846 // C++11 [dcl.align]p6:
2847 // if any declaration of an entity has an alignment-specifier,
2848 // every defining declaration of that entity shall specify an
2849 // equivalent alignment.
2850 // C11 6.7.5/7:
2851 // If the definition of an object does not have an alignment
2852 // specifier, any other declaration of that object shall also
2853 // have no alignment specifier.
2854 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2855 << OldAlignasAttr;
2856 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2857 << OldAlignasAttr;
2858 }
2859
2860 bool AnyAdded = false;
2861
2862 // Ensure we have an attribute representing the strictest alignment.
2863 if (OldAlign > NewAlign) {
2864 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2865 Clone->setInherited(true);
2866 New->addAttr(Clone);
2867 AnyAdded = true;
2868 }
2869
2870 // Ensure we have an alignas attribute if the old declaration had one.
2871 if (OldAlignasAttr && !NewAlignasAttr &&
2872 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2873 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2874 Clone->setInherited(true);
2875 New->addAttr(Clone);
2876 AnyAdded = true;
2877 }
2878
2879 return AnyAdded;
2880}
2881
2882#define WANT_DECL_MERGE_LOGIC
2883#include "clang/Sema/AttrParsedAttrImpl.inc"
2884#undef WANT_DECL_MERGE_LOGIC
2885
2887 const InheritableAttr *Attr,
2889 // Diagnose any mutual exclusions between the attribute that we want to add
2890 // and attributes that already exist on the declaration.
2891 if (!DiagnoseMutualExclusions(S, D, Attr))
2892 return false;
2893
2894 // This function copies an attribute Attr from a previous declaration to the
2895 // new declaration D if the new declaration doesn't itself have that attribute
2896 // yet or if that attribute allows duplicates.
2897 // If you're adding a new attribute that requires logic different from
2898 // "use explicit attribute on decl if present, else use attribute from
2899 // previous decl", for example if the attribute needs to be consistent
2900 // between redeclarations, you need to call a custom merge function here.
2901 InheritableAttr *NewAttr = nullptr;
2902 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) {
2903 const IdentifierInfo *InferredPlatformII = nullptr;
2904 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2905 InferredPlatformII = Inf->getPlatform();
2907 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2908 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2909 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2910 AA->getPriority(), AA->getEnvironment(), InferredPlatformII);
2911 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2912 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2913 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2914 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2915 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2916 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2917 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2918 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2919 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2920 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2921 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2922 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2923 FA->getFirstArg());
2924 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2925 NewAttr = S.mergeFormatMatchesAttr(
2926 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2927 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2928 NewAttr = S.mergeModularFormatAttr(
2929 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2930 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2931 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2932 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2933 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2934 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2935 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2936 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2937 IA->getInheritanceModel());
2938 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2939 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2940 &S.Context.Idents.get(AA->getSpelling()));
2941 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2944 // CUDA target attributes are part of function signature for
2945 // overloading purposes and must not be merged.
2946 return false;
2947 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2948 NewAttr = S.mergeMinSizeAttr(D, *MA);
2949 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2950 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2951 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2952 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2953 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2954 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2955 else if (isa<AlignedAttr>(Attr))
2956 // AlignedAttrs are handled separately, because we need to handle all
2957 // such attributes on a declaration at the same time.
2958 NewAttr = nullptr;
2963 NewAttr = nullptr;
2964 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2965 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2966 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2967 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2968 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2969 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2970 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2971 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2972 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2973 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2974 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2975 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2976 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2977 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2978 NT->getZ());
2979 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2980 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2981 WS->getPreferred(),
2982 WS->getSpelledArgsCount());
2983 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
2984 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
2985 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2986 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2987 else if (isa<SuppressAttr>(Attr))
2988 // Do nothing. Each redeclaration should be suppressed separately.
2989 NewAttr = nullptr;
2990 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
2991 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
2992 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2993 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2994 else if (const auto *PA = dyn_cast<PersonalityAttr>(Attr))
2995 NewAttr = S.mergePersonalityAttr(D, PA->getRoutine(), *PA);
2996
2997 if (NewAttr) {
2998 NewAttr->setInherited(true);
2999 D->addAttr(NewAttr);
3000 if (isa<MSInheritanceAttr>(NewAttr))
3002 return true;
3003 }
3004
3005 return false;
3006}
3007
3008static const NamedDecl *getDefinition(const Decl *D) {
3009 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3010 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3011 return Def;
3012 return nullptr;
3013 }
3014 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3015 const VarDecl *Def = VD->getDefinition();
3016 if (Def)
3017 return Def;
3018 return VD->getActingDefinition();
3019 }
3020 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3021 const FunctionDecl *Def = nullptr;
3022 if (FD->isDefined(Def, true))
3023 return Def;
3024 }
3025 return nullptr;
3026}
3027
3028static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3029 for (const auto *Attribute : D->attrs())
3030 if (Attribute->getKind() == Kind)
3031 return true;
3032 return false;
3033}
3034
3035/// checkNewAttributesAfterDef - If we already have a definition, check that
3036/// there are no new attributes in this declaration.
3037static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3038 if (!New->hasAttrs())
3039 return;
3040
3041 const NamedDecl *Def = getDefinition(Old);
3042 if (!Def || Def == New)
3043 return;
3044
3045 AttrVec &NewAttributes = New->getAttrs();
3046 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3047 Attr *NewAttribute = NewAttributes[I];
3048
3049 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3050 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3051 SkipBodyInfo SkipBody;
3052 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3053
3054 // If we're skipping this definition, drop the "alias" attribute.
3055 if (SkipBody.ShouldSkip) {
3056 NewAttributes.erase(NewAttributes.begin() + I);
3057 --E;
3058 continue;
3059 }
3060 } else {
3061 VarDecl *VD = cast<VarDecl>(New);
3062 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3064 ? diag::err_alias_after_tentative
3065 : diag::err_redefinition;
3066 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3067 if (Diag == diag::err_redefinition)
3068 S.notePreviousDefinition(Def, VD->getLocation());
3069 else
3070 S.Diag(Def->getLocation(), diag::note_previous_definition);
3071 VD->setInvalidDecl();
3072 }
3073 ++I;
3074 continue;
3075 }
3076
3077 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3078 // Tentative definitions are only interesting for the alias check above.
3079 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3080 ++I;
3081 continue;
3082 }
3083 }
3084
3085 if (hasAttribute(Def, NewAttribute->getKind())) {
3086 ++I;
3087 continue; // regular attr merging will take care of validating this.
3088 }
3089
3090 if (isa<C11NoReturnAttr>(NewAttribute)) {
3091 // C's _Noreturn is allowed to be added to a function after it is defined.
3092 ++I;
3093 continue;
3094 } else if (isa<UuidAttr>(NewAttribute)) {
3095 // msvc will allow a subsequent definition to add an uuid to a class
3096 ++I;
3097 continue;
3099 NewAttribute) &&
3100 NewAttribute->isStandardAttributeSyntax()) {
3101 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3102 // deprecated attribute can later be re-declared with the attribute and
3103 // vice-versa.
3104 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3105 // maybe_unused attribute can later be redeclared with the attribute and
3106 // vice versa.
3107 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3108 // nodiscard attribute can later be redeclared with the attribute and
3109 // vice-versa.
3110 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3111 ++I;
3112 continue;
3113 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3114 if (AA->isAlignas()) {
3115 // C++11 [dcl.align]p6:
3116 // if any declaration of an entity has an alignment-specifier,
3117 // every defining declaration of that entity shall specify an
3118 // equivalent alignment.
3119 // C11 6.7.5/7:
3120 // If the definition of an object does not have an alignment
3121 // specifier, any other declaration of that object shall also
3122 // have no alignment specifier.
3123 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3124 << AA;
3125 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3126 << AA;
3127 NewAttributes.erase(NewAttributes.begin() + I);
3128 --E;
3129 continue;
3130 }
3131 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3132 // If there is a C definition followed by a redeclaration with this
3133 // attribute then there are two different definitions. In C++, prefer the
3134 // standard diagnostics.
3135 if (!S.getLangOpts().CPlusPlus) {
3136 S.Diag(NewAttribute->getLocation(),
3137 diag::err_loader_uninitialized_redeclaration);
3138 S.Diag(Def->getLocation(), diag::note_previous_definition);
3139 NewAttributes.erase(NewAttributes.begin() + I);
3140 --E;
3141 continue;
3142 }
3143 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3144 cast<VarDecl>(New)->isInline() &&
3145 !cast<VarDecl>(New)->isInlineSpecified()) {
3146 // Don't warn about applying selectany to implicitly inline variables.
3147 // Older compilers and language modes would require the use of selectany
3148 // to make such variables inline, and it would have no effect if we
3149 // honored it.
3150 ++I;
3151 continue;
3152 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3153 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3154 // declarations after definitions.
3155 ++I;
3156 continue;
3157 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3158 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3159 // error since the definition will have already been created without
3160 // the semantic effects of the attribute having been applied.
3161 S.Diag(NewAttribute->getLocation(),
3162 diag::err_sycl_entry_point_after_definition)
3163 << NewAttribute;
3164 S.Diag(Def->getLocation(), diag::note_previous_definition);
3165 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3166 ++I;
3167 continue;
3168 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3169 // SYCLExternalAttr may be added after a definition.
3170 ++I;
3171 continue;
3172 }
3173
3174 S.Diag(NewAttribute->getLocation(),
3175 diag::warn_attribute_precede_definition);
3176 S.Diag(Def->getLocation(), diag::note_previous_definition);
3177 NewAttributes.erase(NewAttributes.begin() + I);
3178 --E;
3179 }
3180}
3181
3182static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3183 const ConstInitAttr *CIAttr,
3184 bool AttrBeforeInit) {
3185 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3186
3187 // Figure out a good way to write this specifier on the old declaration.
3188 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3189 // enough of the attribute list spelling information to extract that without
3190 // heroics.
3191 std::string SuitableSpelling;
3192 if (S.getLangOpts().CPlusPlus20)
3193 SuitableSpelling = std::string(
3194 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3195 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3196 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3197 InsertLoc, {tok::l_square, tok::l_square,
3198 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3199 S.PP.getIdentifierInfo("require_constant_initialization"),
3200 tok::r_square, tok::r_square}));
3201 if (SuitableSpelling.empty())
3202 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3203 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3204 S.PP.getIdentifierInfo("require_constant_initialization"),
3205 tok::r_paren, tok::r_paren}));
3206 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3207 SuitableSpelling = "constinit";
3208 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3209 SuitableSpelling = "[[clang::require_constant_initialization]]";
3210 if (SuitableSpelling.empty())
3211 SuitableSpelling = "__attribute__((require_constant_initialization))";
3212 SuitableSpelling += " ";
3213
3214 if (AttrBeforeInit) {
3215 // extern constinit int a;
3216 // int a = 0; // error (missing 'constinit'), accepted as extension
3217 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3218 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3219 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3220 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3221 } else {
3222 // int a = 0;
3223 // constinit extern int a; // error (missing 'constinit')
3224 S.Diag(CIAttr->getLocation(),
3225 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3226 : diag::warn_require_const_init_added_too_late)
3227 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3228 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3229 << CIAttr->isConstinit()
3230 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3231 }
3232}
3233
3236 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3237 UsedAttr *NewAttr = OldAttr->clone(Context);
3238 NewAttr->setInherited(true);
3239 New->addAttr(NewAttr);
3240 }
3241 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3242 RetainAttr *NewAttr = OldAttr->clone(Context);
3243 NewAttr->setInherited(true);
3244 New->addAttr(NewAttr);
3245 }
3246
3247 if (!Old->hasAttrs() && !New->hasAttrs())
3248 return;
3249
3250 // [dcl.constinit]p1:
3251 // If the [constinit] specifier is applied to any declaration of a
3252 // variable, it shall be applied to the initializing declaration.
3253 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3254 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3255 if (bool(OldConstInit) != bool(NewConstInit)) {
3256 const auto *OldVD = cast<VarDecl>(Old);
3257 auto *NewVD = cast<VarDecl>(New);
3258
3259 // Find the initializing declaration. Note that we might not have linked
3260 // the new declaration into the redeclaration chain yet.
3261 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3262 if (!InitDecl &&
3263 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3264 InitDecl = NewVD;
3265
3266 if (InitDecl == NewVD) {
3267 // This is the initializing declaration. If it would inherit 'constinit',
3268 // that's ill-formed. (Note that we do not apply this to the attribute
3269 // form).
3270 if (OldConstInit && OldConstInit->isConstinit())
3271 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3272 /*AttrBeforeInit=*/true);
3273 } else if (NewConstInit) {
3274 // This is the first time we've been told that this declaration should
3275 // have a constant initializer. If we already saw the initializing
3276 // declaration, this is too late.
3277 if (InitDecl && InitDecl != NewVD) {
3278 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3279 /*AttrBeforeInit=*/false);
3280 NewVD->dropAttr<ConstInitAttr>();
3281 }
3282 }
3283 }
3284
3285 // Attributes declared post-definition are currently ignored.
3286 checkNewAttributesAfterDef(*this, New, Old);
3287
3288 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3289 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3290 if (!OldA->isEquivalent(NewA)) {
3291 // This redeclaration changes __asm__ label.
3292 Diag(New->getLocation(), diag::err_different_asm_label);
3293 Diag(OldA->getLocation(), diag::note_previous_declaration);
3294 }
3295 } else if (Old->isUsed()) {
3296 // This redeclaration adds an __asm__ label to a declaration that has
3297 // already been ODR-used.
3298 Diag(New->getLocation(), diag::err_late_asm_label_name)
3299 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3300 }
3301 }
3302
3303 // Re-declaration cannot add abi_tag's.
3304 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3305 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3306 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3307 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3308 Diag(NewAbiTagAttr->getLocation(),
3309 diag::err_new_abi_tag_on_redeclaration)
3310 << NewTag;
3311 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3312 }
3313 }
3314 } else {
3315 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3316 Diag(Old->getLocation(), diag::note_previous_declaration);
3317 }
3318 }
3319
3320 // This redeclaration adds a section attribute.
3321 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3322 if (auto *VD = dyn_cast<VarDecl>(New)) {
3323 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3324 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3325 Diag(Old->getLocation(), diag::note_previous_declaration);
3326 }
3327 }
3328 }
3329
3330 // Redeclaration adds code-seg attribute.
3331 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3332 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3333 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3334 Diag(New->getLocation(), diag::warn_mismatched_section)
3335 << 0 /*codeseg*/;
3336 Diag(Old->getLocation(), diag::note_previous_declaration);
3337 }
3338
3339 if (!Old->hasAttrs())
3340 return;
3341
3342 bool foundAny = New->hasAttrs();
3343
3344 // Ensure that any moving of objects within the allocated map is done before
3345 // we process them.
3346 if (!foundAny) New->setAttrs(AttrVec());
3347
3348 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3349 // Ignore deprecated/unavailable/availability attributes if requested.
3351 if (isa<DeprecatedAttr>(I) ||
3354 switch (AMK) {
3356 continue;
3357
3362 LocalAMK = AMK;
3363 break;
3364 }
3365 }
3366
3367 // Already handled.
3368 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3369 continue;
3370
3372 if (auto *FD = dyn_cast<FunctionDecl>(New);
3373 FD &&
3374 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3375 continue; // Don't propagate inferred noreturn attributes to explicit
3376 }
3377
3378 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3379 foundAny = true;
3380 }
3381
3382 if (mergeAlignedAttrs(*this, New, Old))
3383 foundAny = true;
3384
3385 if (!foundAny) New->dropAttrs();
3386}
3387
3389 for (const Attr *A : D->attrs())
3390 checkAttrIsTypeDependent(D, A);
3391}
3392
3393// Returns the number of added attributes.
3394template <class T>
3395static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3396 Sema &S) {
3397 unsigned found = 0;
3398 for (const auto *I : From->specific_attrs<T>()) {
3399 if (!DeclHasAttr(To, I)) {
3400 T *newAttr = cast<T>(I->clone(S.Context));
3401 newAttr->setInherited(true);
3402 To->addAttr(newAttr);
3403 ++found;
3404 }
3405 }
3406 return found;
3407}
3408
3409template <class F>
3410static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3411 F &&propagator) {
3412 if (!From->hasAttrs()) {
3413 return;
3414 }
3415
3416 bool foundAny = To->hasAttrs();
3417
3418 // Ensure that any moving of objects within the allocated map is
3419 // done before we process them.
3420 if (!foundAny)
3421 To->setAttrs(AttrVec());
3422
3423 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3424
3425 if (!foundAny)
3426 To->dropAttrs();
3427}
3428
3429/// mergeParamDeclAttributes - Copy attributes from the old parameter
3430/// to the new one.
3432 const ParmVarDecl *oldDecl,
3433 Sema &S) {
3434 // C++11 [dcl.attr.depend]p2:
3435 // The first declaration of a function shall specify the
3436 // carries_dependency attribute for its declarator-id if any declaration
3437 // of the function specifies the carries_dependency attribute.
3438 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3439 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3440 S.Diag(CDA->getLocation(),
3441 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3442 // Find the first declaration of the parameter.
3443 // FIXME: Should we build redeclaration chains for function parameters?
3444 const FunctionDecl *FirstFD =
3445 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3446 const ParmVarDecl *FirstVD =
3447 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3448 S.Diag(FirstVD->getLocation(),
3449 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3450 }
3451
3453 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3454 unsigned found = 0;
3455 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3456 // Propagate the lifetimebound attribute from parameters to the
3457 // most recent declaration. Note that this doesn't include the implicit
3458 // 'this' parameter, as the attribute is applied to the function type in
3459 // that case.
3460 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3461 return found;
3462 });
3463}
3464
3466 const ASTContext &Ctx) {
3467
3468 auto NoSizeInfo = [&Ctx](QualType Ty) {
3469 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3470 return true;
3471 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3472 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3473 return false;
3474 };
3475
3476 // `type[]` is equivalent to `type *` and `type[*]`.
3477 if (NoSizeInfo(Old) && NoSizeInfo(New))
3478 return true;
3479
3480 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3481 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3482 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3483 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3484 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3485 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3486 return false;
3487 return true;
3488 }
3489
3490 // Only compare size, ignore Size modifiers and CVR.
3491 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3492 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3494 }
3495
3496 // Don't try to compare dependent sized array
3497 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3498 return true;
3499 }
3500
3501 return Old == New;
3502}
3503
3504static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3505 const ParmVarDecl *OldParam,
3506 Sema &S) {
3507 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3508 if (auto Newnullability = NewParam->getType()->getNullability()) {
3509 if (*Oldnullability != *Newnullability) {
3510 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3512 *Newnullability,
3514 != 0))
3516 *Oldnullability,
3518 != 0));
3519 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3520 }
3521 } else {
3522 QualType NewT = NewParam->getType();
3523 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3524 NewParam->setType(NewT);
3525 }
3526 }
3527 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3528 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3529 if (OldParamDT && NewParamDT &&
3530 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3531 QualType OldParamOT = OldParamDT->getOriginalType();
3532 QualType NewParamOT = NewParamDT->getOriginalType();
3533 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3534 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3535 << NewParam << NewParamOT;
3536 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3537 << OldParamOT;
3538 }
3539 }
3540}
3541
3542namespace {
3543
3544/// Used in MergeFunctionDecl to keep track of function parameters in
3545/// C.
3546struct GNUCompatibleParamWarning {
3547 ParmVarDecl *OldParm;
3548 ParmVarDecl *NewParm;
3549 QualType PromotedType;
3550};
3551
3552} // end anonymous namespace
3553
3554// Determine whether the previous declaration was a definition, implicit
3555// declaration, or a declaration.
3556template <typename T>
3557static std::pair<diag::kind, SourceLocation>
3559 diag::kind PrevDiag;
3560 SourceLocation OldLocation = Old->getLocation();
3561 if (Old->isThisDeclarationADefinition())
3562 PrevDiag = diag::note_previous_definition;
3563 else if (Old->isImplicit()) {
3564 PrevDiag = diag::note_previous_implicit_declaration;
3565 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3566 if (FD->getBuiltinID())
3567 PrevDiag = diag::note_previous_builtin_declaration;
3568 }
3569 if (OldLocation.isInvalid())
3570 OldLocation = New->getLocation();
3571 } else
3572 PrevDiag = diag::note_previous_declaration;
3573 return std::make_pair(PrevDiag, OldLocation);
3574}
3575
3576/// canRedefineFunction - checks if a function can be redefined. Currently,
3577/// only extern inline functions can be redefined, and even then only in
3578/// GNU89 mode.
3579static bool canRedefineFunction(const FunctionDecl *FD,
3580 const LangOptions& LangOpts) {
3581 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3582 !LangOpts.CPlusPlus &&
3583 FD->isInlineSpecified() &&
3584 FD->getStorageClass() == SC_Extern);
3585}
3586
3587const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3588 const AttributedType *AT = T->getAs<AttributedType>();
3589 while (AT && !AT->isCallingConv())
3590 AT = AT->getModifiedType()->getAs<AttributedType>();
3591 return AT;
3592}
3593
3594template <typename T>
3595static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3596 const DeclContext *DC = Old->getDeclContext();
3597 if (DC->isRecord())
3598 return false;
3599
3600 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3601 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3602 return true;
3603 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3604 return true;
3605 return false;
3606}
3607
3608template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3609static bool isExternC(VarTemplateDecl *) { return false; }
3610static bool isExternC(FunctionTemplateDecl *) { return false; }
3611
3612/// Check whether a redeclaration of an entity introduced by a
3613/// using-declaration is valid, given that we know it's not an overload
3614/// (nor a hidden tag declaration).
3615template<typename ExpectedDecl>
3617 ExpectedDecl *New) {
3618 // C++11 [basic.scope.declarative]p4:
3619 // Given a set of declarations in a single declarative region, each of
3620 // which specifies the same unqualified name,
3621 // -- they shall all refer to the same entity, or all refer to functions
3622 // and function templates; or
3623 // -- exactly one declaration shall declare a class name or enumeration
3624 // name that is not a typedef name and the other declarations shall all
3625 // refer to the same variable or enumerator, or all refer to functions
3626 // and function templates; in this case the class name or enumeration
3627 // name is hidden (3.3.10).
3628
3629 // C++11 [namespace.udecl]p14:
3630 // If a function declaration in namespace scope or block scope has the
3631 // same name and the same parameter-type-list as a function introduced
3632 // by a using-declaration, and the declarations do not declare the same
3633 // function, the program is ill-formed.
3634
3635 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3636 if (Old &&
3637 !Old->getDeclContext()->getRedeclContext()->Equals(
3638 New->getDeclContext()->getRedeclContext()) &&
3639 !(isExternC(Old) && isExternC(New)))
3640 Old = nullptr;
3641
3642 if (!Old) {
3643 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3644 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3645 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3646 return true;
3647 }
3648 return false;
3649}
3650
3652 const FunctionDecl *B) {
3653 assert(A->getNumParams() == B->getNumParams());
3654
3655 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3656 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3657 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3658 if (AttrA == AttrB)
3659 return true;
3660 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3661 AttrA->isDynamic() == AttrB->isDynamic();
3662 };
3663
3664 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3665}
3666
3667/// If necessary, adjust the semantic declaration context for a qualified
3668/// declaration to name the correct inline namespace within the qualifier.
3670 DeclaratorDecl *OldD) {
3671 // The only case where we need to update the DeclContext is when
3672 // redeclaration lookup for a qualified name finds a declaration
3673 // in an inline namespace within the context named by the qualifier:
3674 //
3675 // inline namespace N { int f(); }
3676 // int ::f(); // Sema DC needs adjusting from :: to N::.
3677 //
3678 // For unqualified declarations, the semantic context *can* change
3679 // along the redeclaration chain (for local extern declarations,
3680 // extern "C" declarations, and friend declarations in particular).
3681 if (!NewD->getQualifier())
3682 return;
3683
3684 // NewD is probably already in the right context.
3685 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3686 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3687 if (NamedDC->Equals(SemaDC))
3688 return;
3689
3690 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3691 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3692 "unexpected context for redeclaration");
3693
3694 auto *LexDC = NewD->getLexicalDeclContext();
3695 auto FixSemaDC = [=](NamedDecl *D) {
3696 if (!D)
3697 return;
3698 D->setDeclContext(SemaDC);
3699 D->setLexicalDeclContext(LexDC);
3700 };
3701
3702 FixSemaDC(NewD);
3703 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3704 FixSemaDC(FD->getDescribedFunctionTemplate());
3705 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3706 FixSemaDC(VD->getDescribedVarTemplate());
3707}
3708
3710 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3711 // Verify the old decl was also a function.
3712 FunctionDecl *Old = OldD->getAsFunction();
3713 if (!Old) {
3714 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3715 // We don't need to check the using friend pattern from other module unit
3716 // since we should have diagnosed such cases in its unit already.
3717 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3718 Diag(New->getLocation(), diag::err_using_decl_friend);
3719 Diag(Shadow->getTargetDecl()->getLocation(),
3720 diag::note_using_decl_target);
3721 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3722 << 0;
3723 return true;
3724 }
3725
3726 // Check whether the two declarations might declare the same function or
3727 // function template.
3728 if (FunctionTemplateDecl *NewTemplate =
3729 New->getDescribedFunctionTemplate()) {
3731 NewTemplate))
3732 return true;
3733 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3734 ->getAsFunction();
3735 } else {
3736 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3737 return true;
3738 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3739 }
3740 } else {
3741 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3742 << New->getDeclName();
3743 notePreviousDefinition(OldD, New->getLocation());
3744 return true;
3745 }
3746 }
3747
3748 // If the old declaration was found in an inline namespace and the new
3749 // declaration was qualified, update the DeclContext to match.
3751
3752 // If the old declaration is invalid, just give up here.
3753 if (Old->isInvalidDecl())
3754 return true;
3755
3756 // Disallow redeclaration of some builtins.
3757 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3758 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3759 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3760 << Old << Old->getType();
3761 return true;
3762 }
3763
3764 diag::kind PrevDiag;
3765 SourceLocation OldLocation;
3766 std::tie(PrevDiag, OldLocation) =
3768
3769 // Don't complain about this if we're in GNU89 mode and the old function
3770 // is an extern inline function.
3771 // Don't complain about specializations. They are not supposed to have
3772 // storage classes.
3773 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3774 New->getStorageClass() == SC_Static &&
3775 Old->hasExternalFormalLinkage() &&
3776 !New->getTemplateSpecializationInfo() &&
3778 if (getLangOpts().MicrosoftExt) {
3779 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3780 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3781 } else {
3782 Diag(New->getLocation(), diag::err_static_non_static) << New;
3783 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3784 return true;
3785 }
3786 }
3787
3788 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3789 if (!Old->hasAttr<InternalLinkageAttr>()) {
3790 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3791 << ILA;
3792 Diag(Old->getLocation(), diag::note_previous_declaration);
3793 New->dropAttr<InternalLinkageAttr>();
3794 }
3795
3796 if (auto *EA = New->getAttr<ErrorAttr>()) {
3797 if (!Old->hasAttr<ErrorAttr>()) {
3798 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3799 Diag(Old->getLocation(), diag::note_previous_declaration);
3800 New->dropAttr<ErrorAttr>();
3801 }
3802 }
3803
3805 return true;
3806
3807 if (!getLangOpts().CPlusPlus) {
3808 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3809 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3810 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3811 << New << OldOvl;
3812
3813 // Try our best to find a decl that actually has the overloadable
3814 // attribute for the note. In most cases (e.g. programs with only one
3815 // broken declaration/definition), this won't matter.
3816 //
3817 // FIXME: We could do this if we juggled some extra state in
3818 // OverloadableAttr, rather than just removing it.
3819 const Decl *DiagOld = Old;
3820 if (OldOvl) {
3821 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3822 const auto *A = D->getAttr<OverloadableAttr>();
3823 return A && !A->isImplicit();
3824 });
3825 // If we've implicitly added *all* of the overloadable attrs to this
3826 // chain, emitting a "previous redecl" note is pointless.
3827 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3828 }
3829
3830 if (DiagOld)
3831 Diag(DiagOld->getLocation(),
3832 diag::note_attribute_overloadable_prev_overload)
3833 << OldOvl;
3834
3835 if (OldOvl)
3836 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3837 else
3838 New->dropAttr<OverloadableAttr>();
3839 }
3840 }
3841
3842 // It is not permitted to redeclare an SME function with different SME
3843 // attributes.
3844 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3845 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3846 << New->getType() << Old->getType();
3847 Diag(OldLocation, diag::note_previous_declaration);
3848 return true;
3849 }
3850
3851 // If a function is first declared with a calling convention, but is later
3852 // declared or defined without one, all following decls assume the calling
3853 // convention of the first.
3854 //
3855 // It's OK if a function is first declared without a calling convention,
3856 // but is later declared or defined with the default calling convention.
3857 //
3858 // To test if either decl has an explicit calling convention, we look for
3859 // AttributedType sugar nodes on the type as written. If they are missing or
3860 // were canonicalized away, we assume the calling convention was implicit.
3861 //
3862 // Note also that we DO NOT return at this point, because we still have
3863 // other tests to run.
3864 QualType OldQType = Context.getCanonicalType(Old->getType());
3865 QualType NewQType = Context.getCanonicalType(New->getType());
3866 const FunctionType *OldType = cast<FunctionType>(OldQType);
3867 const FunctionType *NewType = cast<FunctionType>(NewQType);
3868 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3869 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3870 bool RequiresAdjustment = false;
3871
3872 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3874 const FunctionType *FT =
3875 First->getType().getCanonicalType()->castAs<FunctionType>();
3877 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3878 if (!NewCCExplicit) {
3879 // Inherit the CC from the previous declaration if it was specified
3880 // there but not here.
3881 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3882 RequiresAdjustment = true;
3883 } else if (Old->getBuiltinID()) {
3884 // Builtin attribute isn't propagated to the new one yet at this point,
3885 // so we check if the old one is a builtin.
3886
3887 // Calling Conventions on a Builtin aren't really useful and setting a
3888 // default calling convention and cdecl'ing some builtin redeclarations is
3889 // common, so warn and ignore the calling convention on the redeclaration.
3890 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3891 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3893 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3894 RequiresAdjustment = true;
3895 } else {
3896 // Calling conventions aren't compatible, so complain.
3897 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3898 Diag(New->getLocation(), diag::err_cconv_change)
3899 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3900 << !FirstCCExplicit
3901 << (!FirstCCExplicit ? "" :
3903
3904 // Put the note on the first decl, since it is the one that matters.
3905 Diag(First->getLocation(), diag::note_previous_declaration);
3906 return true;
3907 }
3908 }
3909
3910 // FIXME: diagnose the other way around?
3911 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3912 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3913 RequiresAdjustment = true;
3914 }
3915
3916 // If the declaration is marked with cfi_unchecked_callee but the definition
3917 // isn't, the definition is also cfi_unchecked_callee.
3918 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3919 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3920 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3921 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3922
3923 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3924 EPI2.CFIUncheckedCallee = true;
3925 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3926 FPT2->getParamTypes(), EPI2);
3927 NewType = cast<FunctionType>(NewQType);
3928 New->setType(NewQType);
3929 }
3930 }
3931 }
3932
3933 // Merge regparm attribute.
3934 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3935 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3936 if (NewTypeInfo.getHasRegParm()) {
3937 Diag(New->getLocation(), diag::err_regparm_mismatch)
3938 << NewType->getRegParmType()
3939 << OldType->getRegParmType();
3940 Diag(OldLocation, diag::note_previous_declaration);
3941 return true;
3942 }
3943
3944 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3945 RequiresAdjustment = true;
3946 }
3947
3948 // Merge ns_returns_retained attribute.
3949 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3950 if (NewTypeInfo.getProducesResult()) {
3951 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3952 << "'ns_returns_retained'";
3953 Diag(OldLocation, diag::note_previous_declaration);
3954 return true;
3955 }
3956
3957 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3958 RequiresAdjustment = true;
3959 }
3960
3961 if (OldTypeInfo.getNoCallerSavedRegs() !=
3962 NewTypeInfo.getNoCallerSavedRegs()) {
3963 if (NewTypeInfo.getNoCallerSavedRegs()) {
3964 AnyX86NoCallerSavedRegistersAttr *Attr =
3965 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3966 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3967 Diag(OldLocation, diag::note_previous_declaration);
3968 return true;
3969 }
3970
3971 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3972 RequiresAdjustment = true;
3973 }
3974
3975 if (RequiresAdjustment) {
3976 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3977 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3978 New->setType(QualType(AdjustedType, 0));
3979 NewQType = Context.getCanonicalType(New->getType());
3980 }
3981
3982 // If this redeclaration makes the function inline, we may need to add it to
3983 // UndefinedButUsed.
3984 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3985 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
3986 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3987 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3988 SourceLocation()));
3989
3990 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3991 // about it.
3992 if (New->hasAttr<GNUInlineAttr>() &&
3993 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3994 UndefinedButUsed.erase(Old->getCanonicalDecl());
3995 }
3996
3997 // If pass_object_size params don't match up perfectly, this isn't a valid
3998 // redeclaration.
3999 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4001 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
4002 << New->getDeclName();
4003 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4004 return true;
4005 }
4006
4007 QualType OldQTypeForComparison = OldQType;
4008 if (Context.hasAnyFunctionEffects()) {
4009 const auto OldFX = Old->getFunctionEffects();
4010 const auto NewFX = New->getFunctionEffects();
4011 if (OldFX != NewFX) {
4012 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4013 for (const auto &Diff : Diffs) {
4014 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
4015 Diag(New->getLocation(),
4016 diag::warn_mismatched_func_effect_redeclaration)
4017 << Diff.effectName();
4018 Diag(Old->getLocation(), diag::note_previous_declaration);
4019 }
4020 }
4021 // Following a warning, we could skip merging effects from the previous
4022 // declaration, but that would trigger an additional "conflicting types"
4023 // error.
4024 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4026 FunctionEffectSet MergedFX =
4027 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4028 if (!MergeErrs.empty())
4029 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4030 Old->getLocation());
4031
4032 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4033 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4034 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4035 NewFPT->getParamTypes(), EPI);
4036
4037 New->setType(ModQT);
4038 NewQType = New->getType();
4039
4040 // Revise OldQTForComparison to include the merged effects,
4041 // so as not to fail due to differences later.
4042 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4043 EPI = OldFPT->getExtProtoInfo();
4044 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4045 OldQTypeForComparison = Context.getFunctionType(
4046 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4047 }
4048 if (OldFX.empty()) {
4049 // A redeclaration may add the attribute to a previously seen function
4050 // body which needs to be verified.
4051 maybeAddDeclWithEffects(Old, MergedFX);
4052 }
4053 }
4054 }
4055 }
4056
4057 if (getLangOpts().CPlusPlus) {
4058 OldQType = Context.getCanonicalType(Old->getType());
4059 NewQType = Context.getCanonicalType(New->getType());
4060
4061 // Go back to the type source info to compare the declared return types,
4062 // per C++1y [dcl.type.auto]p13:
4063 // Redeclarations or specializations of a function or function template
4064 // with a declared return type that uses a placeholder type shall also
4065 // use that placeholder, not a deduced type.
4066 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4067 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4068 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4069 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4070 OldDeclaredReturnType)) {
4071 QualType ResQT;
4072 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4073 OldDeclaredReturnType->isObjCObjectPointerType())
4074 // FIXME: This does the wrong thing for a deduced return type.
4075 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4076 if (ResQT.isNull()) {
4077 if (New->isCXXClassMember() && New->isOutOfLine())
4078 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4079 << New << New->getReturnTypeSourceRange();
4080 else if (Old->isExternC() && New->isExternC() &&
4081 !Old->hasAttr<OverloadableAttr>() &&
4082 !New->hasAttr<OverloadableAttr>())
4083 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4084 else
4085 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4086 << New->getReturnTypeSourceRange();
4087 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4088 << Old->getReturnTypeSourceRange();
4089 return true;
4090 }
4091 else
4092 NewQType = ResQT;
4093 }
4094
4095 QualType OldReturnType = OldType->getReturnType();
4096 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4097 if (OldReturnType != NewReturnType) {
4098 // If this function has a deduced return type and has already been
4099 // defined, copy the deduced value from the old declaration.
4100 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4101 if (OldAT && OldAT->isDeduced()) {
4102 QualType DT = OldAT->getDeducedType();
4103 if (DT.isNull()) {
4104 New->setType(SubstAutoTypeDependent(New->getType()));
4105 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4106 } else {
4107 New->setType(SubstAutoType(New->getType(), DT));
4108 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4109 }
4110 }
4111 }
4112
4113 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4114 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4115 if (OldMethod && NewMethod) {
4116 // Preserve triviality.
4117 NewMethod->setTrivial(OldMethod->isTrivial());
4118
4119 // MSVC allows explicit template specialization at class scope:
4120 // 2 CXXMethodDecls referring to the same function will be injected.
4121 // We don't want a redeclaration error.
4122 bool IsClassScopeExplicitSpecialization =
4123 OldMethod->isFunctionTemplateSpecialization() &&
4125 bool isFriend = NewMethod->getFriendObjectKind();
4126
4127 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4128 !IsClassScopeExplicitSpecialization) {
4129 // -- Member function declarations with the same name and the
4130 // same parameter types cannot be overloaded if any of them
4131 // is a static member function declaration.
4132 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4133 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4134 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4135 return true;
4136 }
4137
4138 // C++ [class.mem]p1:
4139 // [...] A member shall not be declared twice in the
4140 // member-specification, except that a nested class or member
4141 // class template can be declared and then later defined.
4142 if (!inTemplateInstantiation()) {
4143 unsigned NewDiag;
4144 if (isa<CXXConstructorDecl>(OldMethod))
4145 NewDiag = diag::err_constructor_redeclared;
4146 else if (isa<CXXDestructorDecl>(NewMethod))
4147 NewDiag = diag::err_destructor_redeclared;
4148 else if (isa<CXXConversionDecl>(NewMethod))
4149 NewDiag = diag::err_conv_function_redeclared;
4150 else
4151 NewDiag = diag::err_member_redeclared;
4152
4153 Diag(New->getLocation(), NewDiag);
4154 } else {
4155 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4156 << New << New->getType();
4157 }
4158 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4159 return true;
4160
4161 // Complain if this is an explicit declaration of a special
4162 // member that was initially declared implicitly.
4163 //
4164 // As an exception, it's okay to befriend such methods in order
4165 // to permit the implicit constructor/destructor/operator calls.
4166 } else if (OldMethod->isImplicit()) {
4167 if (isFriend) {
4168 NewMethod->setImplicit();
4169 } else {
4170 Diag(NewMethod->getLocation(),
4171 diag::err_definition_of_implicitly_declared_member)
4172 << New << getSpecialMember(OldMethod);
4173 return true;
4174 }
4175 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4176 Diag(NewMethod->getLocation(),
4177 diag::err_definition_of_explicitly_defaulted_member)
4178 << getSpecialMember(OldMethod);
4179 return true;
4180 }
4181 }
4182
4183 // C++1z [over.load]p2
4184 // Certain function declarations cannot be overloaded:
4185 // -- Function declarations that differ only in the return type,
4186 // the exception specification, or both cannot be overloaded.
4187
4188 // Check the exception specifications match. This may recompute the type of
4189 // both Old and New if it resolved exception specifications, so grab the
4190 // types again after this. Because this updates the type, we do this before
4191 // any of the other checks below, which may update the "de facto" NewQType
4192 // but do not necessarily update the type of New.
4194 return true;
4195
4196 // C++11 [dcl.attr.noreturn]p1:
4197 // The first declaration of a function shall specify the noreturn
4198 // attribute if any declaration of that function specifies the noreturn
4199 // attribute.
4200 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4201 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4202 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4203 << NRA;
4204 Diag(Old->getLocation(), diag::note_previous_declaration);
4205 }
4206
4207 // C++11 [dcl.attr.depend]p2:
4208 // The first declaration of a function shall specify the
4209 // carries_dependency attribute for its declarator-id if any declaration
4210 // of the function specifies the carries_dependency attribute.
4211 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4212 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4213 Diag(CDA->getLocation(),
4214 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4215 Diag(Old->getFirstDecl()->getLocation(),
4216 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4217 }
4218
4219 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4220 // When a function is declared with SYCL_EXTERNAL, that macro must be
4221 // used on the first declaration of that function in the translation unit.
4222 // Redeclarations of the function in the same translation unit may
4223 // optionally use SYCL_EXTERNAL, but this is not required.
4224 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4225 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4226 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4227 << SEA;
4228 Diag(Old->getLocation(), diag::note_previous_declaration);
4229 }
4230
4231 // (C++98 8.3.5p3):
4232 // All declarations for a function shall agree exactly in both the
4233 // return type and the parameter-type-list.
4234 // We also want to respect all the extended bits except noreturn.
4235
4236 // noreturn should now match unless the old type info didn't have it.
4237 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4238 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4239 const FunctionType *OldTypeForComparison
4240 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4241 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4242 assert(OldQTypeForComparison.isCanonical());
4243 }
4244
4246 // As a special case, retain the language linkage from previous
4247 // declarations of a friend function as an extension.
4248 //
4249 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4250 // and is useful because there's otherwise no way to specify language
4251 // linkage within class scope.
4252 //
4253 // Check cautiously as the friend object kind isn't yet complete.
4254 if (New->getFriendObjectKind() != Decl::FOK_None) {
4255 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4256 Diag(OldLocation, PrevDiag);
4257 } else {
4258 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4259 Diag(OldLocation, PrevDiag);
4260 return true;
4261 }
4262 }
4263
4264 // HLSL check parameters for matching ABI specifications.
4265 if (getLangOpts().HLSL) {
4266 if (HLSL().CheckCompatibleParameterABI(New, Old))
4267 return true;
4268
4269 // If no errors are generated when checking parameter ABIs we can check if
4270 // the two declarations have the same type ignoring the ABIs and if so,
4271 // the declarations can be merged. This case for merging is only valid in
4272 // HLSL because there are no valid cases of merging mismatched parameter
4273 // ABIs except the HLSL implicit in and explicit in.
4274 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4275 NewQType))
4276 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4277 // Fall through for conflicting redeclarations and redefinitions.
4278 }
4279
4280 // If the function types are compatible, merge the declarations. Ignore the
4281 // exception specifier because it was already checked above in
4282 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4283 // about incompatible types under -fms-compatibility.
4284 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4285 NewQType))
4286 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4287
4288 // If the types are imprecise (due to dependent constructs in friends or
4289 // local extern declarations), it's OK if they differ. We'll check again
4290 // during instantiation.
4291 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4292 return false;
4293
4294 // Fall through for conflicting redeclarations and redefinitions.
4295 }
4296
4297 // C: Function types need to be compatible, not identical. This handles
4298 // duplicate function decls like "void f(int); void f(enum X);" properly.
4299 if (!getLangOpts().CPlusPlus) {
4300 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4301 // type is specified by a function definition that contains a (possibly
4302 // empty) identifier list, both shall agree in the number of parameters
4303 // and the type of each parameter shall be compatible with the type that
4304 // results from the application of default argument promotions to the
4305 // type of the corresponding identifier. ...
4306 // This cannot be handled by ASTContext::typesAreCompatible() because that
4307 // doesn't know whether the function type is for a definition or not when
4308 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4309 // we need to cover here is that the number of arguments agree as the
4310 // default argument promotion rules were already checked by
4311 // ASTContext::typesAreCompatible().
4312 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4313 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4314 if (Old->hasInheritedPrototype())
4315 Old = Old->getCanonicalDecl();
4316 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4317 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4318 return true;
4319 }
4320
4321 // If we are merging two functions where only one of them has a prototype,
4322 // we may have enough information to decide to issue a diagnostic that the
4323 // function without a prototype will change behavior in C23. This handles
4324 // cases like:
4325 // void i(); void i(int j);
4326 // void i(int j); void i();
4327 // void i(); void i(int j) {}
4328 // See ActOnFinishFunctionBody() for other cases of the behavior change
4329 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4330 // type without a prototype.
4331 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4332 !New->isImplicit() && !Old->isImplicit()) {
4333 const FunctionDecl *WithProto, *WithoutProto;
4334 if (New->hasWrittenPrototype()) {
4335 WithProto = New;
4336 WithoutProto = Old;
4337 } else {
4338 WithProto = Old;
4339 WithoutProto = New;
4340 }
4341
4342 if (WithProto->getNumParams() != 0) {
4343 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4344 // The one without the prototype will be changing behavior in C23, so
4345 // warn about that one so long as it's a user-visible declaration.
4346 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4347 if (WithoutProto == New)
4348 IsWithoutProtoADef = NewDeclIsDefn;
4349 else
4350 IsWithProtoADef = NewDeclIsDefn;
4351 Diag(WithoutProto->getLocation(),
4352 diag::warn_non_prototype_changes_behavior)
4353 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4354 << (WithoutProto == Old) << IsWithProtoADef;
4355
4356 // The reason the one without the prototype will be changing behavior
4357 // is because of the one with the prototype, so note that so long as
4358 // it's a user-visible declaration. There is one exception to this:
4359 // when the new declaration is a definition without a prototype, the
4360 // old declaration with a prototype is not the cause of the issue,
4361 // and that does not need to be noted because the one with a
4362 // prototype will not change behavior in C23.
4363 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4364 !IsWithoutProtoADef)
4365 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4366 }
4367 }
4368 }
4369
4370 if (Context.typesAreCompatible(OldQType, NewQType)) {
4371 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4372 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4373 const FunctionProtoType *OldProto = nullptr;
4374 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4375 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4376 // The old declaration provided a function prototype, but the
4377 // new declaration does not. Merge in the prototype.
4378 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4379 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4380 OldProto->getParamTypes(),
4381 OldProto->getExtProtoInfo());
4382 New->setType(NewQType);
4383 New->setHasInheritedPrototype();
4384
4385 // Synthesize parameters with the same types.
4387 for (const auto &ParamType : OldProto->param_types()) {
4389 Context, New, SourceLocation(), SourceLocation(), nullptr,
4390 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4391 Param->setScopeInfo(0, Params.size());
4392 Param->setImplicit();
4393 Params.push_back(Param);
4394 }
4395
4396 New->setParams(Params);
4397 }
4398
4399 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4400 }
4401 }
4402
4403 // Check if the function types are compatible when pointer size address
4404 // spaces are ignored.
4405 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4406 return false;
4407
4408 // GNU C permits a K&R definition to follow a prototype declaration
4409 // if the declared types of the parameters in the K&R definition
4410 // match the types in the prototype declaration, even when the
4411 // promoted types of the parameters from the K&R definition differ
4412 // from the types in the prototype. GCC then keeps the types from
4413 // the prototype.
4414 //
4415 // If a variadic prototype is followed by a non-variadic K&R definition,
4416 // the K&R definition becomes variadic. This is sort of an edge case, but
4417 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4418 // C99 6.9.1p8.
4419 if (!getLangOpts().CPlusPlus &&
4420 Old->hasPrototype() && !New->hasPrototype() &&
4421 New->getType()->getAs<FunctionProtoType>() &&
4422 Old->getNumParams() == New->getNumParams()) {
4425 const FunctionProtoType *OldProto
4426 = Old->getType()->getAs<FunctionProtoType>();
4427 const FunctionProtoType *NewProto
4428 = New->getType()->getAs<FunctionProtoType>();
4429
4430 // Determine whether this is the GNU C extension.
4431 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4432 NewProto->getReturnType());
4433 bool LooseCompatible = !MergedReturn.isNull();
4434 for (unsigned Idx = 0, End = Old->getNumParams();
4435 LooseCompatible && Idx != End; ++Idx) {
4436 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4437 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4438 if (Context.typesAreCompatible(OldParm->getType(),
4439 NewProto->getParamType(Idx))) {
4440 ArgTypes.push_back(NewParm->getType());
4441 } else if (Context.typesAreCompatible(OldParm->getType(),
4442 NewParm->getType(),
4443 /*CompareUnqualified=*/true)) {
4444 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4445 NewProto->getParamType(Idx) };
4446 Warnings.push_back(Warn);
4447 ArgTypes.push_back(NewParm->getType());
4448 } else
4449 LooseCompatible = false;
4450 }
4451
4452 if (LooseCompatible) {
4453 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4454 Diag(Warnings[Warn].NewParm->getLocation(),
4455 diag::ext_param_promoted_not_compatible_with_prototype)
4456 << Warnings[Warn].PromotedType
4457 << Warnings[Warn].OldParm->getType();
4458 if (Warnings[Warn].OldParm->getLocation().isValid())
4459 Diag(Warnings[Warn].OldParm->getLocation(),
4460 diag::note_previous_declaration);
4461 }
4462
4463 if (MergeTypeWithOld)
4464 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4465 OldProto->getExtProtoInfo()));
4466 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4467 }
4468
4469 // Fall through to diagnose conflicting types.
4470 }
4471
4472 // A function that has already been declared has been redeclared or
4473 // defined with a different type; show an appropriate diagnostic.
4474
4475 // If the previous declaration was an implicitly-generated builtin
4476 // declaration, then at the very least we should use a specialized note.
4477 unsigned BuiltinID;
4478 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4479 // If it's actually a library-defined builtin function like 'malloc'
4480 // or 'printf', just warn about the incompatible redeclaration.
4481 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4482 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4483 Diag(OldLocation, diag::note_previous_builtin_declaration)
4484 << Old << Old->getType();
4485 return false;
4486 }
4487
4488 PrevDiag = diag::note_previous_builtin_declaration;
4489 }
4490
4491 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4492 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4493 return true;
4494}
4495
4497 Scope *S, bool MergeTypeWithOld) {
4498 // Merge the attributes
4500
4501 // Merge "pure" flag.
4502 if (Old->isPureVirtual())
4503 New->setIsPureVirtual();
4504
4505 // Merge "used" flag.
4506 if (Old->getMostRecentDecl()->isUsed(false))
4507 New->setIsUsed();
4508
4509 // Merge attributes from the parameters. These can mismatch with K&R
4510 // declarations.
4511 if (New->getNumParams() == Old->getNumParams())
4512 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4513 ParmVarDecl *NewParam = New->getParamDecl(i);
4514 ParmVarDecl *OldParam = Old->getParamDecl(i);
4515 mergeParamDeclAttributes(NewParam, OldParam, *this);
4516 mergeParamDeclTypes(NewParam, OldParam, *this);
4517 }
4518
4519 if (getLangOpts().CPlusPlus)
4520 return MergeCXXFunctionDecl(New, Old, S);
4521
4522 // Merge the function types so the we get the composite types for the return
4523 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4524 // was visible.
4525 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4526 if (!Merged.isNull() && MergeTypeWithOld)
4527 New->setType(Merged);
4528
4529 return false;
4530}
4531
4533 ObjCMethodDecl *oldMethod) {
4534 // Merge the attributes, including deprecated/unavailable
4535 AvailabilityMergeKind MergeKind =
4537 ? (oldMethod->isOptional()
4540 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4543
4544 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4545
4546 // Merge attributes from the parameters.
4548 oe = oldMethod->param_end();
4550 ni = newMethod->param_begin(), ne = newMethod->param_end();
4551 ni != ne && oi != oe; ++ni, ++oi)
4552 mergeParamDeclAttributes(*ni, *oi, *this);
4553
4554 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4555}
4556
4558 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4559
4560 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4561 ? diag::err_redefinition_different_type
4562 : diag::err_redeclaration_different_type)
4563 << New->getDeclName() << New->getType() << Old->getType();
4564
4565 diag::kind PrevDiag;
4566 SourceLocation OldLocation;
4567 std::tie(PrevDiag, OldLocation)
4569 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4570 New->setInvalidDecl();
4571}
4572
4574 bool MergeTypeWithOld) {
4575 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4576 return;
4577
4578 QualType MergedT;
4579 if (getLangOpts().CPlusPlus) {
4580 if (New->getType()->isUndeducedType()) {
4581 // We don't know what the new type is until the initializer is attached.
4582 return;
4583 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4584 // These could still be something that needs exception specs checked.
4585 return MergeVarDeclExceptionSpecs(New, Old);
4586 }
4587 // C++ [basic.link]p10:
4588 // [...] the types specified by all declarations referring to a given
4589 // object or function shall be identical, except that declarations for an
4590 // array object can specify array types that differ by the presence or
4591 // absence of a major array bound (8.3.4).
4592 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4593 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4594 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4595
4596 // We are merging a variable declaration New into Old. If it has an array
4597 // bound, and that bound differs from Old's bound, we should diagnose the
4598 // mismatch.
4599 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4600 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4601 PrevVD = PrevVD->getPreviousDecl()) {
4602 QualType PrevVDTy = PrevVD->getType();
4603 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4604 continue;
4605
4606 if (!Context.hasSameType(New->getType(), PrevVDTy))
4607 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4608 }
4609 }
4610
4611 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4612 if (Context.hasSameType(OldArray->getElementType(),
4613 NewArray->getElementType()))
4614 MergedT = New->getType();
4615 }
4616 // FIXME: Check visibility. New is hidden but has a complete type. If New
4617 // has no array bound, it should not inherit one from Old, if Old is not
4618 // visible.
4619 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4620 if (Context.hasSameType(OldArray->getElementType(),
4621 NewArray->getElementType()))
4622 MergedT = Old->getType();
4623 }
4624 }
4625 else if (New->getType()->isObjCObjectPointerType() &&
4626 Old->getType()->isObjCObjectPointerType()) {
4627 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4628 Old->getType());
4629 }
4630 } else {
4631 // C 6.2.7p2:
4632 // All declarations that refer to the same object or function shall have
4633 // compatible type.
4634 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4635 }
4636 if (MergedT.isNull()) {
4637 // It's OK if we couldn't merge types if either type is dependent, for a
4638 // block-scope variable. In other cases (static data members of class
4639 // templates, variable templates, ...), we require the types to be
4640 // equivalent.
4641 // FIXME: The C++ standard doesn't say anything about this.
4642 if ((New->getType()->isDependentType() ||
4643 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4644 // If the old type was dependent, we can't merge with it, so the new type
4645 // becomes dependent for now. We'll reproduce the original type when we
4646 // instantiate the TypeSourceInfo for the variable.
4647 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4648 New->setType(Context.DependentTy);
4649 return;
4650 }
4651 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4652 }
4653
4654 // Don't actually update the type on the new declaration if the old
4655 // declaration was an extern declaration in a different scope.
4656 if (MergeTypeWithOld)
4657 New->setType(MergedT);
4658}
4659
4660static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4662 // C11 6.2.7p4:
4663 // For an identifier with internal or external linkage declared
4664 // in a scope in which a prior declaration of that identifier is
4665 // visible, if the prior declaration specifies internal or
4666 // external linkage, the type of the identifier at the later
4667 // declaration becomes the composite type.
4668 //
4669 // If the variable isn't visible, we do not merge with its type.
4670 if (Previous.isShadowed())
4671 return false;
4672
4673 if (S.getLangOpts().CPlusPlus) {
4674 // C++11 [dcl.array]p3:
4675 // If there is a preceding declaration of the entity in the same
4676 // scope in which the bound was specified, an omitted array bound
4677 // is taken to be the same as in that earlier declaration.
4678 return NewVD->isPreviousDeclInSameBlockScope() ||
4679 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4681 } else {
4682 // If the old declaration was function-local, don't merge with its
4683 // type unless we're in the same function.
4684 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4685 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4686 }
4687}
4688
4690 // If the new decl is already invalid, don't do any other checking.
4691 if (New->isInvalidDecl())
4692 return;
4693
4694 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4695 return;
4696
4697 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4698
4699 // Verify the old decl was also a variable or variable template.
4700 VarDecl *Old = nullptr;
4701 VarTemplateDecl *OldTemplate = nullptr;
4702 if (Previous.isSingleResult()) {
4703 if (NewTemplate) {
4704 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4705 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4706
4707 if (auto *Shadow =
4708 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4709 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4710 return New->setInvalidDecl();
4711 } else {
4712 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4713
4714 if (auto *Shadow =
4715 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4716 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4717 return New->setInvalidDecl();
4718 }
4719 }
4720 if (!Old) {
4721 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4722 << New->getDeclName();
4723 notePreviousDefinition(Previous.getRepresentativeDecl(),
4724 New->getLocation());
4725 return New->setInvalidDecl();
4726 }
4727
4728 // If the old declaration was found in an inline namespace and the new
4729 // declaration was qualified, update the DeclContext to match.
4731
4732 // Ensure the template parameters are compatible.
4733 if (NewTemplate &&
4735 OldTemplate->getTemplateParameters(),
4736 /*Complain=*/true, TPL_TemplateMatch))
4737 return New->setInvalidDecl();
4738
4739 // C++ [class.mem]p1:
4740 // A member shall not be declared twice in the member-specification [...]
4741 //
4742 // Here, we need only consider static data members.
4743 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4744 Diag(New->getLocation(), diag::err_duplicate_member)
4745 << New->getIdentifier();
4746 Diag(Old->getLocation(), diag::note_previous_declaration);
4747 New->setInvalidDecl();
4748 }
4749
4751 // Warn if an already-defined variable is made a weak_import in a subsequent
4752 // declaration
4753 if (New->hasAttr<WeakImportAttr>())
4754 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4755 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4756 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4757 Diag(D->getLocation(), diag::note_previous_definition);
4758 // Remove weak_import attribute on new declaration.
4759 New->dropAttr<WeakImportAttr>();
4760 break;
4761 }
4762 }
4763
4764 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4765 if (!Old->hasAttr<InternalLinkageAttr>()) {
4766 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4767 << ILA;
4768 Diag(Old->getLocation(), diag::note_previous_declaration);
4769 New->dropAttr<InternalLinkageAttr>();
4770 }
4771
4772 // Merge the types.
4773 VarDecl *MostRecent = Old->getMostRecentDecl();
4774 if (MostRecent != Old) {
4775 MergeVarDeclTypes(New, MostRecent,
4776 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4777 if (New->isInvalidDecl())
4778 return;
4779 }
4780
4782 if (New->isInvalidDecl())
4783 return;
4784
4785 diag::kind PrevDiag;
4786 SourceLocation OldLocation;
4787 std::tie(PrevDiag, OldLocation) =
4789
4790 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4791 if (New->getStorageClass() == SC_Static &&
4792 !New->isStaticDataMember() &&
4793 Old->hasExternalFormalLinkage()) {
4794 if (getLangOpts().MicrosoftExt) {
4795 Diag(New->getLocation(), diag::ext_static_non_static)
4796 << New->getDeclName();
4797 Diag(OldLocation, PrevDiag);
4798 } else {
4799 Diag(New->getLocation(), diag::err_static_non_static)
4800 << New->getDeclName();
4801 Diag(OldLocation, PrevDiag);
4802 return New->setInvalidDecl();
4803 }
4804 }
4805 // C99 6.2.2p4:
4806 // For an identifier declared with the storage-class specifier
4807 // extern in a scope in which a prior declaration of that
4808 // identifier is visible,23) if the prior declaration specifies
4809 // internal or external linkage, the linkage of the identifier at
4810 // the later declaration is the same as the linkage specified at
4811 // the prior declaration. If no prior declaration is visible, or
4812 // if the prior declaration specifies no linkage, then the
4813 // identifier has external linkage.
4814 if (New->hasExternalStorage() && Old->hasLinkage())
4815 /* Okay */;
4816 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4817 !New->isStaticDataMember() &&
4819 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4820 Diag(OldLocation, PrevDiag);
4821 return New->setInvalidDecl();
4822 }
4823
4824 // Check if extern is followed by non-extern and vice-versa.
4825 if (New->hasExternalStorage() &&
4826 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4827 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4828 Diag(OldLocation, PrevDiag);
4829 return New->setInvalidDecl();
4830 }
4831 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4832 !New->hasExternalStorage()) {
4833 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4834 Diag(OldLocation, PrevDiag);
4835 return New->setInvalidDecl();
4836 }
4837
4839 return;
4840
4841 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4842
4843 // FIXME: The test for external storage here seems wrong? We still
4844 // need to check for mismatches.
4845 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4846 // Don't complain about out-of-line definitions of static members.
4847 !(Old->getLexicalDeclContext()->isRecord() &&
4848 !New->getLexicalDeclContext()->isRecord())) {
4849 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4850 Diag(OldLocation, PrevDiag);
4851 return New->setInvalidDecl();
4852 }
4853
4854 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4855 if (VarDecl *Def = Old->getDefinition()) {
4856 // C++1z [dcl.fcn.spec]p4:
4857 // If the definition of a variable appears in a translation unit before
4858 // its first declaration as inline, the program is ill-formed.
4859 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4860 Diag(Def->getLocation(), diag::note_previous_definition);
4861 }
4862 }
4863
4864 // If this redeclaration makes the variable inline, we may need to add it to
4865 // UndefinedButUsed.
4866 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4867 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4868 !Old->isInAnotherModuleUnit())
4869 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4870 SourceLocation()));
4871
4872 if (New->getTLSKind() != Old->getTLSKind()) {
4873 if (!Old->getTLSKind()) {
4874 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4875 Diag(OldLocation, PrevDiag);
4876 } else if (!New->getTLSKind()) {
4877 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4878 Diag(OldLocation, PrevDiag);
4879 } else {
4880 // Do not allow redeclaration to change the variable between requiring
4881 // static and dynamic initialization.
4882 // FIXME: GCC allows this, but uses the TLS keyword on the first
4883 // declaration to determine the kind. Do we need to be compatible here?
4884 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4885 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4886 Diag(OldLocation, PrevDiag);
4887 }
4888 }
4889
4890 // C++ doesn't have tentative definitions, so go right ahead and check here.
4891 if (getLangOpts().CPlusPlus) {
4892 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4893 Old->getCanonicalDecl()->isConstexpr()) {
4894 // This definition won't be a definition any more once it's been merged.
4895 Diag(New->getLocation(),
4896 diag::warn_deprecated_redundant_constexpr_static_def);
4897 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4898 VarDecl *Def = Old->getDefinition();
4899 if (Def && checkVarDeclRedefinition(Def, New))
4900 return;
4901 }
4902 } else {
4903 // C++ may not have a tentative definition rule, but it has a different
4904 // rule about what constitutes a definition in the first place. See
4905 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4906 // contains the extern specifier and doesn't have an initializer, it's fine
4907 // in C++.
4908 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4909 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4910 << New;
4911 Diag(Old->getLocation(), diag::note_previous_declaration);
4912 }
4913 }
4914
4916 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4917 Diag(OldLocation, PrevDiag);
4918 New->setInvalidDecl();
4919 return;
4920 }
4921
4922 // Merge "used" flag.
4923 if (Old->getMostRecentDecl()->isUsed(false))
4924 New->setIsUsed();
4925
4926 // Keep a chain of previous declarations.
4927 New->setPreviousDecl(Old);
4928 if (NewTemplate)
4929 NewTemplate->setPreviousDecl(OldTemplate);
4930
4931 // Inherit access appropriately.
4932 New->setAccess(Old->getAccess());
4933 if (NewTemplate)
4934 NewTemplate->setAccess(New->getAccess());
4935
4936 if (Old->isInline())
4937 New->setImplicitlyInline();
4938}
4939
4942 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4943 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4944 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4945 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4946 auto &HSI = PP.getHeaderSearchInfo();
4947 StringRef HdrFilename =
4948 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4949
4950 auto noteFromModuleOrInclude = [&](Module *Mod,
4951 SourceLocation IncLoc) -> bool {
4952 // Redefinition errors with modules are common with non modular mapped
4953 // headers, example: a non-modular header H in module A that also gets
4954 // included directly in a TU. Pointing twice to the same header/definition
4955 // is confusing, try to get better diagnostics when modules is on.
4956 if (IncLoc.isValid()) {
4957 if (Mod) {
4958 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4959 << HdrFilename.str() << Mod->getFullModuleName();
4960 if (!Mod->DefinitionLoc.isInvalid())
4961 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4962 << Mod->getFullModuleName();
4963 } else {
4964 Diag(IncLoc, diag::note_redefinition_include_same_file)
4965 << HdrFilename.str();
4966 }
4967 return true;
4968 }
4969
4970 return false;
4971 };
4972
4973 // Is it the same file and same offset? Provide more information on why
4974 // this leads to a redefinition error.
4975 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4976 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4977 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4978 bool EmittedDiag =
4979 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4980 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4981
4982 // If the header has no guards, emit a note suggesting one.
4983 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4984 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4985
4986 if (EmittedDiag)
4987 return;
4988 }
4989
4990 // Redefinition coming from different files or couldn't do better above.
4991 if (Old->getLocation().isValid())
4992 Diag(Old->getLocation(), diag::note_previous_definition);
4993}
4994
4996 if (!hasVisibleDefinition(Old) &&
4997 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4999 New->getDescribedVarTemplate() ||
5000 !New->getTemplateParameterLists().empty() ||
5001 New->getDeclContext()->isDependentContext() ||
5002 New->hasAttr<SelectAnyAttr>())) {
5003 // The previous definition is hidden, and multiple definitions are
5004 // permitted (in separate TUs). Demote this to a declaration.
5005 New->demoteThisDefinitionToDeclaration();
5006
5007 // Make the canonical definition visible.
5008 if (auto *OldTD = Old->getDescribedVarTemplate())
5011 return false;
5012 } else {
5013 Diag(New->getLocation(), diag::err_redefinition) << New;
5014 notePreviousDefinition(Old, New->getLocation());
5015 New->setInvalidDecl();
5016 return true;
5017 }
5018}
5019
5021 DeclSpec &DS,
5022 const ParsedAttributesView &DeclAttrs,
5023 RecordDecl *&AnonRecord) {
5025 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5026}
5027
5028// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5029// disambiguate entities defined in different scopes.
5030// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5031// compatibility.
5032// We will pick our mangling number depending on which version of MSVC is being
5033// targeted.
5034static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5038}
5039
5040void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5041 if (!Context.getLangOpts().CPlusPlus)
5042 return;
5043
5044 if (isa<CXXRecordDecl>(Tag->getParent())) {
5045 // If this tag is the direct child of a class, number it if
5046 // it is anonymous.
5047 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5048 return;
5050 Context.getManglingNumberContext(Tag->getParent());
5051 Context.setManglingNumber(
5052 Tag, MCtx.getManglingNumber(
5053 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5054 return;
5055 }
5056
5057 // If this tag isn't a direct child of a class, number it if it is local.
5059 Decl *ManglingContextDecl;
5060 std::tie(MCtx, ManglingContextDecl) =
5061 getCurrentMangleNumberContext(Tag->getDeclContext());
5062 if (MCtx) {
5063 Context.setManglingNumber(
5064 Tag, MCtx->getManglingNumber(
5065 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5066 }
5067}
5068
5069namespace {
5070struct NonCLikeKind {
5071 enum {
5072 None,
5073 BaseClass,
5074 DefaultMemberInit,
5075 Lambda,
5076 Friend,
5077 OtherMember,
5078 Invalid,
5079 } Kind = None;
5080 SourceRange Range;
5081
5082 explicit operator bool() { return Kind != None; }
5083};
5084}
5085
5086/// Determine whether a class is C-like, according to the rules of C++
5087/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5088static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5089 if (RD->isInvalidDecl())
5090 return {NonCLikeKind::Invalid, {}};
5091
5092 // C++ [dcl.typedef]p9: [P1766R1]
5093 // An unnamed class with a typedef name for linkage purposes shall not
5094 //
5095 // -- have any base classes
5096 if (RD->getNumBases())
5097 return {NonCLikeKind::BaseClass,
5099 RD->bases_end()[-1].getEndLoc())};
5100 bool Invalid = false;
5101 for (Decl *D : RD->decls()) {
5102 // Don't complain about things we already diagnosed.
5103 if (D->isInvalidDecl()) {
5104 Invalid = true;
5105 continue;
5106 }
5107
5108 // -- have any [...] default member initializers
5109 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5110 if (FD->hasInClassInitializer()) {
5111 auto *Init = FD->getInClassInitializer();
5112 return {NonCLikeKind::DefaultMemberInit,
5113 Init ? Init->getSourceRange() : D->getSourceRange()};
5114 }
5115 continue;
5116 }
5117
5118 // FIXME: We don't allow friend declarations. This violates the wording of
5119 // P1766, but not the intent.
5120 if (isa<FriendDecl>(D))
5121 return {NonCLikeKind::Friend, D->getSourceRange()};
5122
5123 // -- declare any members other than non-static data members, member
5124 // enumerations, or member classes,
5126 isa<EnumDecl>(D))
5127 continue;
5128 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5129 if (!MemberRD) {
5130 if (D->isImplicit())
5131 continue;
5132 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5133 }
5134
5135 // -- contain a lambda-expression,
5136 if (MemberRD->isLambda())
5137 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5138
5139 // and all member classes shall also satisfy these requirements
5140 // (recursively).
5141 if (MemberRD->isThisDeclarationADefinition()) {
5142 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5143 return Kind;
5144 }
5145 }
5146
5147 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5148}
5149
5151 TypedefNameDecl *NewTD) {
5152 if (TagFromDeclSpec->isInvalidDecl())
5153 return;
5154
5155 // Do nothing if the tag already has a name for linkage purposes.
5156 if (TagFromDeclSpec->hasNameForLinkage())
5157 return;
5158
5159 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5160 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5161
5162 // The type must match the tag exactly; no qualifiers allowed.
5163 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5164 Context.getCanonicalTagType(TagFromDeclSpec))) {
5165 if (getLangOpts().CPlusPlus)
5166 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5167 return;
5168 }
5169
5170 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5171 // An unnamed class with a typedef name for linkage purposes shall [be
5172 // C-like].
5173 //
5174 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5175 // shouldn't happen, but there are constructs that the language rule doesn't
5176 // disallow for which we can't reasonably avoid computing linkage early.
5177 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5178 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5179 : NonCLikeKind();
5180 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5181 if (NonCLike || ChangesLinkage) {
5182 if (NonCLike.Kind == NonCLikeKind::Invalid)
5183 return;
5184
5185 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5186 if (ChangesLinkage) {
5187 // If the linkage changes, we can't accept this as an extension.
5188 if (NonCLike.Kind == NonCLikeKind::None)
5189 DiagID = diag::err_typedef_changes_linkage;
5190 else
5191 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5192 }
5193
5194 SourceLocation FixitLoc =
5195 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5196 llvm::SmallString<40> TextToInsert;
5197 TextToInsert += ' ';
5198 TextToInsert += NewTD->getIdentifier()->getName();
5199
5200 Diag(FixitLoc, DiagID)
5201 << isa<TypeAliasDecl>(NewTD)
5202 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5203 if (NonCLike.Kind != NonCLikeKind::None) {
5204 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5205 << NonCLike.Kind - 1 << NonCLike.Range;
5206 }
5207 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5208 << NewTD << isa<TypeAliasDecl>(NewTD);
5209
5210 if (ChangesLinkage)
5211 return;
5212 }
5213
5214 // Otherwise, set this as the anon-decl typedef for the tag.
5215 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5216
5217 // Now that we have a name for the tag, process API notes again.
5218 ProcessAPINotes(TagFromDeclSpec);
5219}
5220
5221static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5223 switch (T) {
5225 return 0;
5227 return 1;
5229 return 2;
5231 return 3;
5232 case DeclSpec::TST_enum:
5233 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5234 if (ED->isScopedUsingClassTag())
5235 return 5;
5236 if (ED->isScoped())
5237 return 6;
5238 }
5239 return 4;
5240 default:
5241 llvm_unreachable("unexpected type specifier");
5242 }
5243}
5244
5246 DeclSpec &DS,
5247 const ParsedAttributesView &DeclAttrs,
5248 MultiTemplateParamsArg TemplateParams,
5249 bool IsExplicitInstantiation,
5250 RecordDecl *&AnonRecord,
5251 SourceLocation EllipsisLoc) {
5252 Decl *TagD = nullptr;
5253 TagDecl *Tag = nullptr;
5259 TagD = DS.getRepAsDecl();
5260
5261 if (!TagD) // We probably had an error
5262 return nullptr;
5263
5264 // Note that the above type specs guarantee that the
5265 // type rep is a Decl, whereas in many of the others
5266 // it's a Type.
5267 if (isa<TagDecl>(TagD))
5268 Tag = cast<TagDecl>(TagD);
5269 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5270 Tag = CTD->getTemplatedDecl();
5271 }
5272
5273 if (Tag) {
5274 handleTagNumbering(Tag, S);
5275 Tag->setFreeStanding();
5276 if (Tag->isInvalidDecl())
5277 return Tag;
5278 }
5279
5280 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5281 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5282 // or incomplete types shall not be restrict-qualified."
5283 if (TypeQuals & DeclSpec::TQ_restrict)
5285 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5286 << DS.getSourceRange();
5287 }
5288
5289 if (DS.isInlineSpecified())
5290 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5291 << getLangOpts().CPlusPlus17;
5292
5293 if (DS.hasConstexprSpecifier()) {
5294 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5295 // and definitions of functions and variables.
5296 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5297 // the declaration of a function or function template
5298 if (Tag)
5299 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5301 << static_cast<int>(DS.getConstexprSpecifier());
5302 else if (getLangOpts().C23)
5303 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5304 else
5305 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5306 << static_cast<int>(DS.getConstexprSpecifier());
5307 // Don't emit warnings after this error.
5308 return TagD;
5309 }
5310
5312
5313 if (DS.isFriendSpecified()) {
5314 // If we're dealing with a decl but not a TagDecl, assume that
5315 // whatever routines created it handled the friendship aspect.
5316 if (TagD && !Tag)
5317 return nullptr;
5318 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5319 }
5320
5321 assert(EllipsisLoc.isInvalid() &&
5322 "Friend ellipsis but not friend-specified?");
5323
5324 // Track whether this decl-specifier declares anything.
5325 bool DeclaresAnything = true;
5326
5327 // Handle anonymous struct definitions.
5328 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5329 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5331 if (getLangOpts().CPlusPlus ||
5332 Record->getDeclContext()->isRecord()) {
5333 // If CurContext is a DeclContext that can contain statements,
5334 // RecursiveASTVisitor won't visit the decls that
5335 // BuildAnonymousStructOrUnion() will put into CurContext.
5336 // Also store them here so that they can be part of the
5337 // DeclStmt that gets created in this case.
5338 // FIXME: Also return the IndirectFieldDecls created by
5339 // BuildAnonymousStructOr union, for the same reason?
5340 if (CurContext->isFunctionOrMethod())
5341 AnonRecord = Record;
5342 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5343 Context.getPrintingPolicy());
5344 }
5345
5346 DeclaresAnything = false;
5347 }
5348 }
5349
5350 // C11 6.7.2.1p2:
5351 // A struct-declaration that does not declare an anonymous structure or
5352 // anonymous union shall contain a struct-declarator-list.
5353 //
5354 // This rule also existed in C89 and C99; the grammar for struct-declaration
5355 // did not permit a struct-declaration without a struct-declarator-list.
5356 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5358 // Check for Microsoft C extension: anonymous struct/union member.
5359 // Handle 2 kinds of anonymous struct/union:
5360 // struct STRUCT;
5361 // union UNION;
5362 // and
5363 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5364 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5365 if ((Tag && Tag->getDeclName()) ||
5367 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5368 : DS.getRepAsType().get()->getAsRecordDecl();
5369 if (Record && getLangOpts().MSAnonymousStructs) {
5370 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5371 << Record->isUnion() << DS.getSourceRange();
5373 }
5374
5375 DeclaresAnything = false;
5376 }
5377 }
5378
5379 // Skip all the checks below if we have a type error.
5381 (TagD && TagD->isInvalidDecl()))
5382 return TagD;
5383
5384 if (getLangOpts().CPlusPlus &&
5386 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5387 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5388 !Enum->isInvalidDecl())
5389 DeclaresAnything = false;
5390
5391 if (!DS.isMissingDeclaratorOk()) {
5392 // Customize diagnostic for a typedef missing a name.
5394 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5395 << DS.getSourceRange();
5396 else
5397 DeclaresAnything = false;
5398 }
5399
5400 if (DS.isModulePrivateSpecified() &&
5401 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5402 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5403 << Tag->getTagKind()
5405
5407
5408 // C 6.7/2:
5409 // A declaration [...] shall declare at least a declarator [...], a tag,
5410 // or the members of an enumeration.
5411 // C++ [dcl.dcl]p3:
5412 // [If there are no declarators], and except for the declaration of an
5413 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5414 // names into the program, or shall redeclare a name introduced by a
5415 // previous declaration.
5416 if (!DeclaresAnything) {
5417 // In C, we allow this as a (popular) extension / bug. Don't bother
5418 // producing further diagnostics for redundant qualifiers after this.
5419 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5420 ? diag::err_no_declarators
5421 : diag::ext_no_declarators)
5422 << DS.getSourceRange();
5423 return TagD;
5424 }
5425
5426 // C++ [dcl.stc]p1:
5427 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5428 // init-declarator-list of the declaration shall not be empty.
5429 // C++ [dcl.fct.spec]p1:
5430 // If a cv-qualifier appears in a decl-specifier-seq, the
5431 // init-declarator-list of the declaration shall not be empty.
5432 //
5433 // Spurious qualifiers here appear to be valid in C.
5434 unsigned DiagID = diag::warn_standalone_specifier;
5435 if (getLangOpts().CPlusPlus)
5436 DiagID = diag::ext_standalone_specifier;
5437
5438 // Note that a linkage-specification sets a storage class, but
5439 // 'extern "C" struct foo;' is actually valid and not theoretically
5440 // useless.
5441 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5442 if (SCS == DeclSpec::SCS_mutable)
5443 // Since mutable is not a viable storage class specifier in C, there is
5444 // no reason to treat it as an extension. Instead, diagnose as an error.
5445 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5446 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5447 Diag(DS.getStorageClassSpecLoc(), DiagID)
5449 }
5450
5454 if (DS.getTypeQualifiers()) {
5456 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5458 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5459 // Restrict is covered above.
5461 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5463 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5464 }
5465
5466 // Warn about ignored type attributes, for example:
5467 // __attribute__((aligned)) struct A;
5468 // Attributes should be placed after tag to apply to type declaration.
5469 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5470 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5471 if (TypeSpecType == DeclSpec::TST_class ||
5472 TypeSpecType == DeclSpec::TST_struct ||
5473 TypeSpecType == DeclSpec::TST_interface ||
5474 TypeSpecType == DeclSpec::TST_union ||
5475 TypeSpecType == DeclSpec::TST_enum) {
5476
5477 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5478 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5479 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5480 DiagnosticId = diag::warn_attribute_ignored;
5481 else if (AL.isRegularKeywordAttribute())
5482 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5483 else
5484 DiagnosticId = diag::warn_declspec_attribute_ignored;
5485 Diag(AL.getLoc(), DiagnosticId)
5486 << AL << GetDiagnosticTypeSpecifierID(DS);
5487 };
5488
5489 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5490 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5491 }
5492 }
5493
5494 return TagD;
5495}
5496
5497/// We are trying to inject an anonymous member into the given scope;
5498/// check if there's an existing declaration that can't be overloaded.
5499///
5500/// \return true if this is a forbidden redeclaration
5501static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5502 DeclContext *Owner,
5503 DeclarationName Name,
5504 SourceLocation NameLoc, bool IsUnion,
5505 StorageClass SC) {
5506 LookupResult R(SemaRef, Name, NameLoc,
5510 if (!SemaRef.LookupName(R, S)) return false;
5511
5512 // Pick a representative declaration.
5513 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5514 assert(PrevDecl && "Expected a non-null Decl");
5515
5516 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5517 return false;
5518
5519 if (SC == StorageClass::SC_None &&
5520 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5521 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5522 if (!Owner->isRecord())
5523 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5524 return false;
5525 }
5526
5527 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5528 << IsUnion << Name;
5529 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5530
5531 return true;
5532}
5533
5535 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5537}
5538
5540 if (!getLangOpts().CPlusPlus)
5541 return;
5542
5543 // This function can be parsed before we have validated the
5544 // structure as an anonymous struct
5545 if (Record->isAnonymousStructOrUnion())
5546 return;
5547
5548 const NamedDecl *First = 0;
5549 for (const Decl *D : Record->decls()) {
5550 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5551 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5552 continue;
5553 if (!First)
5554 First = ND;
5555 else
5557 }
5558}
5559
5560/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5561/// anonymous struct or union AnonRecord into the owning context Owner
5562/// and scope S. This routine will be invoked just after we realize
5563/// that an unnamed union or struct is actually an anonymous union or
5564/// struct, e.g.,
5565///
5566/// @code
5567/// union {
5568/// int i;
5569/// float f;
5570/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5571/// // f into the surrounding scope.x
5572/// @endcode
5573///
5574/// This routine is recursive, injecting the names of nested anonymous
5575/// structs/unions into the owning context and scope as well.
5576static bool
5578 RecordDecl *AnonRecord, AccessSpecifier AS,
5579 StorageClass SC,
5580 SmallVectorImpl<NamedDecl *> &Chaining) {
5581 bool Invalid = false;
5582
5583 // Look every FieldDecl and IndirectFieldDecl with a name.
5584 for (auto *D : AnonRecord->decls()) {
5585 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5586 cast<NamedDecl>(D)->getDeclName()) {
5587 ValueDecl *VD = cast<ValueDecl>(D);
5588 // C++ [class.union]p2:
5589 // The names of the members of an anonymous union shall be
5590 // distinct from the names of any other entity in the
5591 // scope in which the anonymous union is declared.
5592
5593 bool FieldInvalid = CheckAnonMemberRedeclaration(
5594 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5595 AnonRecord->isUnion(), SC);
5596 if (FieldInvalid)
5597 Invalid = true;
5598
5599 // Inject the IndirectFieldDecl even if invalid, because later
5600 // diagnostics may depend on it being present, see findDefaultInitializer.
5601
5602 // C++ [class.union]p2:
5603 // For the purpose of name lookup, after the anonymous union
5604 // definition, the members of the anonymous union are
5605 // considered to have been defined in the scope in which the
5606 // anonymous union is declared.
5607 unsigned OldChainingSize = Chaining.size();
5608 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5609 Chaining.append(IF->chain_begin(), IF->chain_end());
5610 else
5611 Chaining.push_back(VD);
5612
5613 assert(Chaining.size() >= 2);
5614 NamedDecl **NamedChain =
5615 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5616 for (unsigned i = 0; i < Chaining.size(); i++)
5617 NamedChain[i] = Chaining[i];
5618
5620 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5621 VD->getType(), {NamedChain, Chaining.size()});
5622
5623 for (const auto *Attr : VD->attrs())
5624 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5625
5626 IndirectField->setAccess(AS);
5627 IndirectField->setImplicit();
5628 IndirectField->setInvalidDecl(FieldInvalid);
5629 SemaRef.PushOnScopeChains(IndirectField, S);
5630
5631 // That includes picking up the appropriate access specifier.
5632 if (AS != AS_none)
5633 IndirectField->setAccess(AS);
5634
5635 Chaining.resize(OldChainingSize);
5636 }
5637 }
5638
5639 return Invalid;
5640}
5641
5642/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5643/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5644/// illegal input values are mapped to SC_None.
5645static StorageClass
5647 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5648 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5649 "Parser allowed 'typedef' as storage class VarDecl.");
5650 switch (StorageClassSpec) {
5653 if (DS.isExternInLinkageSpec())
5654 return SC_None;
5655 return SC_Extern;
5656 case DeclSpec::SCS_static: return SC_Static;
5657 case DeclSpec::SCS_auto: return SC_Auto;
5660 // Illegal SCSs map to None: error reporting is up to the caller.
5661 case DeclSpec::SCS_mutable: // Fall through.
5662 case DeclSpec::SCS_typedef: return SC_None;
5663 }
5664 llvm_unreachable("unknown storage class specifier");
5665}
5666
5668 assert(Record->hasInClassInitializer());
5669
5670 for (const auto *I : Record->decls()) {
5671 const auto *FD = dyn_cast<FieldDecl>(I);
5672 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5673 FD = IFD->getAnonField();
5674 if (FD && FD->hasInClassInitializer())
5675 return FD->getLocation();
5676 }
5677
5678 llvm_unreachable("couldn't find in-class initializer");
5679}
5680
5682 SourceLocation DefaultInitLoc) {
5683 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5684 return;
5685
5686 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5687 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5688}
5689
5691 CXXRecordDecl *AnonUnion) {
5692 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5693 return;
5694
5696}
5697
5699 AccessSpecifier AS,
5701 const PrintingPolicy &Policy) {
5702 DeclContext *Owner = Record->getDeclContext();
5703
5704 // Diagnose whether this anonymous struct/union is an extension.
5705 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5706 Diag(Record->getLocation(), diag::ext_anonymous_union);
5707 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5708 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5709 else if (!Record->isUnion() && !getLangOpts().C11)
5710 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5711
5712 // C and C++ require different kinds of checks for anonymous
5713 // structs/unions.
5714 bool Invalid = false;
5715 if (getLangOpts().CPlusPlus) {
5716 const char *PrevSpec = nullptr;
5717 if (Record->isUnion()) {
5718 // C++ [class.union]p6:
5719 // C++17 [class.union.anon]p2:
5720 // Anonymous unions declared in a named namespace or in the
5721 // global namespace shall be declared static.
5722 unsigned DiagID;
5723 DeclContext *OwnerScope = Owner->getRedeclContext();
5725 (OwnerScope->isTranslationUnit() ||
5726 (OwnerScope->isNamespace() &&
5727 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5728 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5729 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5730
5731 // Recover by adding 'static'.
5733 PrevSpec, DiagID, Policy);
5734 }
5735 // C++ [class.union]p6:
5736 // A storage class is not allowed in a declaration of an
5737 // anonymous union in a class scope.
5739 isa<RecordDecl>(Owner)) {
5741 diag::err_anonymous_union_with_storage_spec)
5743
5744 // Recover by removing the storage specifier.
5747 PrevSpec, DiagID, Context.getPrintingPolicy());
5748 }
5749 }
5750
5751 // Ignore const/volatile/restrict qualifiers.
5752 if (DS.getTypeQualifiers()) {
5754 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5755 << Record->isUnion() << "const"
5759 diag::ext_anonymous_struct_union_qualified)
5760 << Record->isUnion() << "volatile"
5764 diag::ext_anonymous_struct_union_qualified)
5765 << Record->isUnion() << "restrict"
5769 diag::ext_anonymous_struct_union_qualified)
5770 << Record->isUnion() << "_Atomic"
5774 diag::ext_anonymous_struct_union_qualified)
5775 << Record->isUnion() << "__unaligned"
5777
5779 }
5780
5781 // C++ [class.union]p2:
5782 // The member-specification of an anonymous union shall only
5783 // define non-static data members. [Note: nested types and
5784 // functions cannot be declared within an anonymous union. ]
5785 for (auto *Mem : Record->decls()) {
5786 // Ignore invalid declarations; we already diagnosed them.
5787 if (Mem->isInvalidDecl())
5788 continue;
5789
5790 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5791 // C++ [class.union]p3:
5792 // An anonymous union shall not have private or protected
5793 // members (clause 11).
5794 assert(FD->getAccess() != AS_none);
5795 if (FD->getAccess() != AS_public) {
5796 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5797 << Record->isUnion() << (FD->getAccess() == AS_protected);
5798 Invalid = true;
5799 }
5800
5801 // C++ [class.union]p1
5802 // An object of a class with a non-trivial constructor, a non-trivial
5803 // copy constructor, a non-trivial destructor, or a non-trivial copy
5804 // assignment operator cannot be a member of a union, nor can an
5805 // array of such objects.
5806 if (CheckNontrivialField(FD))
5807 Invalid = true;
5808 } else if (Mem->isImplicit()) {
5809 // Any implicit members are fine.
5810 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5811 // This is a type that showed up in an
5812 // elaborated-type-specifier inside the anonymous struct or
5813 // union, but which actually declares a type outside of the
5814 // anonymous struct or union. It's okay.
5815 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5816 if (!MemRecord->isAnonymousStructOrUnion() &&
5817 MemRecord->getDeclName()) {
5818 // Visual C++ allows type definition in anonymous struct or union.
5819 if (getLangOpts().MicrosoftExt)
5820 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5821 << Record->isUnion();
5822 else {
5823 // This is a nested type declaration.
5824 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5825 << Record->isUnion();
5826 Invalid = true;
5827 }
5828 } else {
5829 // This is an anonymous type definition within another anonymous type.
5830 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5831 // not part of standard C++.
5832 Diag(MemRecord->getLocation(),
5833 diag::ext_anonymous_record_with_anonymous_type)
5834 << Record->isUnion();
5835 }
5836 } else if (isa<AccessSpecDecl>(Mem)) {
5837 // Any access specifier is fine.
5838 } else if (isa<StaticAssertDecl>(Mem)) {
5839 // In C++1z, static_assert declarations are also fine.
5840 } else {
5841 // We have something that isn't a non-static data
5842 // member. Complain about it.
5843 unsigned DK = diag::err_anonymous_record_bad_member;
5844 if (isa<TypeDecl>(Mem))
5845 DK = diag::err_anonymous_record_with_type;
5846 else if (isa<FunctionDecl>(Mem))
5847 DK = diag::err_anonymous_record_with_function;
5848 else if (isa<VarDecl>(Mem))
5849 DK = diag::err_anonymous_record_with_static;
5850
5851 // Visual C++ allows type definition in anonymous struct or union.
5852 if (getLangOpts().MicrosoftExt &&
5853 DK == diag::err_anonymous_record_with_type)
5854 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5855 << Record->isUnion();
5856 else {
5857 Diag(Mem->getLocation(), DK) << Record->isUnion();
5858 Invalid = true;
5859 }
5860 }
5861 }
5862
5863 // C++11 [class.union]p8 (DR1460):
5864 // At most one variant member of a union may have a
5865 // brace-or-equal-initializer.
5866 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5867 Owner->isRecord())
5870 }
5871
5872 if (!Record->isUnion() && !Owner->isRecord()) {
5873 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5874 << getLangOpts().CPlusPlus;
5875 Invalid = true;
5876 }
5877
5878 // C++ [dcl.dcl]p3:
5879 // [If there are no declarators], and except for the declaration of an
5880 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5881 // names into the program
5882 // C++ [class.mem]p2:
5883 // each such member-declaration shall either declare at least one member
5884 // name of the class or declare at least one unnamed bit-field
5885 //
5886 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5887 if (getLangOpts().CPlusPlus && Record->field_empty())
5888 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5889
5890 // Mock up a declarator.
5894 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5895
5896 // Create a declaration for this anonymous struct/union.
5897 NamedDecl *Anon = nullptr;
5898 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5899 Anon = FieldDecl::Create(
5900 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5901 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5902 /*BitWidth=*/nullptr, /*Mutable=*/false,
5903 /*InitStyle=*/ICIS_NoInit);
5904 Anon->setAccess(AS);
5905 ProcessDeclAttributes(S, Anon, Dc);
5906
5907 if (getLangOpts().CPlusPlus)
5908 FieldCollector->Add(cast<FieldDecl>(Anon));
5909 } else {
5910 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5911 if (SCSpec == DeclSpec::SCS_mutable) {
5912 // mutable can only appear on non-static class members, so it's always
5913 // an error here
5914 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5915 Invalid = true;
5916 SC = SC_None;
5917 }
5918
5919 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5920 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5921 Context.getCanonicalTagType(Record), TInfo, SC);
5922 if (Invalid)
5923 Anon->setInvalidDecl();
5924
5925 ProcessDeclAttributes(S, Anon, Dc);
5926
5927 // Default-initialize the implicit variable. This initialization will be
5928 // trivial in almost all cases, except if a union member has an in-class
5929 // initializer:
5930 // union { int n = 0; };
5932 }
5933 Anon->setImplicit();
5934
5935 // Mark this as an anonymous struct/union type.
5936 Record->setAnonymousStructOrUnion(true);
5937
5938 // Add the anonymous struct/union object to the current
5939 // context. We'll be referencing this object when we refer to one of
5940 // its members.
5941 Owner->addDecl(Anon);
5942
5943 // Inject the members of the anonymous struct/union into the owning
5944 // context and into the identifier resolver chain for name lookup
5945 // purposes.
5947 Chain.push_back(Anon);
5948
5949 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5950 Chain))
5951 Invalid = true;
5952
5953 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5954 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5956 Decl *ManglingContextDecl;
5957 std::tie(MCtx, ManglingContextDecl) =
5958 getCurrentMangleNumberContext(NewVD->getDeclContext());
5959 if (MCtx) {
5960 Context.setManglingNumber(
5961 NewVD, MCtx->getManglingNumber(
5962 NewVD, getMSManglingNumber(getLangOpts(), S)));
5963 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5964 }
5965 }
5966 }
5967
5968 if (Invalid)
5969 Anon->setInvalidDecl();
5970
5971 return Anon;
5972}
5973
5975 RecordDecl *Record) {
5976 assert(Record && "expected a record!");
5977
5978 // Mock up a declarator.
5981 assert(TInfo && "couldn't build declarator info for anonymous struct");
5982
5983 auto *ParentDecl = cast<RecordDecl>(CurContext);
5984 CanQualType RecTy = Context.getCanonicalTagType(Record);
5985
5986 // Create a declaration for this anonymous struct.
5987 NamedDecl *Anon =
5988 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5989 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5990 /*BitWidth=*/nullptr, /*Mutable=*/false,
5991 /*InitStyle=*/ICIS_NoInit);
5992 Anon->setImplicit();
5993
5994 // Add the anonymous struct object to the current context.
5995 CurContext->addDecl(Anon);
5996
5997 // Inject the members of the anonymous struct into the current
5998 // context and into the identifier resolver chain for name lookup
5999 // purposes.
6001 Chain.push_back(Anon);
6002
6003 RecordDecl *RecordDef = Record->getDefinition();
6004 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
6005 diag::err_field_incomplete_or_sizeless) ||
6007 *this, S, CurContext, RecordDef, AS_none,
6009 Anon->setInvalidDecl();
6010 ParentDecl->setInvalidDecl();
6011 }
6012
6013 return Anon;
6014}
6015
6019
6022 DeclarationNameInfo NameInfo;
6023 NameInfo.setLoc(Name.StartLocation);
6024
6025 switch (Name.getKind()) {
6026
6029 NameInfo.setName(Name.Identifier);
6030 return NameInfo;
6031
6033 // C++ [temp.deduct.guide]p3:
6034 // The simple-template-id shall name a class template specialization.
6035 // The template-name shall be the same identifier as the template-name
6036 // of the simple-template-id.
6037 // These together intend to imply that the template-name shall name a
6038 // class template.
6039 // FIXME: template<typename T> struct X {};
6040 // template<typename T> using Y = X<T>;
6041 // Y(int) -> Y<int>;
6042 // satisfies these rules but does not name a class template.
6043 TemplateName TN = Name.TemplateName.get().get();
6044 auto *Template = TN.getAsTemplateDecl();
6046 Diag(Name.StartLocation,
6047 diag::err_deduction_guide_name_not_class_template)
6048 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6049 if (Template)
6051 return DeclarationNameInfo();
6052 }
6053
6054 NameInfo.setName(
6055 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6056 return NameInfo;
6057 }
6058
6060 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6064 return NameInfo;
6065
6067 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6068 Name.Identifier));
6070 return NameInfo;
6071
6073 TypeSourceInfo *TInfo;
6075 if (Ty.isNull())
6076 return DeclarationNameInfo();
6077 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6078 Context.getCanonicalType(Ty)));
6079 NameInfo.setNamedTypeInfo(TInfo);
6080 return NameInfo;
6081 }
6082
6084 TypeSourceInfo *TInfo;
6085 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6086 if (Ty.isNull())
6087 return DeclarationNameInfo();
6088 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6089 Context.getCanonicalType(Ty)));
6090 NameInfo.setNamedTypeInfo(TInfo);
6091 return NameInfo;
6092 }
6093
6095 // In well-formed code, we can only have a constructor
6096 // template-id that refers to the current context, so go there
6097 // to find the actual type being constructed.
6098 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6099 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6100 return DeclarationNameInfo();
6101
6102 // Determine the type of the class being constructed.
6103 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6104
6105 // FIXME: Check two things: that the template-id names the same type as
6106 // CurClassType, and that the template-id does not occur when the name
6107 // was qualified.
6108
6109 NameInfo.setName(
6110 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6111 // FIXME: should we retrieve TypeSourceInfo?
6112 NameInfo.setNamedTypeInfo(nullptr);
6113 return NameInfo;
6114 }
6115
6117 TypeSourceInfo *TInfo;
6118 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6119 if (Ty.isNull())
6120 return DeclarationNameInfo();
6121 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6122 Context.getCanonicalType(Ty)));
6123 NameInfo.setNamedTypeInfo(TInfo);
6124 return NameInfo;
6125 }
6126
6128 TemplateName TName = Name.TemplateId->Template.get();
6129 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6130 return Context.getNameForTemplate(TName, TNameLoc);
6131 }
6132
6133 } // switch (Name.getKind())
6134
6135 llvm_unreachable("Unknown name kind");
6136}
6137
6139 do {
6140 if (Ty->isPointerOrReferenceType())
6141 Ty = Ty->getPointeeType();
6142 else if (Ty->isArrayType())
6144 else
6145 return Ty.withoutLocalFastQualifiers();
6146 } while (true);
6147}
6148
6149/// hasSimilarParameters - Determine whether the C++ functions Declaration
6150/// and Definition have "nearly" matching parameters. This heuristic is
6151/// used to improve diagnostics in the case where an out-of-line function
6152/// definition doesn't match any declaration within the class or namespace.
6153/// Also sets Params to the list of indices to the parameters that differ
6154/// between the declaration and the definition. If hasSimilarParameters
6155/// returns true and Params is empty, then all of the parameters match.
6159 SmallVectorImpl<unsigned> &Params) {
6160 Params.clear();
6161 if (Declaration->param_size() != Definition->param_size())
6162 return false;
6163 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6164 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6165 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6166
6167 // The parameter types are identical
6168 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6169 continue;
6170
6171 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6172 QualType DefParamBaseTy = getCoreType(DefParamTy);
6173 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6174 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6175
6176 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6177 (DeclTyName && DeclTyName == DefTyName))
6178 Params.push_back(Idx);
6179 else // The two parameters aren't even close
6180 return false;
6181 }
6182
6183 return true;
6184}
6185
6186/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6187/// declarator needs to be rebuilt in the current instantiation.
6188/// Any bits of declarator which appear before the name are valid for
6189/// consideration here. That's specifically the type in the decl spec
6190/// and the base type in any member-pointer chunks.
6192 DeclarationName Name) {
6193 // The types we specifically need to rebuild are:
6194 // - typenames, typeofs, and decltypes
6195 // - types which will become injected class names
6196 // Of course, we also need to rebuild any type referencing such a
6197 // type. It's safest to just say "dependent", but we call out a
6198 // few cases here.
6199
6200 DeclSpec &DS = D.getMutableDeclSpec();
6201 switch (DS.getTypeSpecType()) {
6205#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6206#include "clang/Basic/TransformTypeTraits.def"
6207 case DeclSpec::TST_atomic: {
6208 // Grab the type from the parser.
6209 TypeSourceInfo *TSI = nullptr;
6210 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6211 if (T.isNull() || !T->isInstantiationDependentType()) break;
6212
6213 // Make sure there's a type source info. This isn't really much
6214 // of a waste; most dependent types should have type source info
6215 // attached already.
6216 if (!TSI)
6218
6219 // Rebuild the type in the current instantiation.
6221 if (!TSI) return true;
6222
6223 // Store the new type back in the decl spec.
6224 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6225 DS.UpdateTypeRep(LocType);
6226 break;
6227 }
6228
6232 Expr *E = DS.getRepAsExpr();
6234 if (Result.isInvalid()) return true;
6235 DS.UpdateExprRep(Result.get());
6236 break;
6237 }
6238
6239 default:
6240 // Nothing to do for these decl specs.
6241 break;
6242 }
6243
6244 // It doesn't matter what order we do this in.
6245 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6246 DeclaratorChunk &Chunk = D.getTypeObject(I);
6247
6248 // The only type information in the declarator which can come
6249 // before the declaration name is the base type of a member
6250 // pointer.
6252 continue;
6253
6254 // Rebuild the scope specifier in-place.
6255 CXXScopeSpec &SS = Chunk.Mem.Scope();
6257 return true;
6258 }
6259
6260 return false;
6261}
6262
6263/// Returns true if the declaration is declared in a system header or from a
6264/// system macro.
6265static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6266 return SM.isInSystemHeader(D->getLocation()) ||
6267 SM.isInSystemMacro(D->getLocation());
6268}
6269
6271 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6272 // of system decl.
6273 if (D->getPreviousDecl() || D->isImplicit())
6274 return;
6277 !isFromSystemHeader(Context.getSourceManager(), D)) {
6278 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6279 << D << static_cast<int>(Status);
6280 }
6281}
6282
6285
6286 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6287 // declaration only if the `bind_to_declaration` extension is set.
6289 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6290 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6291 llvm::omp::TraitProperty::
6292 implementation_extension_bind_to_declaration))
6294 S, D, MultiTemplateParamsArg(), Bases);
6295
6297
6298 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6299 Dcl && Dcl->getDeclContext()->isFileContext())
6301
6302 if (!Bases.empty())
6304 Bases);
6305
6306 return Dcl;
6307}
6308
6310 DeclarationNameInfo NameInfo) {
6311 DeclarationName Name = NameInfo.getName();
6312
6313 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6314 while (Record && Record->isAnonymousStructOrUnion())
6315 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6316 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6317 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6318 return true;
6319 }
6320
6321 return false;
6322}
6323
6325 DeclarationName Name,
6326 SourceLocation Loc,
6327 TemplateIdAnnotation *TemplateId,
6328 bool IsMemberSpecialization) {
6329 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6330 "without nested-name-specifier");
6331 DeclContext *Cur = CurContext;
6332 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6333 Cur = Cur->getParent();
6334
6335 // If the user provided a superfluous scope specifier that refers back to the
6336 // class in which the entity is already declared, diagnose and ignore it.
6337 //
6338 // class X {
6339 // void X::f();
6340 // };
6341 //
6342 // Note, it was once ill-formed to give redundant qualification in all
6343 // contexts, but that rule was removed by DR482.
6344 if (Cur->Equals(DC)) {
6345 if (Cur->isRecord()) {
6346 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6347 : diag::err_member_extra_qualification)
6348 << Name << FixItHint::CreateRemoval(SS.getRange());
6349 SS.clear();
6350 } else {
6351 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6352 }
6353 return false;
6354 }
6355
6356 // Check whether the qualifying scope encloses the scope of the original
6357 // declaration. For a template-id, we perform the checks in
6358 // CheckTemplateSpecializationScope.
6359 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6360 if (Cur->isRecord())
6361 Diag(Loc, diag::err_member_qualification)
6362 << Name << SS.getRange();
6363 else if (isa<TranslationUnitDecl>(DC))
6364 Diag(Loc, diag::err_invalid_declarator_global_scope)
6365 << Name << SS.getRange();
6366 else if (isa<FunctionDecl>(Cur))
6367 Diag(Loc, diag::err_invalid_declarator_in_function)
6368 << Name << SS.getRange();
6369 else if (isa<BlockDecl>(Cur))
6370 Diag(Loc, diag::err_invalid_declarator_in_block)
6371 << Name << SS.getRange();
6372 else if (isa<ExportDecl>(Cur)) {
6373 if (!isa<NamespaceDecl>(DC))
6374 Diag(Loc, diag::err_export_non_namespace_scope_name)
6375 << Name << SS.getRange();
6376 else
6377 // The cases that DC is not NamespaceDecl should be handled in
6378 // CheckRedeclarationExported.
6379 return false;
6380 } else
6381 Diag(Loc, diag::err_invalid_declarator_scope)
6382 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6383
6384 return true;
6385 }
6386
6387 if (Cur->isRecord()) {
6388 // Cannot qualify members within a class.
6389 Diag(Loc, diag::err_member_qualification)
6390 << Name << SS.getRange();
6391 SS.clear();
6392
6393 // C++ constructors and destructors with incorrect scopes can break
6394 // our AST invariants by having the wrong underlying types. If
6395 // that's the case, then drop this declaration entirely.
6398 !Context.hasSameType(
6399 Name.getCXXNameType(),
6400 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6401 return true;
6402
6403 return false;
6404 }
6405
6406 // C++23 [temp.names]p5:
6407 // The keyword template shall not appear immediately after a declarative
6408 // nested-name-specifier.
6409 //
6410 // First check the template-id (if any), and then check each component of the
6411 // nested-name-specifier in reverse order.
6412 //
6413 // FIXME: nested-name-specifiers in friend declarations are declarative,
6414 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6415 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6416 Diag(Loc, diag::ext_template_after_declarative_nns)
6418
6420 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6421 TL = std::exchange(NextTL, TypeLoc())) {
6422 SourceLocation TemplateKeywordLoc;
6423 switch (TL.getTypeLocClass()) {
6424 case TypeLoc::TemplateSpecialization: {
6425 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6426 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6427 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6428 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6429 << TST.getLocalSourceRange();
6430 break;
6431 }
6432 case TypeLoc::Decltype:
6433 case TypeLoc::PackIndexing: {
6434 const Type *T = TL.getTypePtr();
6435 // C++23 [expr.prim.id.qual]p2:
6436 // [...] A declarative nested-name-specifier shall not have a
6437 // computed-type-specifier.
6438 //
6439 // CWG2858 changed this from 'decltype-specifier' to
6440 // 'computed-type-specifier'.
6441 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6442 << T->isDecltypeType() << TL.getSourceRange();
6443 break;
6444 }
6445 case TypeLoc::DependentName:
6446 NextTL =
6447 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6448 break;
6449 default:
6450 break;
6451 }
6452 if (TemplateKeywordLoc.isValid())
6453 Diag(Loc, diag::ext_template_after_declarative_nns)
6454 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6455 }
6456
6457 return false;
6458}
6459
6461 MultiTemplateParamsArg TemplateParamLists) {
6462 // TODO: consider using NameInfo for diagnostic.
6464 DeclarationName Name = NameInfo.getName();
6465
6466 // All of these full declarators require an identifier. If it doesn't have
6467 // one, the ParsedFreeStandingDeclSpec action should be used.
6468 if (D.isDecompositionDeclarator()) {
6469 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6470 } else if (!Name) {
6471 if (!D.isInvalidType()) // Reject this if we think it is valid.
6472 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6474 return nullptr;
6476 return nullptr;
6477
6478 DeclContext *DC = CurContext;
6479 if (D.getCXXScopeSpec().isInvalid())
6480 D.setInvalidType();
6481 else if (D.getCXXScopeSpec().isSet()) {
6484 return nullptr;
6485
6486 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6487 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6488 if (!DC || isa<EnumDecl>(DC)) {
6489 // If we could not compute the declaration context, it's because the
6490 // declaration context is dependent but does not refer to a class,
6491 // class template, or class template partial specialization. Complain
6492 // and return early, to avoid the coming semantic disaster.
6494 diag::err_template_qualified_declarator_no_match)
6496 << D.getCXXScopeSpec().getRange();
6497 return nullptr;
6498 }
6499 bool IsDependentContext = DC->isDependentContext();
6500
6501 if (!IsDependentContext &&
6503 return nullptr;
6504
6505 // If a class is incomplete, do not parse entities inside it.
6508 diag::err_member_def_undefined_record)
6509 << Name << DC << D.getCXXScopeSpec().getRange();
6510 return nullptr;
6511 }
6512 if (!D.getDeclSpec().isFriendSpecified()) {
6513 TemplateIdAnnotation *TemplateId =
6515 ? D.getName().TemplateId
6516 : nullptr;
6518 D.getIdentifierLoc(), TemplateId,
6519 /*IsMemberSpecialization=*/false)) {
6520 if (DC->isRecord())
6521 return nullptr;
6522
6523 D.setInvalidType();
6524 }
6525 }
6526
6527 // Check whether we need to rebuild the type of the given
6528 // declaration in the current instantiation.
6529 if (EnteringContext && IsDependentContext &&
6530 TemplateParamLists.size() != 0) {
6531 ContextRAII SavedContext(*this, DC);
6532 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6533 D.setInvalidType();
6534 }
6535 }
6536
6538 QualType R = TInfo->getType();
6539
6542 D.setInvalidType();
6543
6544 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6546
6547 // See if this is a redefinition of a variable in the same scope.
6548 if (!D.getCXXScopeSpec().isSet()) {
6549 bool IsLinkageLookup = false;
6550 bool CreateBuiltins = false;
6551
6552 // If the declaration we're planning to build will be a function
6553 // or object with linkage, then look for another declaration with
6554 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6555 //
6556 // If the declaration we're planning to build will be declared with
6557 // external linkage in the translation unit, create any builtin with
6558 // the same name.
6560 /* Do nothing*/;
6561 else if (CurContext->isFunctionOrMethod() &&
6563 R->isFunctionType())) {
6564 IsLinkageLookup = true;
6565 CreateBuiltins =
6566 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6567 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6569 CreateBuiltins = true;
6570
6571 if (IsLinkageLookup) {
6573 Previous.setRedeclarationKind(
6575 }
6576
6577 LookupName(Previous, S, CreateBuiltins);
6578 } else { // Something like "int foo::x;"
6580
6581 // C++ [dcl.meaning]p1:
6582 // When the declarator-id is qualified, the declaration shall refer to a
6583 // previously declared member of the class or namespace to which the
6584 // qualifier refers (or, in the case of a namespace, of an element of the
6585 // inline namespace set of that namespace (7.3.1)) or to a specialization
6586 // thereof; [...]
6587 //
6588 // Note that we already checked the context above, and that we do not have
6589 // enough information to make sure that Previous contains the declaration
6590 // we want to match. For example, given:
6591 //
6592 // class X {
6593 // void f();
6594 // void f(float);
6595 // };
6596 //
6597 // void X::f(int) { } // ill-formed
6598 //
6599 // In this case, Previous will point to the overload set
6600 // containing the two f's declared in X, but neither of them
6601 // matches.
6602
6604 }
6605
6606 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6607 TPD && TPD->isTemplateParameter()) {
6608 // Older versions of clang allowed the names of function/variable templates
6609 // to shadow the names of their template parameters. For the compatibility
6610 // purposes we detect such cases and issue a default-to-error warning that
6611 // can be disabled with -Wno-strict-primary-template-shadow.
6612 if (!D.isInvalidType()) {
6613 bool AllowForCompatibility = false;
6614 if (Scope *DeclParent = S->getDeclParent();
6615 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6616 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6617 TemplateParamParent->isDeclScope(TPD);
6618 }
6620 AllowForCompatibility);
6621 }
6622
6623 // Just pretend that we didn't see the previous declaration.
6624 Previous.clear();
6625 }
6626
6627 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6628 // Forget that the previous declaration is the injected-class-name.
6629 Previous.clear();
6630
6631 // In C++, the previous declaration we find might be a tag type
6632 // (class or enum). In this case, the new declaration will hide the
6633 // tag type. Note that this applies to functions, function templates, and
6634 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6635 if (Previous.isSingleTagDecl() &&
6637 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6638 Previous.clear();
6639
6640 // Check that there are no default arguments other than in the parameters
6641 // of a function declaration (C++ only).
6642 if (getLangOpts().CPlusPlus)
6644
6645 /// Get the innermost enclosing declaration scope.
6646 S = S->getDeclParent();
6647
6648 NamedDecl *New;
6649
6650 bool AddToScope = true;
6652 if (TemplateParamLists.size()) {
6653 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6654 return nullptr;
6655 }
6656
6657 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6658 } else if (R->isFunctionType()) {
6659 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6660 TemplateParamLists,
6661 AddToScope);
6662 } else {
6663 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6664 AddToScope);
6665 }
6666
6667 if (!New)
6668 return nullptr;
6669
6671
6672 // If this has an identifier and is not a function template specialization,
6673 // add it to the scope stack.
6674 if (New->getDeclName() && AddToScope)
6676
6677 if (OpenMP().isInOpenMPDeclareTargetContext())
6679
6680 return New;
6681}
6682
6683/// Helper method to turn variable array types into constant array
6684/// types in certain situations which would otherwise be errors (for
6685/// GCC compatibility).
6687 ASTContext &Context,
6688 bool &SizeIsNegative,
6689 llvm::APSInt &Oversized) {
6690 // This method tries to turn a variable array into a constant
6691 // array even when the size isn't an ICE. This is necessary
6692 // for compatibility with code that depends on gcc's buggy
6693 // constant expression folding, like struct {char x[(int)(char*)2];}
6694 SizeIsNegative = false;
6695 Oversized = 0;
6696
6697 if (T->isDependentType())
6698 return QualType();
6699
6701 const Type *Ty = Qs.strip(T);
6702
6703 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6704 QualType Pointee = PTy->getPointeeType();
6705 QualType FixedType =
6706 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6707 Oversized);
6708 if (FixedType.isNull()) return FixedType;
6709 FixedType = Context.getPointerType(FixedType);
6710 return Qs.apply(Context, FixedType);
6711 }
6712 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6713 QualType Inner = PTy->getInnerType();
6714 QualType FixedType =
6715 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6716 Oversized);
6717 if (FixedType.isNull()) return FixedType;
6718 FixedType = Context.getParenType(FixedType);
6719 return Qs.apply(Context, FixedType);
6720 }
6721
6722 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6723 if (!VLATy)
6724 return QualType();
6725
6726 QualType ElemTy = VLATy->getElementType();
6727 if (ElemTy->isVariablyModifiedType()) {
6728 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6729 SizeIsNegative, Oversized);
6730 if (ElemTy.isNull())
6731 return QualType();
6732 }
6733
6735 if (!VLATy->getSizeExpr() ||
6736 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6737 return QualType();
6738
6739 llvm::APSInt Res = Result.Val.getInt();
6740
6741 // Check whether the array size is negative.
6742 if (Res.isSigned() && Res.isNegative()) {
6743 SizeIsNegative = true;
6744 return QualType();
6745 }
6746
6747 // Check whether the array is too large to be addressed.
6748 unsigned ActiveSizeBits =
6749 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6750 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6751 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6752 : Res.getActiveBits();
6753 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6754 Oversized = std::move(Res);
6755 return QualType();
6756 }
6757
6758 QualType FoldedArrayType = Context.getConstantArrayType(
6759 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6760 return Qs.apply(Context, FoldedArrayType);
6761}
6762
6763static void
6765 SrcTL = SrcTL.getUnqualifiedLoc();
6766 DstTL = DstTL.getUnqualifiedLoc();
6767 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6768 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6769 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6770 DstPTL.getPointeeLoc());
6771 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6772 return;
6773 }
6774 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6775 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6776 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6777 DstPTL.getInnerLoc());
6778 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6779 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6780 return;
6781 }
6782 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6783 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6784 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6785 TypeLoc DstElemTL = DstATL.getElementLoc();
6786 if (VariableArrayTypeLoc SrcElemATL =
6787 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6788 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6789 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6790 } else {
6791 DstElemTL.initializeFullCopy(SrcElemTL);
6792 }
6793 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6794 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6795 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6796}
6797
6798/// Helper method to turn variable array types into constant array
6799/// types in certain situations which would otherwise be errors (for
6800/// GCC compatibility).
6801static TypeSourceInfo*
6803 ASTContext &Context,
6804 bool &SizeIsNegative,
6805 llvm::APSInt &Oversized) {
6806 QualType FixedTy
6807 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6808 SizeIsNegative, Oversized);
6809 if (FixedTy.isNull())
6810 return nullptr;
6811 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6813 FixedTInfo->getTypeLoc());
6814 return FixedTInfo;
6815}
6816
6818 QualType &T, SourceLocation Loc,
6819 unsigned FailedFoldDiagID) {
6820 bool SizeIsNegative;
6821 llvm::APSInt Oversized;
6823 TInfo, Context, SizeIsNegative, Oversized);
6824 if (FixedTInfo) {
6825 Diag(Loc, diag::ext_vla_folded_to_constant);
6826 TInfo = FixedTInfo;
6827 T = FixedTInfo->getType();
6828 return true;
6829 }
6830
6831 if (SizeIsNegative)
6832 Diag(Loc, diag::err_typecheck_negative_array_size);
6833 else if (Oversized.getBoolValue())
6834 Diag(Loc, diag::err_array_too_large) << toString(
6835 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6836 /*UpperCase=*/false, /*InsertSeparators=*/true);
6837 else if (FailedFoldDiagID)
6838 Diag(Loc, FailedFoldDiagID);
6839 return false;
6840}
6841
6842void
6844 if (!getLangOpts().CPlusPlus &&
6846 // Don't need to track declarations in the TU in C.
6847 return;
6848
6849 // Note that we have a locally-scoped external with this name.
6850 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6851}
6852
6854 // FIXME: We can have multiple results via __attribute__((overloadable)).
6855 auto Result = Context.getExternCContextDecl()->lookup(Name);
6856 return Result.empty() ? nullptr : *Result.begin();
6857}
6858
6860 // FIXME: We should probably indicate the identifier in question to avoid
6861 // confusion for constructs like "virtual int a(), b;"
6862 if (DS.isVirtualSpecified())
6864 diag::err_virtual_non_function);
6865
6866 if (DS.hasExplicitSpecifier())
6868 diag::err_explicit_non_function);
6869
6870 if (DS.isNoreturnSpecified())
6872 diag::err_noreturn_non_function);
6873}
6874
6875NamedDecl*
6878 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6879 if (D.getCXXScopeSpec().isSet()) {
6880 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6881 << D.getCXXScopeSpec().getRange();
6882 D.setInvalidType();
6883 // Pretend we didn't see the scope specifier.
6884 DC = CurContext;
6885 Previous.clear();
6886 }
6887
6889
6892 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6893 ? diag::warn_ms_inline_non_function
6894 : diag::err_inline_non_function)
6895 << getLangOpts().CPlusPlus17;
6897 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6898 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6899
6903 diag::err_deduction_guide_invalid_specifier)
6904 << "typedef";
6905 else
6906 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6907 << D.getName().getSourceRange();
6908 return nullptr;
6909 }
6910
6911 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6912 if (!NewTD) return nullptr;
6913
6914 // Handle attributes prior to checking for duplicates in MergeVarDecl
6915 ProcessDeclAttributes(S, NewTD, D);
6916
6918
6919 bool Redeclaration = D.isRedeclaration();
6922 return ND;
6923}
6924
6925void
6927 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6928 // then it shall have block scope.
6929 // Note that variably modified types must be fixed before merging the decl so
6930 // that redeclarations will match.
6931 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6932 QualType T = TInfo->getType();
6933 if (T->isVariablyModifiedType()) {
6935
6936 if (S->getFnParent() == nullptr) {
6937 bool SizeIsNegative;
6938 llvm::APSInt Oversized;
6939 TypeSourceInfo *FixedTInfo =
6941 SizeIsNegative,
6942 Oversized);
6943 if (FixedTInfo) {
6944 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6945 NewTD->setTypeSourceInfo(FixedTInfo);
6946 } else {
6947 if (SizeIsNegative)
6948 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6949 else if (T->isVariableArrayType())
6950 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6951 else if (Oversized.getBoolValue())
6952 Diag(NewTD->getLocation(), diag::err_array_too_large)
6953 << toString(Oversized, 10);
6954 else
6955 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6956 NewTD->setInvalidDecl();
6957 }
6958 }
6959 }
6960}
6961
6962NamedDecl*
6965
6966 // Find the shadowed declaration before filtering for scope.
6967 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6968
6969 // Merge the decl with the existing one if appropriate. If the decl is
6970 // in an outer scope, it isn't the same thing.
6971 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6972 /*AllowInlineNamespace*/false);
6974 if (!Previous.empty()) {
6975 Redeclaration = true;
6976 MergeTypedefNameDecl(S, NewTD, Previous);
6977 } else {
6979 }
6980
6981 if (ShadowedDecl && !Redeclaration)
6982 CheckShadow(NewTD, ShadowedDecl, Previous);
6983
6984 // If this is the C FILE type, notify the AST context.
6985 if (IdentifierInfo *II = NewTD->getIdentifier())
6986 if (!NewTD->isInvalidDecl() &&
6988 switch (II->getNotableIdentifierID()) {
6989 case tok::NotableIdentifierKind::FILE:
6990 Context.setFILEDecl(NewTD);
6991 break;
6992 case tok::NotableIdentifierKind::jmp_buf:
6993 Context.setjmp_bufDecl(NewTD);
6994 break;
6995 case tok::NotableIdentifierKind::sigjmp_buf:
6996 Context.setsigjmp_bufDecl(NewTD);
6997 break;
6998 case tok::NotableIdentifierKind::ucontext_t:
6999 Context.setucontext_tDecl(NewTD);
7000 break;
7001 case tok::NotableIdentifierKind::float_t:
7002 case tok::NotableIdentifierKind::double_t:
7003 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
7004 break;
7005 default:
7006 break;
7007 }
7008 }
7009
7010 return NewTD;
7011}
7012
7013/// Determines whether the given declaration is an out-of-scope
7014/// previous declaration.
7015///
7016/// This routine should be invoked when name lookup has found a
7017/// previous declaration (PrevDecl) that is not in the scope where a
7018/// new declaration by the same name is being introduced. If the new
7019/// declaration occurs in a local scope, previous declarations with
7020/// linkage may still be considered previous declarations (C99
7021/// 6.2.2p4-5, C++ [basic.link]p6).
7022///
7023/// \param PrevDecl the previous declaration found by name
7024/// lookup
7025///
7026/// \param DC the context in which the new declaration is being
7027/// declared.
7028///
7029/// \returns true if PrevDecl is an out-of-scope previous declaration
7030/// for a new delcaration with the same name.
7031static bool
7033 ASTContext &Context) {
7034 if (!PrevDecl)
7035 return false;
7036
7037 if (!PrevDecl->hasLinkage())
7038 return false;
7039
7040 if (Context.getLangOpts().CPlusPlus) {
7041 // C++ [basic.link]p6:
7042 // If there is a visible declaration of an entity with linkage
7043 // having the same name and type, ignoring entities declared
7044 // outside the innermost enclosing namespace scope, the block
7045 // scope declaration declares that same entity and receives the
7046 // linkage of the previous declaration.
7047 DeclContext *OuterContext = DC->getRedeclContext();
7048 if (!OuterContext->isFunctionOrMethod())
7049 // This rule only applies to block-scope declarations.
7050 return false;
7051
7052 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7053 if (PrevOuterContext->isRecord())
7054 // We found a member function: ignore it.
7055 return false;
7056
7057 // Find the innermost enclosing namespace for the new and
7058 // previous declarations.
7059 OuterContext = OuterContext->getEnclosingNamespaceContext();
7060 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7061
7062 // The previous declaration is in a different namespace, so it
7063 // isn't the same function.
7064 if (!OuterContext->Equals(PrevOuterContext))
7065 return false;
7066 }
7067
7068 return true;
7069}
7070
7072 CXXScopeSpec &SS = D.getCXXScopeSpec();
7073 if (!SS.isSet()) return;
7075}
7076
7079 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7080 // __opencl_c_program_scope_global_variables feature, the address space
7081 // for a variable at program scope or a static or extern variable inside
7082 // a function are inferred to be __global.
7083 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7084 Var->hasGlobalStorage())
7085 ImplAS = LangAS::opencl_global;
7086 Var->assignAddressSpace(Context, ImplAS);
7087}
7088
7089static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7090 // 'weak' only applies to declarations with external linkage.
7091 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7092 if (!ND.isExternallyVisible()) {
7093 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7094 ND.dropAttr<WeakAttr>();
7095 }
7096 }
7097}
7098
7099static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7100 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7101 if (ND.isExternallyVisible()) {
7102 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7103 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7104 }
7105 }
7106}
7107
7108static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7109 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7110 if (VD->hasInit()) {
7111 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7112 assert(VD->isThisDeclarationADefinition() &&
7113 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7114 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7115 VD->dropAttr<AliasAttr>();
7116 }
7117 }
7118 }
7119}
7120
7121static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7122 // 'selectany' only applies to externally visible variable declarations.
7123 // It does not apply to functions.
7124 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7125 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7126 S.Diag(Attr->getLocation(),
7127 diag::err_attribute_selectany_non_extern_data);
7128 ND.dropAttr<SelectAnyAttr>();
7129 }
7130 }
7131}
7132
7134 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7135 if (!ND.isExternallyVisible())
7136 S.Diag(Attr->getLocation(),
7137 diag::warn_attribute_hybrid_patchable_non_extern);
7138 }
7139}
7140
7142 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7143 auto *VD = dyn_cast<VarDecl>(&ND);
7144 bool IsAnonymousNS = false;
7145 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7146 if (VD) {
7147 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7148 while (NS && !IsAnonymousNS) {
7149 IsAnonymousNS = NS->isAnonymousNamespace();
7150 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7151 }
7152 }
7153 // dll attributes require external linkage. Static locals may have external
7154 // linkage but still cannot be explicitly imported or exported.
7155 // In Microsoft mode, a variable defined in anonymous namespace must have
7156 // external linkage in order to be exported.
7157 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7158 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7159 (!AnonNSInMicrosoftMode &&
7160 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7161 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7162 << &ND << Attr;
7163 ND.setInvalidDecl();
7164 }
7165 }
7166}
7167
7169 // Check the attributes on the function type and function params, if any.
7170 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7171 FD = FD->getMostRecentDecl();
7172 // Don't declare this variable in the second operand of the for-statement;
7173 // GCC miscompiles that by ending its lifetime before evaluating the
7174 // third operand. See gcc.gnu.org/PR86769.
7176 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7177 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7178 TL = ATL.getModifiedLoc()) {
7179 // The [[lifetimebound]] attribute can be applied to the implicit object
7180 // parameter of a non-static member function (other than a ctor or dtor)
7181 // by applying it to the function type.
7182 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7183 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7184 int NoImplicitObjectError = -1;
7185 if (!MD)
7186 NoImplicitObjectError = 0;
7187 else if (MD->isStatic())
7188 NoImplicitObjectError = 1;
7189 else if (MD->isExplicitObjectMemberFunction())
7190 NoImplicitObjectError = 2;
7191 if (NoImplicitObjectError != -1) {
7192 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7193 << NoImplicitObjectError << A->getRange();
7194 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7195 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7196 << isa<CXXDestructorDecl>(MD) << A->getRange();
7197 } else if (MD->getReturnType()->isVoidType()) {
7198 S.Diag(
7199 MD->getLocation(),
7200 diag::
7201 err_lifetimebound_implicit_object_parameter_void_return_type);
7202 }
7203 }
7204 }
7205
7206 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7207 const ParmVarDecl *P = FD->getParamDecl(I);
7208
7209 // The [[lifetimebound]] attribute can be applied to a function parameter
7210 // only if the function returns a value.
7211 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7212 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7213 S.Diag(A->getLocation(),
7214 diag::err_lifetimebound_parameter_void_return_type);
7215 }
7216 }
7217 }
7218 }
7219}
7220
7222 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7223 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7224}
7225
7227 // Ensure that an auto decl is deduced otherwise the checks below might cache
7228 // the wrong linkage.
7229 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7230
7231 checkWeakAttr(S, ND);
7232 checkWeakRefAttr(S, ND);
7233 checkAliasAttr(S, ND);
7234 checkSelectAnyAttr(S, ND);
7236 checkInheritableAttr(S, ND);
7239}
7240
7242 NamedDecl *NewDecl,
7243 bool IsSpecialization,
7244 bool IsDefinition) {
7245 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7246 return;
7247
7248 bool IsTemplate = false;
7249 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7250 OldDecl = OldTD->getTemplatedDecl();
7251 IsTemplate = true;
7252 if (!IsSpecialization)
7253 IsDefinition = false;
7254 }
7255 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7256 NewDecl = NewTD->getTemplatedDecl();
7257 IsTemplate = true;
7258 }
7259
7260 if (!OldDecl || !NewDecl)
7261 return;
7262
7263 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7264 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7265 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7266 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7267
7268 // dllimport and dllexport are inheritable attributes so we have to exclude
7269 // inherited attribute instances.
7270 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7271 (NewExportAttr && !NewExportAttr->isInherited());
7272
7273 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7274 // the only exception being explicit specializations.
7275 // Implicitly generated declarations are also excluded for now because there
7276 // is no other way to switch these to use dllimport or dllexport.
7277 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7278
7279 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7280 // Allow with a warning for free functions and global variables.
7281 bool JustWarn = false;
7282 if (!OldDecl->isCXXClassMember()) {
7283 auto *VD = dyn_cast<VarDecl>(OldDecl);
7284 if (VD && !VD->getDescribedVarTemplate())
7285 JustWarn = true;
7286 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7287 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7288 JustWarn = true;
7289 }
7290
7291 // We cannot change a declaration that's been used because IR has already
7292 // been emitted. Dllimported functions will still work though (modulo
7293 // address equality) as they can use the thunk.
7294 if (OldDecl->isUsed())
7295 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7296 JustWarn = false;
7297
7298 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7299 : diag::err_attribute_dll_redeclaration;
7300 S.Diag(NewDecl->getLocation(), DiagID)
7301 << NewDecl
7302 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7303 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7304 if (!JustWarn) {
7305 NewDecl->setInvalidDecl();
7306 return;
7307 }
7308 }
7309
7310 // A redeclaration is not allowed to drop a dllimport attribute, the only
7311 // exceptions being inline function definitions (except for function
7312 // templates), local extern declarations, qualified friend declarations or
7313 // special MSVC extension: in the last case, the declaration is treated as if
7314 // it were marked dllexport.
7315 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7316 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7317 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7318 // Ignore static data because out-of-line definitions are diagnosed
7319 // separately.
7320 IsStaticDataMember = VD->isStaticDataMember();
7321 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7323 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7324 IsInline = FD->isInlined();
7325 IsQualifiedFriend = FD->getQualifier() &&
7326 FD->getFriendObjectKind() == Decl::FOK_Declared;
7327 }
7328
7329 if (OldImportAttr && !HasNewAttr &&
7330 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7331 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7332 if (IsMicrosoftABI && IsDefinition) {
7333 if (IsSpecialization) {
7334 S.Diag(
7335 NewDecl->getLocation(),
7336 diag::err_attribute_dllimport_function_specialization_definition);
7337 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7338 NewDecl->dropAttr<DLLImportAttr>();
7339 } else {
7340 S.Diag(NewDecl->getLocation(),
7341 diag::warn_redeclaration_without_import_attribute)
7342 << NewDecl;
7343 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7344 NewDecl->dropAttr<DLLImportAttr>();
7345 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7346 S.Context, NewImportAttr->getRange()));
7347 }
7348 } else if (IsMicrosoftABI && IsSpecialization) {
7349 assert(!IsDefinition);
7350 // MSVC allows this. Keep the inherited attribute.
7351 } else {
7352 S.Diag(NewDecl->getLocation(),
7353 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7354 << NewDecl << OldImportAttr;
7355 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7356 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7357 OldDecl->dropAttr<DLLImportAttr>();
7358 NewDecl->dropAttr<DLLImportAttr>();
7359 }
7360 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7361 // In MinGW, seeing a function declared inline drops the dllimport
7362 // attribute.
7363 OldDecl->dropAttr<DLLImportAttr>();
7364 NewDecl->dropAttr<DLLImportAttr>();
7365 S.Diag(NewDecl->getLocation(),
7366 diag::warn_dllimport_dropped_from_inline_function)
7367 << NewDecl << OldImportAttr;
7368 }
7369
7370 // A specialization of a class template member function is processed here
7371 // since it's a redeclaration. If the parent class is dllexport, the
7372 // specialization inherits that attribute. This doesn't happen automatically
7373 // since the parent class isn't instantiated until later.
7374 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7375 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7376 !NewImportAttr && !NewExportAttr) {
7377 if (const DLLExportAttr *ParentExportAttr =
7378 MD->getParent()->getAttr<DLLExportAttr>()) {
7379 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7380 NewAttr->setInherited(true);
7381 NewDecl->addAttr(NewAttr);
7382 }
7383 }
7384 }
7385}
7386
7387/// Given that we are within the definition of the given function,
7388/// will that definition behave like C99's 'inline', where the
7389/// definition is discarded except for optimization purposes?
7391 // Try to avoid calling GetGVALinkageForFunction.
7392
7393 // All cases of this require the 'inline' keyword.
7394 if (!FD->isInlined()) return false;
7395
7396 // This is only possible in C++ with the gnu_inline attribute.
7397 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7398 return false;
7399
7400 // Okay, go ahead and call the relatively-more-expensive function.
7402}
7403
7404/// Determine whether a variable is extern "C" prior to attaching
7405/// an initializer. We can't just call isExternC() here, because that
7406/// will also compute and cache whether the declaration is externally
7407/// visible, which might change when we attach the initializer.
7408///
7409/// This can only be used if the declaration is known to not be a
7410/// redeclaration of an internal linkage declaration.
7411///
7412/// For instance:
7413///
7414/// auto x = []{};
7415///
7416/// Attaching the initializer here makes this declaration not externally
7417/// visible, because its type has internal linkage.
7418///
7419/// FIXME: This is a hack.
7420template<typename T>
7421static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7422 if (S.getLangOpts().CPlusPlus) {
7423 // In C++, the overloadable attribute negates the effects of extern "C".
7424 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7425 return false;
7426
7427 // So do CUDA's host/device attributes.
7428 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7429 D->template hasAttr<CUDAHostAttr>()))
7430 return false;
7431 }
7432 return D->isExternC();
7433}
7434
7435static bool shouldConsiderLinkage(const VarDecl *VD) {
7436 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7439 return VD->hasExternalStorage();
7440 if (DC->isFileContext())
7441 return true;
7442 if (DC->isRecord())
7443 return false;
7444 if (DC->getDeclKind() == Decl::HLSLBuffer)
7445 return false;
7446
7448 return false;
7449 llvm_unreachable("Unexpected context");
7450}
7451
7452static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7453 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7454 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7456 return true;
7457 if (DC->isRecord())
7458 return false;
7459 llvm_unreachable("Unexpected context");
7460}
7461
7462static bool hasParsedAttr(Scope *S, const Declarator &PD,
7463 ParsedAttr::Kind Kind) {
7464 // Check decl attributes on the DeclSpec.
7465 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7466 return true;
7467
7468 // Walk the declarator structure, checking decl attributes that were in a type
7469 // position to the decl itself.
7470 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7471 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7472 return true;
7473 }
7474
7475 // Finally, check attributes on the decl itself.
7476 return PD.getAttributes().hasAttribute(Kind) ||
7478}
7479
7481 if (!DC->isFunctionOrMethod())
7482 return false;
7483
7484 // If this is a local extern function or variable declared within a function
7485 // template, don't add it into the enclosing namespace scope until it is
7486 // instantiated; it might have a dependent type right now.
7487 if (DC->isDependentContext())
7488 return true;
7489
7490 // C++11 [basic.link]p7:
7491 // When a block scope declaration of an entity with linkage is not found to
7492 // refer to some other declaration, then that entity is a member of the
7493 // innermost enclosing namespace.
7494 //
7495 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7496 // semantically-enclosing namespace, not a lexically-enclosing one.
7497 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7498 DC = DC->getParent();
7499 return true;
7500}
7501
7502/// Returns true if given declaration has external C language linkage.
7503static bool isDeclExternC(const Decl *D) {
7504 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7505 return FD->isExternC();
7506 if (const auto *VD = dyn_cast<VarDecl>(D))
7507 return VD->isExternC();
7508
7509 llvm_unreachable("Unknown type of decl!");
7510}
7511
7512/// Returns true if there hasn't been any invalid type diagnosed.
7513static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7514 DeclContext *DC = NewVD->getDeclContext();
7515 QualType R = NewVD->getType();
7516
7517 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7518 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7519 // argument.
7520 if (R->isImageType() || R->isPipeType()) {
7521 Se.Diag(NewVD->getLocation(),
7522 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7523 << R;
7524 NewVD->setInvalidDecl();
7525 return false;
7526 }
7527
7528 // OpenCL v1.2 s6.9.r:
7529 // The event type cannot be used to declare a program scope variable.
7530 // OpenCL v2.0 s6.9.q:
7531 // The clk_event_t and reserve_id_t types cannot be declared in program
7532 // scope.
7533 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7534 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7535 Se.Diag(NewVD->getLocation(),
7536 diag::err_invalid_type_for_program_scope_var)
7537 << R;
7538 NewVD->setInvalidDecl();
7539 return false;
7540 }
7541 }
7542
7543 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7544 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7545 Se.getLangOpts())) {
7546 QualType NR = R.getCanonicalType();
7547 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7548 NR->isReferenceType()) {
7551 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7552 << NR->isReferenceType();
7553 NewVD->setInvalidDecl();
7554 return false;
7555 }
7556 NR = NR->getPointeeType();
7557 }
7558 }
7559
7560 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7561 Se.getLangOpts())) {
7562 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7563 // half array type (unless the cl_khr_fp16 extension is enabled).
7564 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7565 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7566 NewVD->setInvalidDecl();
7567 return false;
7568 }
7569 }
7570
7571 // OpenCL v1.2 s6.9.r:
7572 // The event type cannot be used with the __local, __constant and __global
7573 // address space qualifiers.
7574 if (R->isEventT()) {
7575 if (R.getAddressSpace() != LangAS::opencl_private) {
7576 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7577 NewVD->setInvalidDecl();
7578 return false;
7579 }
7580 }
7581
7582 if (R->isSamplerT()) {
7583 // OpenCL v1.2 s6.9.b p4:
7584 // The sampler type cannot be used with the __local and __global address
7585 // space qualifiers.
7586 if (R.getAddressSpace() == LangAS::opencl_local ||
7587 R.getAddressSpace() == LangAS::opencl_global) {
7588 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7589 NewVD->setInvalidDecl();
7590 }
7591
7592 // OpenCL v1.2 s6.12.14.1:
7593 // A global sampler must be declared with either the constant address
7594 // space qualifier or with the const qualifier.
7595 if (DC->isTranslationUnit() &&
7596 !(R.getAddressSpace() == LangAS::opencl_constant ||
7597 R.isConstQualified())) {
7598 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7599 NewVD->setInvalidDecl();
7600 }
7601 if (NewVD->isInvalidDecl())
7602 return false;
7603 }
7604
7605 return true;
7606}
7607
7608template <typename AttrTy>
7609static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7610 const TypedefNameDecl *TND = TT->getDecl();
7611 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7612 AttrTy *Clone = Attribute->clone(S.Context);
7613 Clone->setInherited(true);
7614 D->addAttr(Clone);
7615 }
7616}
7617
7618// This function emits warning and a corresponding note based on the
7619// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7620// declarations of an annotated type must be const qualified.
7622 QualType VarType = VD->getType().getCanonicalType();
7623
7624 // Ignore local declarations (for now) and those with const qualification.
7625 // TODO: Local variables should not be allowed if their type declaration has
7626 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7627 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7628 return;
7629
7630 if (VarType->isArrayType()) {
7631 // Retrieve element type for array declarations.
7632 VarType = S.getASTContext().getBaseElementType(VarType);
7633 }
7634
7635 const RecordDecl *RD = VarType->getAsRecordDecl();
7636
7637 // Check if the record declaration is present and if it has any attributes.
7638 if (RD == nullptr)
7639 return;
7640
7641 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7642 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7643 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7644 return;
7645 }
7646}
7647
7649 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7650 "NewD is not a function or variable");
7651
7652 if (PendingExportedNames.empty())
7653 return;
7654 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(NewD)) {
7655 if (getLangOpts().CPlusPlus && !FD->isExternC())
7656 return;
7657 }
7658 IdentifierInfo *IdentName = NewD->getIdentifier();
7659 if (IdentName == nullptr)
7660 return;
7661 auto PendingName = PendingExportedNames.find(IdentName);
7662 if (PendingName != PendingExportedNames.end()) {
7663 auto &Label = PendingName->second;
7664 if (!Label.Used) {
7665 Label.Used = true;
7666 if (NewD->hasExternalFormalLinkage())
7667 mergeVisibilityType(NewD, Label.NameLoc, VisibilityAttr::Default);
7668 else
7669 Diag(Label.NameLoc, diag::warn_pragma_not_applied) << "export" << NewD;
7670 }
7671 }
7672}
7673
7674// Checks if VD is declared at global scope or with C language linkage.
7675static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7676 return Name.getAsIdentifierInfo() &&
7677 Name.getAsIdentifierInfo()->isStr("main") &&
7678 !VD->getDescribedVarTemplate() &&
7679 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7680 VD->isExternC());
7681}
7682
7683void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7684 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7685
7686 // Quickly return if the function does not have an `asm` attribute.
7687 if (E == nullptr)
7688 return;
7689
7690 // The parser guarantees this is a string.
7691 StringLiteral *SE = cast<StringLiteral>(E);
7692 StringRef Label = SE->getString();
7693 QualType R = TInfo->getType();
7694 if (S->getFnParent() != nullptr) {
7695 switch (SC) {
7696 case SC_None:
7697 case SC_Auto:
7698 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7699 break;
7700 case SC_Register:
7701 // Local Named register
7702 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7704 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7705 break;
7706 case SC_Static:
7707 case SC_Extern:
7708 case SC_PrivateExtern:
7709 break;
7710 }
7711 } else if (SC == SC_Register) {
7712 // Global Named register
7713 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7714 const auto &TI = Context.getTargetInfo();
7715 bool HasSizeMismatch;
7716
7717 if (!TI.isValidGCCRegisterName(Label))
7718 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7719 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7720 HasSizeMismatch))
7721 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7722 else if (HasSizeMismatch)
7723 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7724 }
7725
7726 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7727 Diag(TInfo->getTypeLoc().getBeginLoc(),
7728 diag::err_asm_unsupported_register_type)
7729 << TInfo->getTypeLoc().getSourceRange();
7730 NewVD->setInvalidDecl(true);
7731 }
7732 }
7733}
7734
7736 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7737 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7738 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7739 QualType R = TInfo->getType();
7741
7743 bool IsPlaceholderVariable = false;
7744
7745 if (D.isDecompositionDeclarator()) {
7746 // Take the name of the first declarator as our name for diagnostic
7747 // purposes.
7748 auto &Decomp = D.getDecompositionDeclarator();
7749 if (!Decomp.bindings().empty()) {
7750 II = Decomp.bindings()[0].Name;
7751 Name = II;
7752 }
7753 } else if (!II) {
7754 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7755 return nullptr;
7756 }
7757
7758
7761 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7762 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7763
7764 IsPlaceholderVariable = true;
7765
7766 if (!Previous.empty()) {
7767 NamedDecl *PrevDecl = *Previous.begin();
7768 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7769 DC->getRedeclContext());
7770 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7771 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7772 if (IsPlaceholderVariable)
7774 }
7775 }
7776 }
7777
7778 // dllimport globals without explicit storage class are treated as extern. We
7779 // have to change the storage class this early to get the right DeclContext.
7780 if (SC == SC_None && !DC->isRecord() &&
7781 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7782 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7783 SC = SC_Extern;
7784
7785 DeclContext *OriginalDC = DC;
7786 bool IsLocalExternDecl = SC == SC_Extern &&
7788
7789 if (SCSpec == DeclSpec::SCS_mutable) {
7790 // mutable can only appear on non-static class members, so it's always
7791 // an error here
7792 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7793 D.setInvalidType();
7794 SC = SC_None;
7795 }
7796
7797 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7798 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7800 // In C++11, the 'register' storage class specifier is deprecated.
7801 // Suppress the warning in system macros, it's used in macros in some
7802 // popular C system headers, such as in glibc's htonl() macro.
7804 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7805 : diag::warn_deprecated_register)
7807 }
7808
7810
7811 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7812 // C99 6.9p2: The storage-class specifiers auto and register shall not
7813 // appear in the declaration specifiers in an external declaration.
7814 // Global Register+Asm is a GNU extension we support.
7815 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7816 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7817 D.setInvalidType();
7818 }
7819 }
7820
7821 // If this variable has a VLA type and an initializer, try to
7822 // fold to a constant-sized type. This is otherwise invalid.
7823 if (D.hasInitializer() && R->isVariableArrayType())
7825 /*DiagID=*/0);
7826
7827 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7828 const AutoType *AT = TL.getTypePtr();
7829 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7830 }
7831
7832 bool IsMemberSpecialization = false;
7833 bool IsVariableTemplateSpecialization = false;
7834 bool IsPartialSpecialization = false;
7835 bool IsVariableTemplate = false;
7836 VarDecl *NewVD = nullptr;
7837 VarTemplateDecl *NewTemplate = nullptr;
7838 TemplateParameterList *TemplateParams = nullptr;
7839 if (!getLangOpts().CPlusPlus) {
7841 II, R, TInfo, SC);
7842
7843 if (R->getContainedDeducedType())
7844 ParsingInitForAutoVars.insert(NewVD);
7845
7846 if (D.isInvalidType())
7847 NewVD->setInvalidDecl();
7848
7850 NewVD->hasLocalStorage())
7851 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7853 } else {
7854 bool Invalid = false;
7855 // Match up the template parameter lists with the scope specifier, then
7856 // determine whether we have a template or a template specialization.
7859 D.getCXXScopeSpec(),
7861 ? D.getName().TemplateId
7862 : nullptr,
7863 TemplateParamLists,
7864 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7865
7866 if (TemplateParams) {
7867 if (DC->isDependentContext()) {
7868 ContextRAII SavedContext(*this, DC);
7870 Invalid = true;
7871 }
7872
7873 if (!TemplateParams->size() &&
7875 // There is an extraneous 'template<>' for this variable. Complain
7876 // about it, but allow the declaration of the variable.
7877 Diag(TemplateParams->getTemplateLoc(),
7878 diag::err_template_variable_noparams)
7879 << II
7880 << SourceRange(TemplateParams->getTemplateLoc(),
7881 TemplateParams->getRAngleLoc());
7882 TemplateParams = nullptr;
7883 } else {
7884 // Check that we can declare a template here.
7885 if (CheckTemplateDeclScope(S, TemplateParams))
7886 return nullptr;
7887
7889 // This is an explicit specialization or a partial specialization.
7890 IsVariableTemplateSpecialization = true;
7891 IsPartialSpecialization = TemplateParams->size() > 0;
7892 } else { // if (TemplateParams->size() > 0)
7893 // This is a template declaration.
7894 IsVariableTemplate = true;
7895
7896 // Only C++1y supports variable templates (N3651).
7897 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7898 }
7899 }
7900 } else {
7901 // Check that we can declare a member specialization here.
7902 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7903 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7904 return nullptr;
7905 assert((Invalid ||
7907 "should have a 'template<>' for this decl");
7908 }
7909
7910 bool IsExplicitSpecialization =
7911 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7912
7913 // C++ [temp.expl.spec]p2:
7914 // The declaration in an explicit-specialization shall not be an
7915 // export-declaration. An explicit specialization shall not use a
7916 // storage-class-specifier other than thread_local.
7917 //
7918 // We use the storage-class-specifier from DeclSpec because we may have
7919 // added implicit 'extern' for declarations with __declspec(dllimport)!
7920 if (SCSpec != DeclSpec::SCS_unspecified &&
7921 (IsExplicitSpecialization || IsMemberSpecialization)) {
7923 diag::ext_explicit_specialization_storage_class)
7925 }
7926
7927 if (CurContext->isRecord()) {
7928 if (SC == SC_Static) {
7929 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7930 // Walk up the enclosing DeclContexts to check for any that are
7931 // incompatible with static data members.
7932 const DeclContext *FunctionOrMethod = nullptr;
7933 const CXXRecordDecl *AnonStruct = nullptr;
7934 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7935 if (Ctxt->isFunctionOrMethod()) {
7936 FunctionOrMethod = Ctxt;
7937 break;
7938 }
7939 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7940 if (ParentDecl && !ParentDecl->getDeclName()) {
7941 AnonStruct = ParentDecl;
7942 break;
7943 }
7944 }
7945 if (FunctionOrMethod) {
7946 // C++ [class.static.data]p5: A local class shall not have static
7947 // data members.
7949 diag::err_static_data_member_not_allowed_in_local_class)
7950 << Name << RD->getDeclName() << RD->getTagKind();
7951 } else if (AnonStruct) {
7952 // C++ [class.static.data]p4: Unnamed classes and classes contained
7953 // directly or indirectly within unnamed classes shall not contain
7954 // static data members.
7956 diag::err_static_data_member_not_allowed_in_anon_struct)
7957 << Name << AnonStruct->getTagKind();
7958 Invalid = true;
7959 } else if (RD->isUnion()) {
7960 // C++98 [class.union]p1: If a union contains a static data member,
7961 // the program is ill-formed. C++11 drops this restriction.
7963 diag_compat::static_data_member_in_union)
7964 << Name;
7965 }
7966 }
7967 } else if (IsVariableTemplate || IsPartialSpecialization) {
7968 // There is no such thing as a member field template.
7969 Diag(D.getIdentifierLoc(), diag::err_template_member)
7970 << II << TemplateParams->getSourceRange();
7971 // Recover by pretending this is a static data member template.
7972 SC = SC_Static;
7973 }
7974 } else if (DC->isRecord()) {
7975 // This is an out-of-line definition of a static data member.
7976 switch (SC) {
7977 case SC_None:
7978 break;
7979 case SC_Static:
7981 diag::err_static_out_of_line)
7984 break;
7985 case SC_Auto:
7986 case SC_Register:
7987 case SC_Extern:
7988 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7989 // to names of variables declared in a block or to function parameters.
7990 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7991 // of class members
7992
7994 diag::err_storage_class_for_static_member)
7997 break;
7998 case SC_PrivateExtern:
7999 llvm_unreachable("C storage class in c++!");
8000 }
8001 }
8002
8003 if (IsVariableTemplateSpecialization) {
8004 SourceLocation TemplateKWLoc =
8005 TemplateParamLists.size() > 0
8006 ? TemplateParamLists[0]->getTemplateLoc()
8007 : SourceLocation();
8009 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8011 if (Res.isInvalid())
8012 return nullptr;
8013 NewVD = cast<VarDecl>(Res.get());
8014 AddToScope = false;
8015 } else if (D.isDecompositionDeclarator()) {
8017 D.getIdentifierLoc(), R, TInfo, SC,
8018 Bindings);
8019 } else
8020 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
8021 D.getIdentifierLoc(), II, R, TInfo, SC);
8022
8023 // If this is supposed to be a variable template, create it as such.
8024 if (IsVariableTemplate) {
8025 NewTemplate =
8027 TemplateParams, NewVD);
8028 NewVD->setDescribedVarTemplate(NewTemplate);
8029 }
8030
8031 // If this decl has an auto type in need of deduction, make a note of the
8032 // Decl so we can diagnose uses of it in its own initializer.
8033 if (R->getContainedDeducedType())
8034 ParsingInitForAutoVars.insert(NewVD);
8035
8036 if (D.isInvalidType() || Invalid) {
8037 NewVD->setInvalidDecl();
8038 if (NewTemplate)
8039 NewTemplate->setInvalidDecl();
8040 }
8041
8042 SetNestedNameSpecifier(*this, NewVD, D);
8043
8044 // If we have any template parameter lists that don't directly belong to
8045 // the variable (matching the scope specifier), store them.
8046 // An explicit variable template specialization does not own any template
8047 // parameter lists.
8048 unsigned VDTemplateParamLists =
8049 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8050 if (TemplateParamLists.size() > VDTemplateParamLists)
8052 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8053 }
8054
8055 if (D.getDeclSpec().isInlineSpecified()) {
8056 if (!getLangOpts().CPlusPlus) {
8057 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8058 << 0;
8059 } else if (CurContext->isFunctionOrMethod()) {
8060 // 'inline' is not allowed on block scope variable declaration.
8062 diag::err_inline_declaration_block_scope) << Name
8064 } else {
8066 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8067 : diag::compat_pre_cxx17_inline_variable);
8068 NewVD->setInlineSpecified();
8069 }
8070 }
8071
8072 // Set the lexical context. If the declarator has a C++ scope specifier, the
8073 // lexical context will be different from the semantic context.
8075 if (NewTemplate)
8076 NewTemplate->setLexicalDeclContext(CurContext);
8077
8078 if (IsLocalExternDecl) {
8080 for (auto *B : Bindings)
8081 B->setLocalExternDecl();
8082 else
8083 NewVD->setLocalExternDecl();
8084 }
8085
8086 bool EmitTLSUnsupportedError = false;
8088 // C++11 [dcl.stc]p4:
8089 // When thread_local is applied to a variable of block scope the
8090 // storage-class-specifier static is implied if it does not appear
8091 // explicitly.
8092 // Core issue: 'static' is not implied if the variable is declared
8093 // 'extern'.
8094 if (NewVD->hasLocalStorage() &&
8095 (SCSpec != DeclSpec::SCS_unspecified ||
8097 !DC->isFunctionOrMethod()))
8099 diag::err_thread_non_global)
8101 else if (!Context.getTargetInfo().isTLSSupported()) {
8102 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8103 // Postpone error emission until we've collected attributes required to
8104 // figure out whether it's a host or device variable and whether the
8105 // error should be ignored.
8106 EmitTLSUnsupportedError = true;
8107 // We still need to mark the variable as TLS so it shows up in AST with
8108 // proper storage class for other tools to use even if we're not going
8109 // to emit any code for it.
8110 NewVD->setTSCSpec(TSCS);
8111 } else
8113 diag::err_thread_unsupported);
8114 } else
8115 NewVD->setTSCSpec(TSCS);
8116 }
8117
8118 switch (D.getDeclSpec().getConstexprSpecifier()) {
8120 break;
8121
8124 diag::err_constexpr_wrong_decl_kind)
8125 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8126 [[fallthrough]];
8127
8129 NewVD->setConstexpr(true);
8130 // C++1z [dcl.spec.constexpr]p1:
8131 // A static data member declared with the constexpr specifier is
8132 // implicitly an inline variable.
8133 if (NewVD->isStaticDataMember() &&
8135 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8136 NewVD->setImplicitlyInline();
8137 break;
8138
8140 if (!NewVD->hasGlobalStorage())
8142 diag::err_constinit_local_variable);
8143 else
8144 NewVD->addAttr(
8145 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8146 ConstInitAttr::Keyword_constinit));
8147 break;
8148 }
8149
8150 // C99 6.7.4p3
8151 // An inline definition of a function with external linkage shall
8152 // not contain a definition of a modifiable object with static or
8153 // thread storage duration...
8154 // We only apply this when the function is required to be defined
8155 // elsewhere, i.e. when the function is not 'extern inline'. Note
8156 // that a local variable with thread storage duration still has to
8157 // be marked 'static'. Also note that it's possible to get these
8158 // semantics in C++ using __attribute__((gnu_inline)).
8159 if (SC == SC_Static && S->getFnParent() != nullptr &&
8160 !NewVD->getType().isConstQualified()) {
8162 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8164 diag::warn_static_local_in_extern_inline);
8166 }
8167 }
8168
8170 if (IsVariableTemplateSpecialization)
8171 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8172 << (IsPartialSpecialization ? 1 : 0)
8175 else if (IsMemberSpecialization)
8176 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8177 << 2
8179 else if (NewVD->hasLocalStorage())
8180 Diag(NewVD->getLocation(), diag::err_module_private_local)
8181 << 0 << NewVD
8185 else {
8186 NewVD->setModulePrivate();
8187 if (NewTemplate)
8188 NewTemplate->setModulePrivate();
8189 for (auto *B : Bindings)
8190 B->setModulePrivate();
8191 }
8192 }
8193
8194 if (getLangOpts().OpenCL) {
8196
8198 if (TSC != TSCS_unspecified) {
8200 diag::err_opencl_unknown_type_specifier)
8202 << DeclSpec::getSpecifierName(TSC) << 1;
8203 NewVD->setInvalidDecl();
8204 }
8205 }
8206
8207 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8208 // address space if the table has local storage (semantic checks elsewhere
8209 // will produce an error anyway).
8210 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8211 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8212 !NewVD->hasLocalStorage()) {
8213 QualType Type = Context.getAddrSpaceQualType(
8214 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8215 NewVD->setType(Type);
8216 }
8217 }
8218
8220
8221 if (Expr *E = D.getAsmLabel()) {
8222 // The parser guarantees this is a string.
8224 StringRef Label = SE->getString();
8225
8226 // Insert the asm attribute.
8227 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8228 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8229 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8231 if (I != ExtnameUndeclaredIdentifiers.end()) {
8232 if (isDeclExternC(NewVD)) {
8233 NewVD->addAttr(I->second);
8235 } else if (NewVD->getDeclContext()
8238 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8239 << /*Variable*/ 1 << NewVD;
8240 }
8241 }
8242
8243 // Handle attributes prior to checking for duplicates in MergeVarDecl
8244 ProcessDeclAttributes(S, NewVD, D);
8245
8246 if (getLangOpts().HLSL)
8248
8249 if (getLangOpts().OpenACC)
8251
8252 // FIXME: This is probably the wrong location to be doing this and we should
8253 // probably be doing this for more attributes (especially for function
8254 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8255 // the code to copy attributes would be generated by TableGen.
8256 if (R->isFunctionPointerType())
8257 if (const auto *TT = R->getAs<TypedefType>())
8259
8260 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8261 if (EmitTLSUnsupportedError &&
8263 (getLangOpts().OpenMPIsTargetDevice &&
8264 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8266 diag::err_thread_unsupported);
8267
8268 if (EmitTLSUnsupportedError &&
8269 (LangOpts.SYCLIsDevice ||
8270 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8271 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8272 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8273 // storage [duration]."
8274 if (SC == SC_None && S->getFnParent() != nullptr &&
8275 (NewVD->hasAttr<CUDASharedAttr>() ||
8276 NewVD->hasAttr<CUDAConstantAttr>())) {
8277 NewVD->setStorageClass(SC_Static);
8278 }
8279 }
8280
8281 // Ensure that dllimport globals without explicit storage class are treated as
8282 // extern. The storage class is set above using parsed attributes. Now we can
8283 // check the VarDecl itself.
8284 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8285 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8286 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8287
8288 // In auto-retain/release, infer strong retension for variables of
8289 // retainable type.
8290 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8291 NewVD->setInvalidDecl();
8292
8293 // Check the ASM label here, as we need to know all other attributes of the
8294 // Decl first. Otherwise, we can't know if the asm label refers to the
8295 // host or device in a CUDA context. The device has other registers than
8296 // host and we must know where the function will be placed.
8297 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8298
8299 // Find the shadowed declaration before filtering for scope.
8300 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8302 : nullptr;
8303
8304 // Don't consider existing declarations that are in a different
8305 // scope and are out-of-semantic-context declarations (if the new
8306 // declaration has linkage).
8309 IsMemberSpecialization ||
8310 IsVariableTemplateSpecialization);
8311
8312 // Check whether the previous declaration is in the same block scope. This
8313 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8314 if (getLangOpts().CPlusPlus &&
8315 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8317 Previous.isSingleResult() && !Previous.isShadowed() &&
8318 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8319
8320 if (!getLangOpts().CPlusPlus) {
8322 } else {
8323 // If this is an explicit specialization of a static data member, check it.
8324 if (IsMemberSpecialization && !IsVariableTemplate &&
8325 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8327 NewVD->setInvalidDecl();
8328
8329 // Merge the decl with the existing one if appropriate.
8330 if (!Previous.empty()) {
8331 if (Previous.isSingleResult() &&
8332 isa<FieldDecl>(Previous.getFoundDecl()) &&
8333 D.getCXXScopeSpec().isSet()) {
8334 // The user tried to define a non-static data member
8335 // out-of-line (C++ [dcl.meaning]p1).
8336 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8337 << D.getCXXScopeSpec().getRange();
8338 Previous.clear();
8339 NewVD->setInvalidDecl();
8340 }
8341 } else if (D.getCXXScopeSpec().isSet() &&
8342 !IsVariableTemplateSpecialization) {
8343 // No previous declaration in the qualifying scope.
8344 Diag(D.getIdentifierLoc(), diag::err_no_member)
8345 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8346 << D.getCXXScopeSpec().getRange();
8347 NewVD->setInvalidDecl();
8348 }
8349
8350 if (!IsPlaceholderVariable)
8352
8353 // CheckVariableDeclaration will set NewVD as invalid if something is in
8354 // error like WebAssembly tables being declared as arrays with a non-zero
8355 // size, but then parsing continues and emits further errors on that line.
8356 // To avoid that we check here if it happened and return nullptr.
8357 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8358 return nullptr;
8359
8360 if (NewTemplate) {
8361 VarTemplateDecl *PrevVarTemplate =
8362 NewVD->getPreviousDecl()
8364 : nullptr;
8365
8366 // Check the template parameter list of this declaration, possibly
8367 // merging in the template parameter list from the previous variable
8368 // template declaration.
8370 TemplateParams,
8371 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8372 : nullptr,
8373 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8374 DC->isDependentContext())
8376 : TPC_Other))
8377 NewVD->setInvalidDecl();
8378
8379 // If we are providing an explicit specialization of a static variable
8380 // template, make a note of that.
8381 if (PrevVarTemplate &&
8382 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8383 PrevVarTemplate->setMemberSpecialization();
8384 }
8385 }
8386
8387 // Diagnose shadowed variables iff this isn't a redeclaration.
8388 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8389 CheckShadow(NewVD, ShadowedDecl, Previous);
8390
8391 ProcessPragmaWeak(S, NewVD);
8392 ProcessPragmaExport(NewVD);
8393
8394 // If this is the first declaration of an extern C variable, update
8395 // the map of such variables.
8396 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8397 isIncompleteDeclExternC(*this, NewVD))
8399
8400 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8402 Decl *ManglingContextDecl;
8403 std::tie(MCtx, ManglingContextDecl) =
8405 if (MCtx) {
8406 Context.setManglingNumber(
8407 NewVD, MCtx->getManglingNumber(
8408 NewVD, getMSManglingNumber(getLangOpts(), S)));
8409 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8410 }
8411 }
8412
8413 // Special handling of variable named 'main'.
8414 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8415 // C++ [basic.start.main]p3:
8416 // A program that declares
8417 // - a variable main at global scope, or
8418 // - an entity named main with C language linkage (in any namespace)
8419 // is ill-formed
8420 if (getLangOpts().CPlusPlus)
8421 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8422 << NewVD->isExternC();
8423
8424 // In C, and external-linkage variable named main results in undefined
8425 // behavior.
8426 else if (NewVD->hasExternalFormalLinkage())
8427 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8428 }
8429
8430 if (D.isRedeclaration() && !Previous.empty()) {
8431 NamedDecl *Prev = Previous.getRepresentativeDecl();
8432 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8434 }
8435
8436 if (NewTemplate) {
8437 if (NewVD->isInvalidDecl())
8438 NewTemplate->setInvalidDecl();
8439 ActOnDocumentableDecl(NewTemplate);
8440 return NewTemplate;
8441 }
8442
8443 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8445
8447
8448 return NewVD;
8449}
8450
8451/// Enum describing the %select options in diag::warn_decl_shadow.
8461
8462/// Determine what kind of declaration we're shadowing.
8464 const DeclContext *OldDC) {
8465 if (isa<TypeAliasDecl>(ShadowedDecl))
8466 return SDK_Using;
8467 else if (isa<TypedefDecl>(ShadowedDecl))
8468 return SDK_Typedef;
8469 else if (isa<BindingDecl>(ShadowedDecl))
8470 return SDK_StructuredBinding;
8471 else if (isa<RecordDecl>(OldDC))
8472 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8473
8474 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8475}
8476
8477/// Return the location of the capture if the given lambda captures the given
8478/// variable \p VD, or an invalid source location otherwise.
8480 const ValueDecl *VD) {
8481 for (const Capture &Capture : LSI->Captures) {
8483 return Capture.getLocation();
8484 }
8485 return SourceLocation();
8486}
8487
8489 const LookupResult &R) {
8490 // Only diagnose if we're shadowing an unambiguous field or variable.
8491 if (R.getResultKind() != LookupResultKind::Found)
8492 return false;
8493
8494 // Return false if warning is ignored.
8495 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8496}
8497
8499 const LookupResult &R) {
8501 return nullptr;
8502
8503 // Don't diagnose declarations at file scope.
8504 if (D->hasGlobalStorage() && !D->isStaticLocal())
8505 return nullptr;
8506
8507 NamedDecl *ShadowedDecl = R.getFoundDecl();
8508 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8509 : nullptr;
8510}
8511
8513 const LookupResult &R) {
8514 // Don't warn if typedef declaration is part of a class
8515 if (D->getDeclContext()->isRecord())
8516 return nullptr;
8517
8519 return nullptr;
8520
8521 NamedDecl *ShadowedDecl = R.getFoundDecl();
8522 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8523}
8524
8526 const LookupResult &R) {
8528 return nullptr;
8529
8530 NamedDecl *ShadowedDecl = R.getFoundDecl();
8531 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8532 : nullptr;
8533}
8534
8536 const LookupResult &R) {
8537 DeclContext *NewDC = D->getDeclContext();
8538
8539 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8540 if (const auto *MD =
8541 dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) {
8542 // Fields aren't shadowed in C++ static members or in member functions
8543 // with an explicit object parameter.
8544 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8545 return;
8546 }
8547 // Fields shadowed by constructor parameters are a special case. Usually
8548 // the constructor initializes the field with the parameter.
8549 if (isa<CXXConstructorDecl>(NewDC))
8550 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8551 // Remember that this was shadowed so we can either warn about its
8552 // modification or its existence depending on warning settings.
8553 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8554 return;
8555 }
8556 }
8557
8558 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8559 if (shadowedVar->isExternC()) {
8560 // For shadowing external vars, make sure that we point to the global
8561 // declaration, not a locally scoped extern declaration.
8562 for (auto *I : shadowedVar->redecls())
8563 if (I->isFileVarDecl()) {
8564 ShadowedDecl = I;
8565 break;
8566 }
8567 }
8568
8569 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8570
8571 unsigned WarningDiag = diag::warn_decl_shadow;
8572 SourceLocation CaptureLoc;
8573 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8574 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8575 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8576 // Handle both VarDecl and BindingDecl in lambda contexts
8577 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8578 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8579 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8580 if (RD->getLambdaCaptureDefault() == LCD_None) {
8581 // Try to avoid warnings for lambdas with an explicit capture
8582 // list. Warn only when the lambda captures the shadowed decl
8583 // explicitly.
8584 CaptureLoc = getCaptureLocation(LSI, VD);
8585 if (CaptureLoc.isInvalid())
8586 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8587 } else {
8588 // Remember that this was shadowed so we can avoid the warning if
8589 // the shadowed decl isn't captured and the warning settings allow
8590 // it.
8592 ->ShadowingDecls.push_back({D, VD});
8593 return;
8594 }
8595 }
8596 if (isa<FieldDecl>(ShadowedDecl)) {
8597 // If lambda can capture this, then emit default shadowing warning,
8598 // Otherwise it is not really a shadowing case since field is not
8599 // available in lambda's body.
8600 // At this point we don't know that lambda can capture this, so
8601 // remember that this was shadowed and delay until we know.
8603 ->ShadowingDecls.push_back({D, ShadowedDecl});
8604 return;
8605 }
8606 }
8607 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8608 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8609 bool HasLocalStorage = false;
8610 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8611 HasLocalStorage = VD->hasLocalStorage();
8612 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8613 HasLocalStorage =
8614 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8615
8616 if (HasLocalStorage) {
8617 // A variable can't shadow a local variable or binding in an enclosing
8618 // scope, if they are separated by a non-capturing declaration
8619 // context.
8620 for (DeclContext *ParentDC = NewDC;
8621 ParentDC && !ParentDC->Equals(OldDC);
8622 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8623 // Only block literals, captured statements, and lambda expressions
8624 // can capture; other scopes don't.
8625 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8626 !isLambdaCallOperator(ParentDC))
8627 return;
8628 }
8629 }
8630 }
8631 }
8632 }
8633
8634 // Never warn about shadowing a placeholder variable.
8635 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8636 return;
8637
8638 // Only warn about certain kinds of shadowing for class members.
8639 if (NewDC) {
8640 // In particular, don't warn about shadowing non-class members.
8641 if (NewDC->isRecord() && !OldDC->isRecord())
8642 return;
8643
8644 // Skip shadowing check if we're in a class scope, dealing with an enum
8645 // constant in a different context.
8646 DeclContext *ReDC = NewDC->getRedeclContext();
8647 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8648 return;
8649
8650 // TODO: should we warn about static data members shadowing
8651 // static data members from base classes?
8652
8653 // TODO: don't diagnose for inaccessible shadowed members.
8654 // This is hard to do perfectly because we might friend the
8655 // shadowing context, but that's just a false negative.
8656 }
8657
8658 DeclarationName Name = R.getLookupName();
8659
8660 // Emit warning and note.
8661 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8662 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8663 if (!CaptureLoc.isInvalid())
8664 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8665 << Name << /*explicitly*/ 1;
8666 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8667}
8668
8670 for (const auto &Shadow : LSI->ShadowingDecls) {
8671 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8672 // Try to avoid the warning when the shadowed decl isn't captured.
8673 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8674 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8675 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8676 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8677 Diag(Shadow.VD->getLocation(),
8678 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8679 : diag::warn_decl_shadow)
8680 << Shadow.VD->getDeclName()
8681 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8682 if (CaptureLoc.isValid())
8683 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8684 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8685 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8686 } else if (isa<FieldDecl>(ShadowedDecl)) {
8687 Diag(Shadow.VD->getLocation(),
8688 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8689 : diag::warn_decl_shadow_uncaptured_local)
8690 << Shadow.VD->getDeclName()
8691 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8692 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8693 }
8694 }
8695}
8696
8698 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8699 return;
8700
8701 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8704 LookupName(R, S);
8705 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8706 CheckShadow(D, ShadowedDecl, R);
8707}
8708
8709/// Check if 'E', which is an expression that is about to be modified, refers
8710/// to a constructor parameter that shadows a field.
8712 // Quickly ignore expressions that can't be shadowing ctor parameters.
8713 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8714 return;
8715 E = E->IgnoreParenImpCasts();
8716 auto *DRE = dyn_cast<DeclRefExpr>(E);
8717 if (!DRE)
8718 return;
8719 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8720 auto I = ShadowingDecls.find(D);
8721 if (I == ShadowingDecls.end())
8722 return;
8723 const NamedDecl *ShadowedDecl = I->second;
8724 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8725 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8726 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8727 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8728
8729 // Avoid issuing multiple warnings about the same decl.
8730 ShadowingDecls.erase(I);
8731}
8732
8733/// Check for conflict between this global or extern "C" declaration and
8734/// previous global or extern "C" declarations. This is only used in C++.
8735template<typename T>
8737 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8738 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8739 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8740
8741 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8742 // The common case: this global doesn't conflict with any extern "C"
8743 // declaration.
8744 return false;
8745 }
8746
8747 if (Prev) {
8748 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8749 // Both the old and new declarations have C language linkage. This is a
8750 // redeclaration.
8751 Previous.clear();
8752 Previous.addDecl(Prev);
8753 return true;
8754 }
8755
8756 // This is a global, non-extern "C" declaration, and there is a previous
8757 // non-global extern "C" declaration. Diagnose if this is a variable
8758 // declaration.
8759 if (!isa<VarDecl>(ND))
8760 return false;
8761 } else {
8762 // The declaration is extern "C". Check for any declaration in the
8763 // translation unit which might conflict.
8764 if (IsGlobal) {
8765 // We have already performed the lookup into the translation unit.
8766 IsGlobal = false;
8767 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8768 I != E; ++I) {
8769 if (isa<VarDecl>(*I)) {
8770 Prev = *I;
8771 break;
8772 }
8773 }
8774 } else {
8776 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8777 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8778 I != E; ++I) {
8779 if (isa<VarDecl>(*I)) {
8780 Prev = *I;
8781 break;
8782 }
8783 // FIXME: If we have any other entity with this name in global scope,
8784 // the declaration is ill-formed, but that is a defect: it breaks the
8785 // 'stat' hack, for instance. Only variables can have mangled name
8786 // clashes with extern "C" declarations, so only they deserve a
8787 // diagnostic.
8788 }
8789 }
8790
8791 if (!Prev)
8792 return false;
8793 }
8794
8795 // Use the first declaration's location to ensure we point at something which
8796 // is lexically inside an extern "C" linkage-spec.
8797 assert(Prev && "should have found a previous declaration to diagnose");
8798 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8799 Prev = FD->getFirstDecl();
8800 else
8801 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8802
8803 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8804 << IsGlobal << ND;
8805 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8806 << IsGlobal;
8807 return false;
8808}
8809
8810/// Apply special rules for handling extern "C" declarations. Returns \c true
8811/// if we have found that this is a redeclaration of some prior entity.
8812///
8813/// Per C++ [dcl.link]p6:
8814/// Two declarations [for a function or variable] with C language linkage
8815/// with the same name that appear in different scopes refer to the same
8816/// [entity]. An entity with C language linkage shall not be declared with
8817/// the same name as an entity in global scope.
8818template<typename T>
8821 if (!S.getLangOpts().CPlusPlus) {
8822 // In C, when declaring a global variable, look for a corresponding 'extern'
8823 // variable declared in function scope. We don't need this in C++, because
8824 // we find local extern decls in the surrounding file-scope DeclContext.
8825 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8826 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8827 Previous.clear();
8828 Previous.addDecl(Prev);
8829 return true;
8830 }
8831 }
8832 return false;
8833 }
8834
8835 // A declaration in the translation unit can conflict with an extern "C"
8836 // declaration.
8837 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8838 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8839
8840 // An extern "C" declaration can conflict with a declaration in the
8841 // translation unit or can be a redeclaration of an extern "C" declaration
8842 // in another scope.
8843 if (isIncompleteDeclExternC(S,ND))
8844 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8845
8846 // Neither global nor extern "C": nothing to do.
8847 return false;
8848}
8849
8850static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8851 QualType T) {
8852 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8853 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8854 // any of its members, even recursively, shall not have an atomic type, or a
8855 // variably modified type, or a type that is volatile or restrict qualified.
8856 if (CanonT->isVariablyModifiedType()) {
8857 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8858 return true;
8859 }
8860
8861 // Arrays are qualified by their element type, so get the base type (this
8862 // works on non-arrays as well).
8863 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8864
8865 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8866 CanonT.isRestrictQualified()) {
8867 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8868 return true;
8869 }
8870
8871 if (CanonT->isRecordType()) {
8872 const RecordDecl *RD = CanonT->getAsRecordDecl();
8873 if (!RD->isInvalidDecl() &&
8874 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8875 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8876 }))
8877 return true;
8878 }
8879
8880 return false;
8881}
8882
8884 // If the decl is already known invalid, don't check it.
8885 if (NewVD->isInvalidDecl())
8886 return;
8887
8888 QualType T = NewVD->getType();
8889
8890 // Defer checking an 'auto' type until its initializer is attached.
8891 if (T->isUndeducedType())
8892 return;
8893
8894 if (NewVD->hasAttrs())
8896
8897 if (T->isObjCObjectType()) {
8898 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8899 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8900 T = Context.getObjCObjectPointerType(T);
8901 NewVD->setType(T);
8902 }
8903
8904 // Emit an error if an address space was applied to decl with local storage.
8905 // This includes arrays of objects with address space qualifiers, but not
8906 // automatic variables that point to other address spaces.
8907 // ISO/IEC TR 18037 S5.1.2
8908 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8909 T.getAddressSpace() != LangAS::Default) {
8910 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8911 NewVD->setInvalidDecl();
8912 return;
8913 }
8914
8915 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8916 // scope.
8917 if (getLangOpts().OpenCLVersion == 120 &&
8918 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8919 getLangOpts()) &&
8920 NewVD->isStaticLocal()) {
8921 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8922 NewVD->setInvalidDecl();
8923 return;
8924 }
8925
8926 if (getLangOpts().OpenCL) {
8927 if (!diagnoseOpenCLTypes(*this, NewVD))
8928 return;
8929
8930 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8931 if (NewVD->hasAttr<BlocksAttr>()) {
8932 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8933 return;
8934 }
8935
8936 if (T->isBlockPointerType()) {
8937 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8938 // can't use 'extern' storage class.
8939 if (!T.isConstQualified()) {
8940 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8941 << 0 /*const*/;
8942 NewVD->setInvalidDecl();
8943 return;
8944 }
8945 if (NewVD->hasExternalStorage()) {
8946 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8947 NewVD->setInvalidDecl();
8948 return;
8949 }
8950 }
8951
8952 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8953 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8954 NewVD->hasExternalStorage()) {
8955 if (!T->isSamplerT() && !T->isDependentType() &&
8956 !(T.getAddressSpace() == LangAS::opencl_constant ||
8957 (T.getAddressSpace() == LangAS::opencl_global &&
8958 getOpenCLOptions().areProgramScopeVariablesSupported(
8959 getLangOpts())))) {
8960 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8961 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8962 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8963 << Scope << "global or constant";
8964 else
8965 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8966 << Scope << "constant";
8967 NewVD->setInvalidDecl();
8968 return;
8969 }
8970 } else {
8971 if (T.getAddressSpace() == LangAS::opencl_global) {
8972 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8973 << 1 /*is any function*/ << "global";
8974 NewVD->setInvalidDecl();
8975 return;
8976 }
8977 // When this extension is enabled, 'local' variables are permitted in
8978 // non-kernel functions and within nested scopes of kernel functions,
8979 // bypassing standard OpenCL address space restrictions.
8980 bool AllowFunctionScopeLocalVariables =
8981 T.getAddressSpace() == LangAS::opencl_local &&
8983 "__cl_clang_function_scope_local_variables", getLangOpts());
8984 if (AllowFunctionScopeLocalVariables) {
8985 // Direct pass: No further diagnostics needed for this specific case.
8986 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
8987 T.getAddressSpace() == LangAS::opencl_local) {
8989 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8990 // in functions.
8991 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
8992 if (T.getAddressSpace() == LangAS::opencl_constant)
8993 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8994 << 0 /*non-kernel only*/ << "constant";
8995 else
8996 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8997 << 0 /*non-kernel only*/ << "local";
8998 NewVD->setInvalidDecl();
8999 return;
9000 }
9001 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9002 // in the outermost scope of a kernel function.
9003 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9004 if (!getCurScope()->isFunctionScope()) {
9005 if (T.getAddressSpace() == LangAS::opencl_constant)
9006 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9007 << "constant";
9008 else
9009 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9010 << "local";
9011 NewVD->setInvalidDecl();
9012 return;
9013 }
9014 }
9015 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9016 // If we are parsing a template we didn't deduce an addr
9017 // space yet.
9018 T.getAddressSpace() != LangAS::Default) {
9019 // Do not allow other address spaces on automatic variable.
9020 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
9021 NewVD->setInvalidDecl();
9022 return;
9023 }
9024 }
9025 }
9026
9027 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9028 && !NewVD->hasAttr<BlocksAttr>()) {
9029 if (getLangOpts().getGC() != LangOptions::NonGC)
9030 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
9031 else {
9032 assert(!getLangOpts().ObjCAutoRefCount);
9033 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
9034 }
9035 }
9036
9037 // WebAssembly tables must be static with a zero length and can't be
9038 // declared within functions.
9039 if (T->isWebAssemblyTableType()) {
9040 if (getCurScope()->getParent()) { // Parent is null at top-level
9041 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9042 NewVD->setInvalidDecl();
9043 return;
9044 }
9045 if (NewVD->getStorageClass() != SC_Static) {
9046 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9047 NewVD->setInvalidDecl();
9048 return;
9049 }
9050 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9051 if (!ATy || ATy->getZExtSize() != 0) {
9052 Diag(NewVD->getLocation(),
9053 diag::err_typecheck_wasm_table_must_have_zero_length);
9054 NewVD->setInvalidDecl();
9055 return;
9056 }
9057 }
9058
9059 // zero sized static arrays are not allowed in HIP device functions
9060 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9061 if (FunctionDecl *FD = getCurFunctionDecl();
9062 FD &&
9063 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9064 if (const ConstantArrayType *ArrayT =
9065 getASTContext().getAsConstantArrayType(T);
9066 ArrayT && ArrayT->isZeroSize()) {
9067 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9068 }
9069 }
9070 }
9071
9072 bool isVM = T->isVariablyModifiedType();
9073 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9074 NewVD->hasAttr<BlocksAttr>())
9076
9077 if ((isVM && NewVD->hasLinkage()) ||
9078 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9079 bool SizeIsNegative;
9080 llvm::APSInt Oversized;
9082 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9083 QualType FixedT;
9084 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9085 FixedT = FixedTInfo->getType();
9086 else if (FixedTInfo) {
9087 // Type and type-as-written are canonically different. We need to fix up
9088 // both types separately.
9089 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9090 Oversized);
9091 }
9092 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9093 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9094 // FIXME: This won't give the correct result for
9095 // int a[10][n];
9096 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9097
9098 if (NewVD->isFileVarDecl())
9099 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9100 << SizeRange;
9101 else if (NewVD->isStaticLocal())
9102 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9103 << SizeRange;
9104 else
9105 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9106 << SizeRange;
9107 NewVD->setInvalidDecl();
9108 return;
9109 }
9110
9111 if (!FixedTInfo) {
9112 if (NewVD->isFileVarDecl())
9113 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9114 else
9115 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9116 NewVD->setInvalidDecl();
9117 return;
9118 }
9119
9120 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9121 NewVD->setType(FixedT);
9122 NewVD->setTypeSourceInfo(FixedTInfo);
9123 }
9124
9125 if (T->isVoidType()) {
9126 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9127 // of objects and functions.
9129 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9130 << T;
9131 NewVD->setInvalidDecl();
9132 return;
9133 }
9134 }
9135
9136 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9137 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9138 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9139 NewVD->setInvalidDecl();
9140 return;
9141 }
9142
9143 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9144 Diag(NewVD->getLocation(), diag::err_block_on_vm);
9145 NewVD->setInvalidDecl();
9146 return;
9147 }
9148
9149 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9150 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9151 NewVD->setInvalidDecl();
9152 return;
9153 }
9154
9155 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9156 !T->isDependentType() &&
9157 RequireLiteralType(NewVD->getLocation(), T,
9158 diag::err_constexpr_var_non_literal)) {
9159 NewVD->setInvalidDecl();
9160 return;
9161 }
9162
9163 // PPC MMA non-pointer types are not allowed as non-local variable types.
9164 if (Context.getTargetInfo().getTriple().isPPC64() &&
9165 !NewVD->isLocalVarDecl() &&
9166 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9167 NewVD->setInvalidDecl();
9168 return;
9169 }
9170
9171 // Check that SVE types are only used in functions with SVE available.
9172 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9174 llvm::StringMap<bool> CallerFeatureMap;
9175 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9176 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9177 CallerFeatureMap)) {
9178 NewVD->setInvalidDecl();
9179 return;
9180 }
9181 }
9182
9183 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9185 llvm::StringMap<bool> CallerFeatureMap;
9186 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9188 CallerFeatureMap);
9189 }
9190
9191 if (T.hasAddressSpace() &&
9192 !CheckVarDeclSizeAddressSpace(NewVD, T.getAddressSpace())) {
9193 NewVD->setInvalidDecl();
9194 return;
9195 }
9196}
9197
9200
9201 // If the decl is already known invalid, don't check it.
9202 if (NewVD->isInvalidDecl())
9203 return false;
9204
9205 // If we did not find anything by this name, look for a non-visible
9206 // extern "C" declaration with the same name.
9207 if (Previous.empty() &&
9209 Previous.setShadowed();
9210
9211 if (!Previous.empty()) {
9212 MergeVarDecl(NewVD, Previous);
9213 return true;
9214 }
9215 return false;
9216}
9217
9220
9221 // Look for methods in base classes that this method might override.
9222 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9223 /*DetectVirtual=*/false);
9224 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9225 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9226 DeclarationName Name = MD->getDeclName();
9227
9229 // We really want to find the base class destructor here.
9230 Name = Context.DeclarationNames.getCXXDestructorName(
9231 Context.getCanonicalTagType(BaseRecord));
9232 }
9233
9234 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9235 CXXMethodDecl *BaseMD =
9236 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9237 if (!BaseMD || !BaseMD->isVirtual() ||
9238 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9239 /*ConsiderCudaAttrs=*/true))
9240 continue;
9241 if (!CheckExplicitObjectOverride(MD, BaseMD))
9242 continue;
9243 if (Overridden.insert(BaseMD).second) {
9244 MD->addOverriddenMethod(BaseMD);
9245 bool Invalid = false;
9249 if (Invalid)
9250 MD->setInvalidDecl();
9252 }
9253
9254 // A method can only override one function from each base class. We
9255 // don't track indirectly overridden methods from bases of bases.
9256 return true;
9257 }
9258
9259 return false;
9260 };
9261
9262 DC->lookupInBases(VisitBase, Paths);
9263 return !Overridden.empty();
9264}
9265
9266namespace {
9267 // Struct for holding all of the extra arguments needed by
9268 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9269 struct ActOnFDArgs {
9270 Scope *S;
9271 Declarator &D;
9272 MultiTemplateParamsArg TemplateParamLists;
9273 bool AddToScope;
9274 };
9275} // end anonymous namespace
9276
9277namespace {
9278
9279// Callback to only accept typo corrections that have a non-zero edit distance.
9280// Also only accept corrections that have the same parent decl.
9281class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9282 public:
9283 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9284 CXXRecordDecl *Parent)
9285 : Context(Context), OriginalFD(TypoFD),
9286 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9287
9288 bool ValidateCandidate(const TypoCorrection &candidate) override {
9289 if (candidate.getEditDistance() == 0)
9290 return false;
9291
9292 SmallVector<unsigned, 1> MismatchedParams;
9293 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9294 CDeclEnd = candidate.end();
9295 CDecl != CDeclEnd; ++CDecl) {
9296 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9297
9298 if (FD && !FD->hasBody() &&
9299 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9300 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9301 CXXRecordDecl *Parent = MD->getParent();
9302 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9303 return true;
9304 } else if (!ExpectedParent) {
9305 return true;
9306 }
9307 }
9308 }
9309
9310 return false;
9311 }
9312
9313 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9314 return std::make_unique<DifferentNameValidatorCCC>(*this);
9315 }
9316
9317 private:
9318 ASTContext &Context;
9319 FunctionDecl *OriginalFD;
9320 CXXRecordDecl *ExpectedParent;
9321};
9322
9323} // end anonymous namespace
9324
9328
9329/// Generate diagnostics for an invalid function redeclaration.
9330///
9331/// This routine handles generating the diagnostic messages for an invalid
9332/// function redeclaration, including finding possible similar declarations
9333/// or performing typo correction if there are no previous declarations with
9334/// the same name.
9335///
9336/// Returns a NamedDecl iff typo correction was performed and substituting in
9337/// the new declaration name does not cause new errors.
9339 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9340 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9341 DeclarationName Name = NewFD->getDeclName();
9342 DeclContext *NewDC = NewFD->getDeclContext();
9343 SmallVector<unsigned, 1> MismatchedParams;
9345 TypoCorrection Correction;
9346 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9347 unsigned DiagMsg =
9348 IsLocalFriend ? diag::err_no_matching_local_friend :
9349 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9350 diag::err_member_decl_does_not_match;
9351 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9352 IsLocalFriend ? Sema::LookupLocalFriendName
9355
9356 NewFD->setInvalidDecl();
9357 if (IsLocalFriend)
9358 SemaRef.LookupName(Prev, S);
9359 else
9360 SemaRef.LookupQualifiedName(Prev, NewDC);
9361 assert(!Prev.isAmbiguous() &&
9362 "Cannot have an ambiguity in previous-declaration lookup");
9363 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9364 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9365 MD ? MD->getParent() : nullptr);
9366 if (!Prev.empty()) {
9367 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9368 Func != FuncEnd; ++Func) {
9369 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9370 if (FD &&
9371 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9372 // Add 1 to the index so that 0 can mean the mismatch didn't
9373 // involve a parameter
9374 unsigned ParamNum =
9375 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9376 NearMatches.push_back(std::make_pair(FD, ParamNum));
9377 }
9378 }
9379 // If the qualified name lookup yielded nothing, try typo correction
9380 } else if ((Correction = SemaRef.CorrectTypo(
9381 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9382 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9384 IsLocalFriend ? nullptr : NewDC))) {
9385 // Set up everything for the call to ActOnFunctionDeclarator
9386 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9387 ExtraArgs.D.getIdentifierLoc());
9388 Previous.clear();
9389 Previous.setLookupName(Correction.getCorrection());
9390 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9391 CDeclEnd = Correction.end();
9392 CDecl != CDeclEnd; ++CDecl) {
9393 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9394 if (FD && !FD->hasBody() &&
9395 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9396 Previous.addDecl(FD);
9397 }
9398 }
9399 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9400
9402 // Retry building the function declaration with the new previous
9403 // declarations, and with errors suppressed.
9404 {
9405 // Trap errors.
9406 Sema::SFINAETrap Trap(SemaRef);
9407
9408 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9409 // pieces need to verify the typo-corrected C++ declaration and hopefully
9410 // eliminate the need for the parameter pack ExtraArgs.
9412 ExtraArgs.S, ExtraArgs.D,
9413 Correction.getCorrectionDecl()->getDeclContext(),
9414 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9415 ExtraArgs.AddToScope);
9416
9417 if (Trap.hasErrorOccurred())
9418 Result = nullptr;
9419 }
9420
9421 if (Result) {
9422 // Determine which correction we picked.
9423 Decl *Canonical = Result->getCanonicalDecl();
9424 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9425 I != E; ++I)
9426 if ((*I)->getCanonicalDecl() == Canonical)
9427 Correction.setCorrectionDecl(*I);
9428
9429 // Let Sema know about the correction.
9431 SemaRef.diagnoseTypo(
9432 Correction,
9433 SemaRef.PDiag(IsLocalFriend
9434 ? diag::err_no_matching_local_friend_suggest
9435 : diag::err_member_decl_does_not_match_suggest)
9436 << Name << NewDC << IsDefinition);
9437 return Result;
9438 }
9439
9440 // Pretend the typo correction never occurred
9441 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9442 ExtraArgs.D.getIdentifierLoc());
9443 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9444 Previous.clear();
9445 Previous.setLookupName(Name);
9446 }
9447
9448 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9449 << Name << NewDC << IsDefinition << NewFD->getLocation();
9450
9451 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9452 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9453 CXXRecordDecl *RD = NewMD->getParent();
9454 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9455 << RD->getName() << RD->getLocation();
9456 }
9457
9458 bool NewFDisConst = NewMD && NewMD->isConst();
9459
9460 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9461 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9462 NearMatch != NearMatchEnd; ++NearMatch) {
9463 FunctionDecl *FD = NearMatch->first;
9464 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9465 bool FDisConst = MD && MD->isConst();
9466 bool IsMember = MD || !IsLocalFriend;
9467
9468 // FIXME: These notes are poorly worded for the local friend case.
9469 if (unsigned Idx = NearMatch->second) {
9470 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9471 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9472 if (Loc.isInvalid()) Loc = FD->getLocation();
9473 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9474 : diag::note_local_decl_close_param_match)
9475 << Idx << FDParam->getType()
9476 << NewFD->getParamDecl(Idx - 1)->getType();
9477 } else if (FDisConst != NewFDisConst) {
9478 auto DB = SemaRef.Diag(FD->getLocation(),
9479 diag::note_member_def_close_const_match)
9480 << NewFDisConst << FD->getSourceRange().getEnd();
9481 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9482 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9483 " const");
9484 else if (FTI.hasMethodTypeQualifiers() &&
9485 FTI.getConstQualifierLoc().isValid())
9486 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9487 } else {
9488 SemaRef.Diag(FD->getLocation(),
9489 IsMember ? diag::note_member_def_close_match
9490 : diag::note_local_decl_close_match);
9491 }
9492 }
9493 return nullptr;
9494}
9495
9497 switch (D.getDeclSpec().getStorageClassSpec()) {
9498 default: llvm_unreachable("Unknown storage class!");
9499 case DeclSpec::SCS_auto:
9503 diag::err_typecheck_sclass_func);
9505 D.setInvalidType();
9506 break;
9507 case DeclSpec::SCS_unspecified: break;
9510 return SC_None;
9511 return SC_Extern;
9512 case DeclSpec::SCS_static: {
9514 // C99 6.7.1p5:
9515 // The declaration of an identifier for a function that has
9516 // block scope shall have no explicit storage-class specifier
9517 // other than extern
9518 // See also (C++ [dcl.stc]p4).
9520 diag::err_static_block_func);
9521 break;
9522 } else
9523 return SC_Static;
9524 }
9526 }
9527
9528 // No explicit storage class has already been returned
9529 return SC_None;
9530}
9531
9533 DeclContext *DC, QualType &R,
9534 TypeSourceInfo *TInfo,
9535 StorageClass SC,
9536 bool &IsVirtualOkay) {
9537 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9538 DeclarationName Name = NameInfo.getName();
9539
9540 FunctionDecl *NewFD = nullptr;
9541 bool isInline = D.getDeclSpec().isInlineSpecified();
9542
9544 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9545 (SemaRef.getLangOpts().C23 &&
9546 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9547
9548 if (SemaRef.getLangOpts().C23)
9549 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9550 diag::err_c23_constexpr_not_variable);
9551 else
9552 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9553 diag::err_constexpr_wrong_decl_kind)
9554 << static_cast<int>(ConstexprKind);
9555 ConstexprKind = ConstexprSpecKind::Unspecified;
9557 }
9558
9559 if (!SemaRef.getLangOpts().CPlusPlus) {
9560 // Determine whether the function was written with a prototype. This is
9561 // true when:
9562 // - there is a prototype in the declarator, or
9563 // - the type R of the function is some kind of typedef or other non-
9564 // attributed reference to a type name (which eventually refers to a
9565 // function type). Note, we can't always look at the adjusted type to
9566 // check this case because attributes may cause a non-function
9567 // declarator to still have a function type. e.g.,
9568 // typedef void func(int a);
9569 // __attribute__((noreturn)) func other_func; // This has a prototype
9570 bool HasPrototype =
9572 (D.getDeclSpec().isTypeRep() &&
9573 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9574 ->isFunctionProtoType()) ||
9575 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9576 assert(
9577 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9578 "Strict prototypes are required");
9579
9580 NewFD = FunctionDecl::Create(
9581 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9582 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9584 /*TrailingRequiresClause=*/{});
9585 if (D.isInvalidType())
9586 NewFD->setInvalidDecl();
9587
9588 return NewFD;
9589 }
9590
9592 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9593
9594 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9595
9597 // This is a C++ constructor declaration.
9598 assert(DC->isRecord() &&
9599 "Constructors can only be declared in a member context");
9600
9601 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9603 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9605 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9606 InheritedConstructor(), TrailingRequiresClause);
9607
9608 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9609 // This is a C++ destructor declaration.
9610 if (DC->isRecord()) {
9611 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9614 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9615 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9616 /*isImplicitlyDeclared=*/false, ConstexprKind,
9617 TrailingRequiresClause);
9618 // User defined destructors start as not selected if the class definition is still
9619 // not done.
9620 if (Record->isBeingDefined())
9621 NewDD->setIneligibleOrNotSelected(true);
9622
9623 // If the destructor needs an implicit exception specification, set it
9624 // now. FIXME: It'd be nice to be able to create the right type to start
9625 // with, but the type needs to reference the destructor declaration.
9626 if (SemaRef.getLangOpts().CPlusPlus11)
9627 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9628
9629 IsVirtualOkay = true;
9630 return NewDD;
9631
9632 } else {
9633 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9634 D.setInvalidType();
9635
9636 // Create a FunctionDecl to satisfy the function definition parsing
9637 // code path.
9638 return FunctionDecl::Create(
9639 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9640 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9641 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9642 }
9643
9645 if (!DC->isRecord()) {
9646 SemaRef.Diag(D.getIdentifierLoc(),
9647 diag::err_conv_function_not_member);
9648 return nullptr;
9649 }
9650
9651 SemaRef.CheckConversionDeclarator(D, R, SC);
9652 if (D.isInvalidType())
9653 return nullptr;
9654
9655 IsVirtualOkay = true;
9657 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9658 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9659 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9660 TrailingRequiresClause);
9661
9663 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9664 return nullptr;
9666 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9667 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9668 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9669 } else if (DC->isRecord()) {
9670 // If the name of the function is the same as the name of the record,
9671 // then this must be an invalid constructor that has a return type.
9672 // (The parser checks for a return type and makes the declarator a
9673 // constructor if it has no return type).
9674 if (Name.getAsIdentifierInfo() &&
9675 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9676 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9679 return nullptr;
9680 }
9681
9682 // This is a C++ method declaration.
9684 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9685 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9686 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9687 IsVirtualOkay = !Ret->isStatic();
9688 return Ret;
9689 } else {
9690 bool isFriend =
9691 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9692 if (!isFriend && SemaRef.CurContext->isRecord())
9693 return nullptr;
9694
9695 // Determine whether the function was written with a
9696 // prototype. This true when:
9697 // - we're in C++ (where every function has a prototype),
9698 return FunctionDecl::Create(
9699 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9700 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9701 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9702 }
9703}
9704
9713
9715 // Size dependent types are just typedefs to normal integer types
9716 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9717 // integers other than by their names.
9718 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9719
9720 // Remove typedefs one by one until we reach a typedef
9721 // for a size dependent type.
9722 QualType DesugaredTy = Ty;
9723 do {
9724 ArrayRef<StringRef> Names(SizeTypeNames);
9725 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9726 if (Names.end() != Match)
9727 return true;
9728
9729 Ty = DesugaredTy;
9730 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9731 } while (DesugaredTy != Ty);
9732
9733 return false;
9734}
9735
9737 if (PT->isDependentType())
9738 return InvalidKernelParam;
9739
9740 if (PT->isPointerOrReferenceType()) {
9741 QualType PointeeType = PT->getPointeeType();
9742 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9743 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9744 PointeeType.getAddressSpace() == LangAS::Default)
9746
9747 if (PointeeType->isPointerType()) {
9748 // This is a pointer to pointer parameter.
9749 // Recursively check inner type.
9750 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9751 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9752 ParamKind == InvalidKernelParam)
9753 return ParamKind;
9754
9755 // OpenCL v3.0 s6.11.a:
9756 // A restriction to pass pointers to pointers only applies to OpenCL C
9757 // v1.2 or below.
9759 return ValidKernelParam;
9760
9761 return PtrPtrKernelParam;
9762 }
9763
9764 // C++ for OpenCL v1.0 s2.4:
9765 // Moreover the types used in parameters of the kernel functions must be:
9766 // Standard layout types for pointer parameters. The same applies to
9767 // reference if an implementation supports them in kernel parameters.
9768 if (S.getLangOpts().OpenCLCPlusPlus &&
9770 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9771 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9772 bool IsStandardLayoutType = true;
9773 if (CXXRec) {
9774 // If template type is not ODR-used its definition is only available
9775 // in the template definition not its instantiation.
9776 // FIXME: This logic doesn't work for types that depend on template
9777 // parameter (PR58590).
9778 if (!CXXRec->hasDefinition())
9779 CXXRec = CXXRec->getTemplateInstantiationPattern();
9780 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9781 IsStandardLayoutType = false;
9782 }
9783 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9784 !IsStandardLayoutType)
9785 return InvalidKernelParam;
9786 }
9787
9788 // OpenCL v1.2 s6.9.p:
9789 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9791 return ValidKernelParam;
9792
9793 return PtrKernelParam;
9794 }
9795
9796 // OpenCL v1.2 s6.9.k:
9797 // Arguments to kernel functions in a program cannot be declared with the
9798 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9799 // uintptr_t or a struct and/or union that contain fields declared to be one
9800 // of these built-in scalar types.
9802 return InvalidKernelParam;
9803
9804 if (PT->isImageType())
9805 return PtrKernelParam;
9806
9807 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9808 return InvalidKernelParam;
9809
9810 // OpenCL extension spec v1.2 s9.5:
9811 // This extension adds support for half scalar and vector types as built-in
9812 // types that can be used for arithmetic operations, conversions etc.
9813 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9814 PT->isHalfType())
9815 return InvalidKernelParam;
9816
9817 // Look into an array argument to check if it has a forbidden type.
9818 if (PT->isArrayType()) {
9819 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9820 // Call ourself to check an underlying type of an array. Since the
9821 // getPointeeOrArrayElementType returns an innermost type which is not an
9822 // array, this recursive call only happens once.
9823 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9824 }
9825
9826 // C++ for OpenCL v1.0 s2.4:
9827 // Moreover the types used in parameters of the kernel functions must be:
9828 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9829 // types) for parameters passed by value;
9830 if (S.getLangOpts().OpenCLCPlusPlus &&
9832 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9833 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9834 return InvalidKernelParam;
9835
9836 if (PT->isRecordType())
9837 return RecordKernelParam;
9838
9839 return ValidKernelParam;
9840}
9841
9843 Sema &S,
9844 Declarator &D,
9845 ParmVarDecl *Param,
9846 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9847 QualType PT = Param->getType();
9848
9849 // Cache the valid types we encounter to avoid rechecking structs that are
9850 // used again
9851 if (ValidTypes.count(PT.getTypePtr()))
9852 return;
9853
9854 switch (getOpenCLKernelParameterType(S, PT)) {
9855 case PtrPtrKernelParam:
9856 // OpenCL v3.0 s6.11.a:
9857 // A kernel function argument cannot be declared as a pointer to a pointer
9858 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9859 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9860 D.setInvalidType();
9861 return;
9862
9864 // OpenCL v1.0 s6.5:
9865 // __kernel function arguments declared to be a pointer of a type can point
9866 // to one of the following address spaces only : __global, __local or
9867 // __constant.
9868 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9869 D.setInvalidType();
9870 return;
9871
9872 // OpenCL v1.2 s6.9.k:
9873 // Arguments to kernel functions in a program cannot be declared with the
9874 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9875 // uintptr_t or a struct and/or union that contain fields declared to be
9876 // one of these built-in scalar types.
9877
9878 case InvalidKernelParam:
9879 // OpenCL v1.2 s6.8 n:
9880 // A kernel function argument cannot be declared
9881 // of event_t type.
9882 // Do not diagnose half type since it is diagnosed as invalid argument
9883 // type for any function elsewhere.
9884 if (!PT->isHalfType()) {
9885 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9886
9887 // Explain what typedefs are involved.
9888 const TypedefType *Typedef = nullptr;
9889 while ((Typedef = PT->getAs<TypedefType>())) {
9890 SourceLocation Loc = Typedef->getDecl()->getLocation();
9891 // SourceLocation may be invalid for a built-in type.
9892 if (Loc.isValid())
9893 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9894 PT = Typedef->desugar();
9895 }
9896 }
9897
9898 D.setInvalidType();
9899 return;
9900
9901 case PtrKernelParam:
9902 case ValidKernelParam:
9903 ValidTypes.insert(PT.getTypePtr());
9904 return;
9905
9906 case RecordKernelParam:
9907 break;
9908 }
9909
9910 // Track nested structs we will inspect
9912
9913 // Track where we are in the nested structs. Items will migrate from
9914 // VisitStack to HistoryStack as we do the DFS for bad field.
9916 HistoryStack.push_back(nullptr);
9917
9918 // At this point we already handled everything except of a RecordType.
9919 assert(PT->isRecordType() && "Unexpected type.");
9920 const auto *PD = PT->castAsRecordDecl();
9921 VisitStack.push_back(PD);
9922 assert(VisitStack.back() && "First decl null?");
9923
9924 do {
9925 const Decl *Next = VisitStack.pop_back_val();
9926 if (!Next) {
9927 assert(!HistoryStack.empty());
9928 // Found a marker, we have gone up a level
9929 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9930 ValidTypes.insert(Hist->getType().getTypePtr());
9931
9932 continue;
9933 }
9934
9935 // Adds everything except the original parameter declaration (which is not a
9936 // field itself) to the history stack.
9937 const RecordDecl *RD;
9938 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9939 HistoryStack.push_back(Field);
9940
9941 QualType FieldTy = Field->getType();
9942 // Other field types (known to be valid or invalid) are handled while we
9943 // walk around RecordDecl::fields().
9944 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9945 "Unexpected type.");
9946 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9947
9948 RD = FieldRecTy->castAsRecordDecl();
9949 } else {
9950 RD = cast<RecordDecl>(Next);
9951 }
9952
9953 // Add a null marker so we know when we've gone back up a level
9954 VisitStack.push_back(nullptr);
9955
9956 for (const auto *FD : RD->fields()) {
9957 QualType QT = FD->getType();
9958
9959 if (ValidTypes.count(QT.getTypePtr()))
9960 continue;
9961
9963 if (ParamType == ValidKernelParam)
9964 continue;
9965
9966 if (ParamType == RecordKernelParam) {
9967 VisitStack.push_back(FD);
9968 continue;
9969 }
9970
9971 // OpenCL v1.2 s6.9.p:
9972 // Arguments to kernel functions that are declared to be a struct or union
9973 // do not allow OpenCL objects to be passed as elements of the struct or
9974 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9975 // of SVM.
9976 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9977 ParamType == InvalidAddrSpacePtrKernelParam) {
9978 S.Diag(Param->getLocation(),
9979 diag::err_record_with_pointers_kernel_param)
9980 << PT->isUnionType()
9981 << PT;
9982 } else {
9983 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9984 }
9985
9986 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
9987 << PD->getDeclName();
9988
9989 // We have an error, now let's go back up through history and show where
9990 // the offending field came from
9992 I = HistoryStack.begin() + 1,
9993 E = HistoryStack.end();
9994 I != E; ++I) {
9995 const FieldDecl *OuterField = *I;
9996 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9997 << OuterField->getType();
9998 }
9999
10000 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
10001 << QT->isPointerType()
10002 << QT;
10003 D.setInvalidType();
10004 return;
10005 }
10006 } while (!VisitStack.empty());
10007}
10008
10009/// Find the DeclContext in which a tag is implicitly declared if we see an
10010/// elaborated type specifier in the specified context, and lookup finds
10011/// nothing.
10013 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10014 DC = DC->getParent();
10015 return DC;
10016}
10017
10018/// Find the Scope in which a tag is implicitly declared if we see an
10019/// elaborated type specifier in the specified context, and lookup finds
10020/// nothing.
10021static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10022 while (S->isClassScope() ||
10023 (LangOpts.CPlusPlus &&
10025 ((S->getFlags() & Scope::DeclScope) == 0) ||
10026 (S->getEntity() && S->getEntity()->isTransparentContext()))
10027 S = S->getParent();
10028 return S;
10029}
10030
10031/// Determine whether a declaration matches a known function in namespace std.
10033 unsigned BuiltinID) {
10034 switch (BuiltinID) {
10035 case Builtin::BI__GetExceptionInfo:
10036 // No type checking whatsoever.
10037 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10038
10039 case Builtin::BIaddressof:
10040 case Builtin::BI__addressof:
10041 case Builtin::BIforward:
10042 case Builtin::BIforward_like:
10043 case Builtin::BImove:
10044 case Builtin::BImove_if_noexcept:
10045 case Builtin::BIas_const: {
10046 // Ensure that we don't treat the algorithm
10047 // OutputIt std::move(InputIt, InputIt, OutputIt)
10048 // as the builtin std::move.
10049 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10050 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10051 }
10052
10053 default:
10054 return false;
10055 }
10056}
10057
10058NamedDecl*
10061 MultiTemplateParamsArg TemplateParamListsRef,
10062 bool &AddToScope) {
10063 QualType R = TInfo->getType();
10064
10065 assert(R->isFunctionType());
10066 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10067 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10068
10069 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10070 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10072 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10073 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10074 TemplateParamLists.back() = Invented;
10075 else
10076 TemplateParamLists.push_back(Invented);
10077 }
10078
10079 // TODO: consider using NameInfo for diagnostic.
10081 DeclarationName Name = NameInfo.getName();
10083
10086 diag::err_invalid_thread)
10088
10093
10094 bool isFriend = false;
10096 bool isMemberSpecialization = false;
10097 bool isFunctionTemplateSpecialization = false;
10098
10099 bool HasExplicitTemplateArgs = false;
10100 TemplateArgumentListInfo TemplateArgs;
10101
10102 bool isVirtualOkay = false;
10103
10104 DeclContext *OriginalDC = DC;
10105 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10106
10107 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10108 isVirtualOkay);
10109 if (!NewFD) return nullptr;
10110
10111 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10113
10114 // Set the lexical context. If this is a function-scope declaration, or has a
10115 // C++ scope specifier, or is the object of a friend declaration, the lexical
10116 // context will be different from the semantic context.
10118
10119 if (IsLocalExternDecl)
10120 NewFD->setLocalExternDecl();
10121
10122 if (getLangOpts().CPlusPlus) {
10123 // The rules for implicit inlines changed in C++20 for methods and friends
10124 // with an in-class definition (when such a definition is not attached to
10125 // the global module). This does not affect declarations that are already
10126 // inline (whether explicitly or implicitly by being declared constexpr,
10127 // consteval, etc).
10128 // FIXME: We need a better way to separate C++ standard and clang modules.
10129 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10130 !NewFD->getOwningModule() ||
10131 NewFD->isFromGlobalModule() ||
10133 bool isInline = D.getDeclSpec().isInlineSpecified();
10134 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10135 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10136 isFriend = D.getDeclSpec().isFriendSpecified();
10137 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10138 // Pre-C++20 [class.friend]p5
10139 // A function can be defined in a friend declaration of a
10140 // class . . . . Such a function is implicitly inline.
10141 // Post C++20 [class.friend]p7
10142 // Such a function is implicitly an inline function if it is attached
10143 // to the global module.
10144 NewFD->setImplicitlyInline();
10145 }
10146
10147 // If this is a method defined in an __interface, and is not a constructor
10148 // or an overloaded operator, then set the pure flag (isVirtual will already
10149 // return true).
10150 if (const CXXRecordDecl *Parent =
10151 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10152 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10153 NewFD->setIsPureVirtual(true);
10154
10155 // C++ [class.union]p2
10156 // A union can have member functions, but not virtual functions.
10157 if (isVirtual && Parent->isUnion()) {
10158 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10159 NewFD->setInvalidDecl();
10160 }
10161 if ((Parent->isClass() || Parent->isStruct()) &&
10162 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10163 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10164 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10165 if (auto *Def = Parent->getDefinition())
10166 Def->setInitMethod(true);
10167 }
10168 }
10169
10170 SetNestedNameSpecifier(*this, NewFD, D);
10171 isMemberSpecialization = false;
10172 isFunctionTemplateSpecialization = false;
10173 if (D.isInvalidType())
10174 NewFD->setInvalidDecl();
10175
10176 // Match up the template parameter lists with the scope specifier, then
10177 // determine whether we have a template or a template specialization.
10178 bool Invalid = false;
10179 TemplateIdAnnotation *TemplateId =
10181 ? D.getName().TemplateId
10182 : nullptr;
10183 TemplateParameterList *TemplateParams =
10186 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10187 isMemberSpecialization, Invalid);
10188 if (TemplateParams) {
10189 // Check that we can declare a template here.
10190 if (CheckTemplateDeclScope(S, TemplateParams))
10191 NewFD->setInvalidDecl();
10192
10193 if (TemplateParams->size() > 0) {
10194 // This is a function template
10195
10196 // A destructor cannot be a template.
10198 Diag(NewFD->getLocation(), diag::err_destructor_template);
10199 NewFD->setInvalidDecl();
10200 // Function template with explicit template arguments.
10201 } else if (TemplateId) {
10202 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10203 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10204 NewFD->setInvalidDecl();
10205 }
10206
10207 // If we're adding a template to a dependent context, we may need to
10208 // rebuilding some of the types used within the template parameter list,
10209 // now that we know what the current instantiation is.
10210 if (DC->isDependentContext()) {
10211 ContextRAII SavedContext(*this, DC);
10213 Invalid = true;
10214 }
10215
10217 NewFD->getLocation(),
10218 Name, TemplateParams,
10219 NewFD);
10220 FunctionTemplate->setLexicalDeclContext(CurContext);
10222
10223 // For source fidelity, store the other template param lists.
10224 if (TemplateParamLists.size() > 1) {
10226 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10227 .drop_back(1));
10228 }
10229 } else {
10230 // This is a function template specialization.
10231 isFunctionTemplateSpecialization = true;
10232 // For source fidelity, store all the template param lists.
10233 if (TemplateParamLists.size() > 0)
10234 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10235
10236 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10237 if (isFriend) {
10238 // We want to remove the "template<>", found here.
10239 SourceRange RemoveRange = TemplateParams->getSourceRange();
10240
10241 // If we remove the template<> and the name is not a
10242 // template-id, we're actually silently creating a problem:
10243 // the friend declaration will refer to an untemplated decl,
10244 // and clearly the user wants a template specialization. So
10245 // we need to insert '<>' after the name.
10246 SourceLocation InsertLoc;
10248 InsertLoc = D.getName().getSourceRange().getEnd();
10249 InsertLoc = getLocForEndOfToken(InsertLoc);
10250 }
10251
10252 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10253 << Name << RemoveRange
10254 << FixItHint::CreateRemoval(RemoveRange)
10255 << FixItHint::CreateInsertion(InsertLoc, "<>");
10256 Invalid = true;
10257
10258 // Recover by faking up an empty template argument list.
10259 HasExplicitTemplateArgs = true;
10260 TemplateArgs.setLAngleLoc(InsertLoc);
10261 TemplateArgs.setRAngleLoc(InsertLoc);
10262 }
10263 }
10264 } else {
10265 // Check that we can declare a template here.
10266 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10267 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10268 NewFD->setInvalidDecl();
10269
10270 // All template param lists were matched against the scope specifier:
10271 // this is NOT (an explicit specialization of) a template.
10272 if (TemplateParamLists.size() > 0)
10273 // For source fidelity, store all the template param lists.
10274 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10275
10276 // "friend void foo<>(int);" is an implicit specialization decl.
10277 if (isFriend && TemplateId)
10278 isFunctionTemplateSpecialization = true;
10279 }
10280
10281 // If this is a function template specialization and the unqualified-id of
10282 // the declarator-id is a template-id, convert the template argument list
10283 // into our AST format and check for unexpanded packs.
10284 if (isFunctionTemplateSpecialization && TemplateId) {
10285 HasExplicitTemplateArgs = true;
10286
10287 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10288 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10289 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10290 TemplateId->NumArgs);
10291 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10292
10293 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10294 // declaration of a function template partial specialization? Should we
10295 // consider the unexpanded pack context to be a partial specialization?
10296 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10298 ArgLoc, isFriend ? UPPC_FriendDeclaration
10300 NewFD->setInvalidDecl();
10301 }
10302 }
10303
10304 if (Invalid) {
10305 NewFD->setInvalidDecl();
10306 if (FunctionTemplate)
10307 FunctionTemplate->setInvalidDecl();
10308 }
10309
10310 // C++ [dcl.fct.spec]p5:
10311 // The virtual specifier shall only be used in declarations of
10312 // nonstatic class member functions that appear within a
10313 // member-specification of a class declaration; see 10.3.
10314 //
10315 if (isVirtual && !NewFD->isInvalidDecl()) {
10316 if (!isVirtualOkay) {
10318 diag::err_virtual_non_function);
10319 } else if (!CurContext->isRecord()) {
10320 // 'virtual' was specified outside of the class.
10322 diag::err_virtual_out_of_class)
10324 } else if (NewFD->getDescribedFunctionTemplate()) {
10325 // C++ [temp.mem]p3:
10326 // A member function template shall not be virtual.
10328 diag::err_virtual_member_function_template)
10330 } else {
10331 // Okay: Add virtual to the method.
10332 NewFD->setVirtualAsWritten(true);
10333 }
10334
10335 if (getLangOpts().CPlusPlus14 &&
10336 NewFD->getReturnType()->isUndeducedType())
10337 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10338 }
10339
10340 // C++ [dcl.fct.spec]p3:
10341 // The inline specifier shall not appear on a block scope function
10342 // declaration.
10343 if (isInline && !NewFD->isInvalidDecl()) {
10344 if (CurContext->isFunctionOrMethod()) {
10345 // 'inline' is not allowed on block scope function declaration.
10347 diag::err_inline_declaration_block_scope) << Name
10349 }
10350 }
10351
10352 // C++ [dcl.fct.spec]p6:
10353 // The explicit specifier shall be used only in the declaration of a
10354 // constructor or conversion function within its class definition;
10355 // see 12.3.1 and 12.3.2.
10356 if (hasExplicit && !NewFD->isInvalidDecl() &&
10358 if (!CurContext->isRecord()) {
10359 // 'explicit' was specified outside of the class.
10361 diag::err_explicit_out_of_class)
10363 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10364 !isa<CXXConversionDecl>(NewFD)) {
10365 // 'explicit' was specified on a function that wasn't a constructor
10366 // or conversion function.
10368 diag::err_explicit_non_ctor_or_conv_function)
10370 }
10371 }
10372
10374 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10375 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10376 // are implicitly inline.
10377 NewFD->setImplicitlyInline();
10378
10379 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10380 // be either constructors or to return a literal type. Therefore,
10381 // destructors cannot be declared constexpr.
10382 if (isa<CXXDestructorDecl>(NewFD) &&
10384 ConstexprKind == ConstexprSpecKind::Consteval)) {
10385 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10386 << static_cast<int>(ConstexprKind);
10390 }
10391 // C++20 [dcl.constexpr]p2: An allocation function, or a
10392 // deallocation function shall not be declared with the consteval
10393 // specifier.
10394 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10397 diag::err_invalid_consteval_decl_kind)
10398 << NewFD;
10400 }
10401 }
10402
10403 // If __module_private__ was specified, mark the function accordingly.
10405 if (isFunctionTemplateSpecialization) {
10406 SourceLocation ModulePrivateLoc
10408 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10409 << 0
10410 << FixItHint::CreateRemoval(ModulePrivateLoc);
10411 } else {
10412 NewFD->setModulePrivate();
10413 if (FunctionTemplate)
10414 FunctionTemplate->setModulePrivate();
10415 }
10416 }
10417
10418 if (isFriend) {
10419 if (FunctionTemplate) {
10420 FunctionTemplate->setObjectOfFriendDecl();
10421 FunctionTemplate->setAccess(AS_public);
10422 }
10423 NewFD->setObjectOfFriendDecl();
10424 NewFD->setAccess(AS_public);
10425 }
10426
10427 // If a function is defined as defaulted or deleted, mark it as such now.
10428 // We'll do the relevant checks on defaulted / deleted functions later.
10429 switch (D.getFunctionDefinitionKind()) {
10432 break;
10433
10435 NewFD->setDefaulted();
10436 break;
10437
10439 NewFD->setDeletedAsWritten();
10440 break;
10441 }
10442
10443 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10445 // Pre C++20 [class.mfct]p2:
10446 // A member function may be defined (8.4) in its class definition, in
10447 // which case it is an inline member function (7.1.2)
10448 // Post C++20 [class.mfct]p1:
10449 // If a member function is attached to the global module and is defined
10450 // in its class definition, it is inline.
10451 NewFD->setImplicitlyInline();
10452 }
10453
10454 if (!isFriend && SC != SC_None) {
10455 // C++ [temp.expl.spec]p2:
10456 // The declaration in an explicit-specialization shall not be an
10457 // export-declaration. An explicit specialization shall not use a
10458 // storage-class-specifier other than thread_local.
10459 //
10460 // We diagnose friend declarations with storage-class-specifiers
10461 // elsewhere.
10462 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10464 diag::ext_explicit_specialization_storage_class)
10467 }
10468
10469 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10470 assert(isa<CXXMethodDecl>(NewFD) &&
10471 "Out-of-line member function should be a CXXMethodDecl");
10472 // C++ [class.static]p1:
10473 // A data or function member of a class may be declared static
10474 // in a class definition, in which case it is a static member of
10475 // the class.
10476
10477 // Complain about the 'static' specifier if it's on an out-of-line
10478 // member function definition.
10479
10480 // MSVC permits the use of a 'static' storage specifier on an
10481 // out-of-line member function template declaration and class member
10482 // template declaration (MSVC versions before 2015), warn about this.
10484 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10485 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10486 (getLangOpts().MSVCCompat &&
10488 ? diag::ext_static_out_of_line
10489 : diag::err_static_out_of_line)
10492 }
10493 }
10494
10495 // C++11 [except.spec]p15:
10496 // A deallocation function with no exception-specification is treated
10497 // as if it were specified with noexcept(true).
10498 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10499 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10500 !FPT->hasExceptionSpec())
10501 NewFD->setType(Context.getFunctionType(
10502 FPT->getReturnType(), FPT->getParamTypes(),
10504
10505 // C++20 [dcl.inline]/7
10506 // If an inline function or variable that is attached to a named module
10507 // is declared in a definition domain, it shall be defined in that
10508 // domain.
10509 // So, if the current declaration does not have a definition, we must
10510 // check at the end of the TU (or when the PMF starts) to see that we
10511 // have a definition at that point.
10512 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10513 NewFD->isInNamedModule()) {
10514 PendingInlineFuncDecls.insert(NewFD);
10515 }
10516 }
10517
10518 // Filter out previous declarations that don't match the scope.
10521 isMemberSpecialization ||
10522 isFunctionTemplateSpecialization);
10523
10525
10526 // Handle GNU asm-label extension (encoded as an attribute).
10527 if (Expr *E = D.getAsmLabel()) {
10528 // The parser guarantees this is a string.
10530 NewFD->addAttr(
10531 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10532 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10533 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10535 if (I != ExtnameUndeclaredIdentifiers.end()) {
10536 if (isDeclExternC(NewFD)) {
10537 NewFD->addAttr(I->second);
10539 } else if (NewFD->getDeclContext()
10542 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10543 << /*Variable*/0 << NewFD;
10544 }
10545 }
10546
10547 // Copy the parameter declarations from the declarator D to the function
10548 // declaration NewFD, if they are available. First scavenge them into Params.
10550 unsigned FTIIdx;
10551 if (D.isFunctionDeclarator(FTIIdx)) {
10553
10554 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10555 // function that takes no arguments, not a function that takes a
10556 // single void argument.
10557 // We let through "const void" here because Sema::GetTypeForDeclarator
10558 // already checks for that case.
10559 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10560 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10561 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10562 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10563 Param->setDeclContext(NewFD);
10564 Params.push_back(Param);
10565
10566 if (Param->isInvalidDecl())
10567 NewFD->setInvalidDecl();
10568 }
10569 }
10570
10571 if (!getLangOpts().CPlusPlus) {
10572 // In C, find all the tag declarations from the prototype and move them
10573 // into the function DeclContext. Remove them from the surrounding tag
10574 // injection context of the function, which is typically but not always
10575 // the TU.
10576 DeclContext *PrototypeTagContext =
10578 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10579 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10580
10581 // We don't want to reparent enumerators. Look at their parent enum
10582 // instead.
10583 if (!TD) {
10584 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10585 TD = cast<EnumDecl>(ECD->getDeclContext());
10586 }
10587 if (!TD)
10588 continue;
10589 DeclContext *TagDC = TD->getLexicalDeclContext();
10590 if (!TagDC->containsDecl(TD))
10591 continue;
10592 TagDC->removeDecl(TD);
10593 TD->setDeclContext(NewFD);
10594 NewFD->addDecl(TD);
10595
10596 // Preserve the lexical DeclContext if it is not the surrounding tag
10597 // injection context of the FD. In this example, the semantic context of
10598 // E will be f and the lexical context will be S, while both the
10599 // semantic and lexical contexts of S will be f:
10600 // void f(struct S { enum E { a } f; } s);
10601 if (TagDC != PrototypeTagContext)
10602 TD->setLexicalDeclContext(TagDC);
10603 }
10604 }
10605 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10606 // When we're declaring a function with a typedef, typeof, etc as in the
10607 // following example, we'll need to synthesize (unnamed)
10608 // parameters for use in the declaration.
10609 //
10610 // @code
10611 // typedef void fn(int);
10612 // fn f;
10613 // @endcode
10614
10615 // Synthesize a parameter for each argument type.
10616 for (const auto &AI : FT->param_types()) {
10617 ParmVarDecl *Param =
10619 Param->setScopeInfo(0, Params.size());
10620 Params.push_back(Param);
10621 }
10622 } else {
10623 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10624 "Should not need args for typedef of non-prototype fn");
10625 }
10626
10627 // Finally, we know we have the right number of parameters, install them.
10628 NewFD->setParams(Params);
10629
10630 // If this declarator is a declaration and not a definition, its parameters
10631 // will not be pushed onto a scope chain. That means we will not issue any
10632 // reserved identifier warnings for the declaration, but we will for the
10633 // definition. Handle those here.
10634 if (!D.isFunctionDefinition()) {
10635 for (const ParmVarDecl *PVD : Params)
10637 }
10638
10640 NewFD->addAttr(
10641 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10642
10643 // Functions returning a variably modified type violate C99 6.7.5.2p2
10644 // because all functions have linkage.
10645 if (!NewFD->isInvalidDecl() &&
10647 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10648 NewFD->setInvalidDecl();
10649 }
10650
10651 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10653 !NewFD->hasAttr<SectionAttr>())
10654 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10655 Context, PragmaClangTextSection.SectionName,
10656 PragmaClangTextSection.PragmaLocation));
10657
10658 // Apply an implicit SectionAttr if #pragma code_seg is active.
10659 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10660 !NewFD->hasAttr<SectionAttr>()) {
10661 NewFD->addAttr(SectionAttr::CreateImplicit(
10662 Context, CodeSegStack.CurrentValue->getString(),
10663 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10664 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10667 NewFD))
10668 NewFD->dropAttr<SectionAttr>();
10669 }
10670
10671 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10672 // active.
10673 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10674 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10675 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10676 Context, PragmaClangTextSection.PragmaLocation));
10677
10678 // Apply an implicit CodeSegAttr from class declspec or
10679 // apply an implicit SectionAttr from #pragma code_seg if active.
10680 if (!NewFD->hasAttr<CodeSegAttr>()) {
10682 D.isFunctionDefinition())) {
10683 NewFD->addAttr(SAttr);
10684 }
10685 }
10686
10687 // Handle attributes.
10688 ProcessDeclAttributes(S, NewFD, D);
10689 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10690 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10691 !NewTVA->isDefaultVersion() &&
10692 !Context.getTargetInfo().hasFeature("fmv")) {
10693 // Don't add to scope fmv functions declarations if fmv disabled
10694 AddToScope = false;
10695 return NewFD;
10696 }
10697
10698 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10699 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10700 // type.
10701 //
10702 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10703 // type declaration will generate a compilation error.
10704 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10705 if (AddressSpace != LangAS::Default) {
10706 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10707 NewFD->setInvalidDecl();
10708 }
10709 }
10710
10711 if (!getLangOpts().CPlusPlus) {
10712 // Perform semantic checking on the function declaration.
10713 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10714 CheckMain(NewFD, D.getDeclSpec());
10715
10716 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10717 CheckMSVCRTEntryPoint(NewFD);
10718
10719 if (!NewFD->isInvalidDecl())
10721 isMemberSpecialization,
10723 else if (!Previous.empty())
10724 // Recover gracefully from an invalid redeclaration.
10725 D.setRedeclaration(true);
10726 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10727 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10728 "previous declaration set still overloaded");
10729
10730 // Diagnose no-prototype function declarations with calling conventions that
10731 // don't support variadic calls. Only do this in C and do it after merging
10732 // possibly prototyped redeclarations.
10733 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10735 CallingConv CC = FT->getExtInfo().getCC();
10736 if (!supportsVariadicCall(CC)) {
10737 // Windows system headers sometimes accidentally use stdcall without
10738 // (void) parameters, so we relax this to a warning.
10739 int DiagID =
10740 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10741 Diag(NewFD->getLocation(), DiagID)
10743 }
10744 }
10745
10749 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10751 } else {
10752 // C++11 [replacement.functions]p3:
10753 // The program's definitions shall not be specified as inline.
10754 //
10755 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10756 //
10757 // Suppress the diagnostic if the function is __attribute__((used)), since
10758 // that forces an external definition to be emitted.
10759 if (D.getDeclSpec().isInlineSpecified() &&
10761 !NewFD->hasAttr<UsedAttr>())
10763 diag::ext_operator_new_delete_declared_inline)
10764 << NewFD->getDeclName();
10765
10766 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10767 // C++20 [dcl.decl.general]p4:
10768 // The optional requires-clause in an init-declarator or
10769 // member-declarator shall be present only if the declarator declares a
10770 // templated function.
10771 //
10772 // C++20 [temp.pre]p8:
10773 // An entity is templated if it is
10774 // - a template,
10775 // - an entity defined or created in a templated entity,
10776 // - a member of a templated entity,
10777 // - an enumerator for an enumeration that is a templated entity, or
10778 // - the closure type of a lambda-expression appearing in the
10779 // declaration of a templated entity.
10780 //
10781 // [Note 6: A local class, a local or block variable, or a friend
10782 // function defined in a templated entity is a templated entity.
10783 // — end note]
10784 //
10785 // A templated function is a function template or a function that is
10786 // templated. A templated class is a class template or a class that is
10787 // templated. A templated variable is a variable template or a variable
10788 // that is templated.
10789 if (!FunctionTemplate) {
10790 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10791 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10792 // An explicit specialization shall not have a trailing
10793 // requires-clause unless it declares a function template.
10794 //
10795 // Since a friend function template specialization cannot be
10796 // definition, and since a non-template friend declaration with a
10797 // trailing requires-clause must be a definition, we diagnose
10798 // friend function template specializations with trailing
10799 // requires-clauses on the same path as explicit specializations
10800 // even though they aren't necessarily prohibited by the same
10801 // language rule.
10802 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10803 << isFriend;
10804 } else if (isFriend && NewFD->isTemplated() &&
10805 !D.isFunctionDefinition()) {
10806 // C++ [temp.friend]p9:
10807 // A non-template friend declaration with a requires-clause shall be
10808 // a definition.
10809 Diag(NewFD->getBeginLoc(),
10810 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10811 NewFD->setInvalidDecl();
10812 } else if (!NewFD->isTemplated() ||
10813 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10814 Diag(TRC->getBeginLoc(),
10815 diag::err_constrained_non_templated_function);
10816 }
10817 }
10818 }
10819
10820 // We do not add HD attributes to specializations here because
10821 // they may have different constexpr-ness compared to their
10822 // templates and, after maybeAddHostDeviceAttrs() is applied,
10823 // may end up with different effective targets. Instead, a
10824 // specialization inherits its target attributes from its template
10825 // in the CheckFunctionTemplateSpecialization() call below.
10826 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10828
10829 // Handle explicit specializations of function templates
10830 // and friend function declarations with an explicit
10831 // template argument list.
10832 if (isFunctionTemplateSpecialization) {
10833 bool isDependentSpecialization = false;
10834 if (isFriend) {
10835 // For friend function specializations, this is a dependent
10836 // specialization if its semantic context is dependent, its
10837 // type is dependent, or if its template-id is dependent.
10838 isDependentSpecialization =
10839 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10840 (HasExplicitTemplateArgs &&
10841 TemplateSpecializationType::
10842 anyInstantiationDependentTemplateArguments(
10843 TemplateArgs.arguments()));
10844 assert((!isDependentSpecialization ||
10845 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10846 "dependent friend function specialization without template "
10847 "args");
10848 } else {
10849 // For class-scope explicit specializations of function templates,
10850 // if the lexical context is dependent, then the specialization
10851 // is dependent.
10852 isDependentSpecialization =
10853 CurContext->isRecord() && CurContext->isDependentContext();
10854 }
10855
10856 TemplateArgumentListInfo *ExplicitTemplateArgs =
10857 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10858 if (isDependentSpecialization) {
10859 // If it's a dependent specialization, it may not be possible
10860 // to determine the primary template (for explicit specializations)
10861 // or befriended declaration (for friends) until the enclosing
10862 // template is instantiated. In such cases, we store the declarations
10863 // found by name lookup and defer resolution until instantiation.
10865 NewFD, ExplicitTemplateArgs, Previous))
10866 NewFD->setInvalidDecl();
10867 } else if (!NewFD->isInvalidDecl()) {
10868 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10869 Previous))
10870 NewFD->setInvalidDecl();
10871 }
10872 } else if (isMemberSpecialization && !FunctionTemplate) {
10874 NewFD->setInvalidDecl();
10875 }
10876
10877 // Perform semantic checking on the function declaration.
10878 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10879 CheckMain(NewFD, D.getDeclSpec());
10880
10881 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10882 CheckMSVCRTEntryPoint(NewFD);
10883
10884 if (!NewFD->isInvalidDecl())
10886 isMemberSpecialization,
10888 else if (!Previous.empty())
10889 // Recover gracefully from an invalid redeclaration.
10890 D.setRedeclaration(true);
10891
10892 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10893 !D.isRedeclaration() ||
10894 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10895 "previous declaration set still overloaded");
10896
10897 NamedDecl *PrincipalDecl = (FunctionTemplate
10899 : NewFD);
10900
10901 if (isFriend && NewFD->getPreviousDecl()) {
10902 AccessSpecifier Access = AS_public;
10903 if (!NewFD->isInvalidDecl())
10904 Access = NewFD->getPreviousDecl()->getAccess();
10905
10906 NewFD->setAccess(Access);
10907 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10908 }
10909
10910 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10912 PrincipalDecl->setNonMemberOperator();
10913
10914 // If we have a function template, check the template parameter
10915 // list. This will check and merge default template arguments.
10916 if (FunctionTemplate) {
10917 FunctionTemplateDecl *PrevTemplate =
10918 FunctionTemplate->getPreviousDecl();
10919 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10920 PrevTemplate ? PrevTemplate->getTemplateParameters()
10921 : nullptr,
10926 : (D.getCXXScopeSpec().isSet() &&
10927 DC && DC->isRecord() &&
10928 DC->isDependentContext())
10931 }
10932
10933 if (NewFD->isInvalidDecl()) {
10934 // Ignore all the rest of this.
10935 } else if (!D.isRedeclaration()) {
10936 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10937 AddToScope };
10938 // Fake up an access specifier if it's supposed to be a class member.
10939 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10940 NewFD->setAccess(AS_public);
10941
10942 // Qualified decls generally require a previous declaration.
10943 if (D.getCXXScopeSpec().isSet()) {
10944 // ...with the major exception of templated-scope or
10945 // dependent-scope friend declarations.
10946
10947 // TODO: we currently also suppress this check in dependent
10948 // contexts because (1) the parameter depth will be off when
10949 // matching friend templates and (2) we might actually be
10950 // selecting a friend based on a dependent factor. But there
10951 // are situations where these conditions don't apply and we
10952 // can actually do this check immediately.
10953 //
10954 // Unless the scope is dependent, it's always an error if qualified
10955 // redeclaration lookup found nothing at all. Diagnose that now;
10956 // nothing will diagnose that error later.
10957 if (isFriend &&
10959 (!Previous.empty() && CurContext->isDependentContext()))) {
10960 // ignore these
10961 } else if (NewFD->isCPUDispatchMultiVersion() ||
10962 NewFD->isCPUSpecificMultiVersion()) {
10963 // ignore this, we allow the redeclaration behavior here to create new
10964 // versions of the function.
10965 } else {
10966 // The user tried to provide an out-of-line definition for a
10967 // function that is a member of a class or namespace, but there
10968 // was no such member function declared (C++ [class.mfct]p2,
10969 // C++ [namespace.memdef]p2). For example:
10970 //
10971 // class X {
10972 // void f() const;
10973 // };
10974 //
10975 // void X::f() { } // ill-formed
10976 //
10977 // Complain about this problem, and attempt to suggest close
10978 // matches (e.g., those that differ only in cv-qualifiers and
10979 // whether the parameter types are references).
10980
10982 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10983 AddToScope = ExtraArgs.AddToScope;
10984 return Result;
10985 }
10986 }
10987
10988 // Unqualified local friend declarations are required to resolve
10989 // to something.
10990 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10992 *this, Previous, NewFD, ExtraArgs, true, S)) {
10993 AddToScope = ExtraArgs.AddToScope;
10994 return Result;
10995 }
10996 }
10997 } else if (!D.isFunctionDefinition() &&
10998 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10999 !isFriend && !isFunctionTemplateSpecialization &&
11000 !isMemberSpecialization) {
11001 // An out-of-line member function declaration must also be a
11002 // definition (C++ [class.mfct]p2).
11003 // Note that this is not the case for explicit specializations of
11004 // function templates or member functions of class templates, per
11005 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11006 // extension for compatibility with old SWIG code which likes to
11007 // generate them.
11008 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
11009 << D.getCXXScopeSpec().getRange();
11010 }
11011 }
11012
11013 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11014 // Any top level function could potentially be specified as an entry.
11015 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11016 HLSL().ActOnTopLevelFunction(NewFD);
11017
11018 if (NewFD->hasAttr<HLSLShaderAttr>())
11019 HLSL().CheckEntryPoint(NewFD);
11020 }
11021
11022 // If this is the first declaration of a library builtin function, add
11023 // attributes as appropriate.
11024 if (!D.isRedeclaration()) {
11025 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11026 if (unsigned BuiltinID = II->getBuiltinID()) {
11027 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
11028 if (!InStdNamespace &&
11030 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11031 // Validate the type matches unless this builtin is specified as
11032 // matching regardless of its declared type.
11033 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
11034 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11035 } else {
11037 LookupNecessaryTypesForBuiltin(S, BuiltinID);
11038 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
11039
11040 if (!Error && !BuiltinType.isNull() &&
11041 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11042 NewFD->getType(), BuiltinType))
11043 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11044 }
11045 }
11046 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11047 isStdBuiltin(Context, NewFD, BuiltinID)) {
11048 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11049 }
11050 }
11051 }
11052 }
11053
11054 ProcessPragmaWeak(S, NewFD);
11055 ProcessPragmaExport(NewFD);
11056 checkAttributesAfterMerging(*this, *NewFD);
11057
11059
11060 if (NewFD->hasAttr<OverloadableAttr>() &&
11061 !NewFD->getType()->getAs<FunctionProtoType>()) {
11062 Diag(NewFD->getLocation(),
11063 diag::err_attribute_overloadable_no_prototype)
11064 << NewFD;
11065 NewFD->dropAttr<OverloadableAttr>();
11066 }
11067
11068 // If there's a #pragma GCC visibility in scope, and this isn't a class
11069 // member, set the visibility of this function.
11070 if (!DC->isRecord() && NewFD->isExternallyVisible())
11072
11073 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11074 // marking the function.
11075 ObjC().AddCFAuditedAttribute(NewFD);
11076
11077 // If this is a function definition, check if we have to apply any
11078 // attributes (i.e. optnone and no_builtin) due to a pragma.
11079 if (D.isFunctionDefinition()) {
11080 AddRangeBasedOptnone(NewFD);
11082 AddSectionMSAllocText(NewFD);
11084 }
11085
11086 // If this is the first declaration of an extern C variable, update
11087 // the map of such variables.
11088 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11089 isIncompleteDeclExternC(*this, NewFD))
11091
11092 // Set this FunctionDecl's range up to the right paren.
11093 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11094
11095 if (D.isRedeclaration() && !Previous.empty()) {
11096 NamedDecl *Prev = Previous.getRepresentativeDecl();
11097 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11098 isMemberSpecialization ||
11099 isFunctionTemplateSpecialization,
11101 }
11102
11103 if (getLangOpts().CUDA) {
11104 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11105 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11107 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11108 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11110 Context.setcudaConfigureCallDecl(NewFD);
11111 }
11112 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11113 !NewFD->isInvalidDecl() &&
11115 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11116 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11118 Context.setcudaGetParameterBufferDecl(NewFD);
11119 }
11120 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11121 !NewFD->isInvalidDecl() &&
11123 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11124 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11126 Context.setcudaLaunchDeviceDecl(NewFD);
11127 }
11128 }
11129 }
11130
11132
11133 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11134 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11135 if (SC == SC_Static) {
11136 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11137 D.setInvalidType();
11138 }
11139
11140 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11141 if (!NewFD->getReturnType()->isVoidType()) {
11142 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11143 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11144 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11145 : FixItHint());
11146 D.setInvalidType();
11147 }
11148
11150 for (auto *Param : NewFD->parameters())
11151 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11152
11153 if (getLangOpts().OpenCLCPlusPlus) {
11154 if (DC->isRecord()) {
11155 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11156 D.setInvalidType();
11157 }
11158 if (FunctionTemplate) {
11159 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11160 D.setInvalidType();
11161 }
11162 }
11163 }
11164
11165 if (getLangOpts().CPlusPlus) {
11166 // Precalculate whether this is a friend function template with a constraint
11167 // that depends on an enclosing template, per [temp.friend]p9.
11168 if (isFriend && FunctionTemplate &&
11171
11172 // C++ [temp.friend]p9:
11173 // A friend function template with a constraint that depends on a
11174 // template parameter from an enclosing template shall be a definition.
11175 if (!D.isFunctionDefinition()) {
11176 Diag(NewFD->getBeginLoc(),
11177 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11178 NewFD->setInvalidDecl();
11179 }
11180 }
11181
11182 if (FunctionTemplate) {
11183 if (NewFD->isInvalidDecl())
11184 FunctionTemplate->setInvalidDecl();
11185 return FunctionTemplate;
11186 }
11187
11188 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11190 }
11191
11192 for (const ParmVarDecl *Param : NewFD->parameters()) {
11193 QualType PT = Param->getType();
11194
11195 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11196 // types.
11197 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11198 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11199 QualType ElemTy = PipeTy->getElementType();
11200 if (ElemTy->isPointerOrReferenceType()) {
11201 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11202 D.setInvalidType();
11203 }
11204 }
11205 }
11206 // WebAssembly tables can't be used as function parameters.
11207 if (Context.getTargetInfo().getTriple().isWasm()) {
11209 Diag(Param->getTypeSpecStartLoc(),
11210 diag::err_wasm_table_as_function_parameter);
11211 D.setInvalidType();
11212 }
11213 }
11214 }
11215
11216 // Diagnose availability attributes. Availability cannot be used on functions
11217 // that are run during load/unload.
11218 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11219 if (NewFD->hasAttr<ConstructorAttr>()) {
11220 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11221 << 1;
11222 NewFD->dropAttr<AvailabilityAttr>();
11223 }
11224 if (NewFD->hasAttr<DestructorAttr>()) {
11225 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11226 << 2;
11227 NewFD->dropAttr<AvailabilityAttr>();
11228 }
11229 }
11230
11231 // Diagnose no_builtin attribute on function declaration that are not a
11232 // definition.
11233 // FIXME: We should really be doing this in
11234 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11235 // the FunctionDecl and at this point of the code
11236 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11237 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11238 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11239 switch (D.getFunctionDefinitionKind()) {
11242 Diag(NBA->getLocation(),
11243 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11244 << NBA->getSpelling();
11245 break;
11247 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11248 << NBA->getSpelling();
11249 break;
11251 break;
11252 }
11253
11254 // Similar to no_builtin logic above, at this point of the code
11255 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11256 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11257 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11258 !NewFD->isInvalidDecl() &&
11260 ExternalDeclarations.push_back(NewFD);
11261
11262 // Used for a warning on the 'next' declaration when used with a
11263 // `routine(name)`.
11264 if (getLangOpts().OpenACC)
11266
11267 return NewFD;
11268}
11269
11270/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11271/// when __declspec(code_seg) "is applied to a class, all member functions of
11272/// the class and nested classes -- this includes compiler-generated special
11273/// member functions -- are put in the specified segment."
11274/// The actual behavior is a little more complicated. The Microsoft compiler
11275/// won't check outer classes if there is an active value from #pragma code_seg.
11276/// The CodeSeg is always applied from the direct parent but only from outer
11277/// classes when the #pragma code_seg stack is empty. See:
11278/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11279/// available since MS has removed the page.
11281 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11282 if (!Method)
11283 return nullptr;
11284 const CXXRecordDecl *Parent = Method->getParent();
11285 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11286 Attr *NewAttr = SAttr->clone(S.getASTContext());
11287 NewAttr->setImplicit(true);
11288 return NewAttr;
11289 }
11290
11291 // The Microsoft compiler won't check outer classes for the CodeSeg
11292 // when the #pragma code_seg stack is active.
11293 if (S.CodeSegStack.CurrentValue)
11294 return nullptr;
11295
11296 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11297 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11298 Attr *NewAttr = SAttr->clone(S.getASTContext());
11299 NewAttr->setImplicit(true);
11300 return NewAttr;
11301 }
11302 }
11303 return nullptr;
11304}
11305
11307 bool IsDefinition) {
11308 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11309 return A;
11310 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11311 CodeSegStack.CurrentValue)
11312 return SectionAttr::CreateImplicit(
11313 getASTContext(), CodeSegStack.CurrentValue->getString(),
11314 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11315 return nullptr;
11316}
11317
11319 QualType NewT, QualType OldT) {
11321 return true;
11322
11323 // For dependently-typed local extern declarations and friends, we can't
11324 // perform a correct type check in general until instantiation:
11325 //
11326 // int f();
11327 // template<typename T> void g() { T f(); }
11328 //
11329 // (valid if g() is only instantiated with T = int).
11330 if (NewT->isDependentType() &&
11331 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11332 return false;
11333
11334 // Similarly, if the previous declaration was a dependent local extern
11335 // declaration, we don't really know its type yet.
11336 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11337 return false;
11338
11339 return true;
11340}
11341
11344 return true;
11345
11346 // Don't chain dependent friend function definitions until instantiation, to
11347 // permit cases like
11348 //
11349 // void func();
11350 // template<typename T> class C1 { friend void func() {} };
11351 // template<typename T> class C2 { friend void func() {} };
11352 //
11353 // ... which is valid if only one of C1 and C2 is ever instantiated.
11354 //
11355 // FIXME: This need only apply to function definitions. For now, we proxy
11356 // this by checking for a file-scope function. We do not want this to apply
11357 // to friend declarations nominating member functions, because that gets in
11358 // the way of access checks.
11360 return false;
11361
11362 auto *VD = dyn_cast<ValueDecl>(D);
11363 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11364 return !VD || !PrevVD ||
11365 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11366 PrevVD->getType());
11367}
11368
11369/// Check the target or target_version attribute of the function for
11370/// MultiVersion validity.
11371///
11372/// Returns true if there was an error, false otherwise.
11373static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11374 const auto *TA = FD->getAttr<TargetAttr>();
11375 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11376
11377 assert((TA || TVA) && "Expecting target or target_version attribute");
11378
11380 enum ErrType { Feature = 0, Architecture = 1 };
11381
11382 if (TA) {
11383 ParsedTargetAttr ParseInfo =
11384 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11385 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11386 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11387 << Architecture << ParseInfo.CPU;
11388 return true;
11389 }
11390 for (const auto &Feat : ParseInfo.Features) {
11391 auto BareFeat = StringRef{Feat}.substr(1);
11392 if (Feat[0] == '-') {
11393 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11394 << Feature << ("no-" + BareFeat).str();
11395 return true;
11396 }
11397
11398 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11399 !TargetInfo.isValidFeatureName(BareFeat) ||
11400 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11401 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11402 << Feature << BareFeat;
11403 return true;
11404 }
11405 }
11406 }
11407
11408 if (TVA) {
11410 ParsedTargetAttr ParseInfo;
11411 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11412 ParseInfo =
11413 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11414 for (auto &Feat : ParseInfo.Features)
11415 Feats.push_back(StringRef{Feat}.substr(1));
11416 } else {
11417 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11418 TVA->getFeatures(Feats);
11419 }
11420 for (const auto &Feat : Feats) {
11421 if (!TargetInfo.validateCpuSupports(Feat)) {
11422 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11423 << Feature << Feat;
11424 return true;
11425 }
11426 }
11427 }
11428 return false;
11429}
11430
11431// Provide a white-list of attributes that are allowed to be combined with
11432// multiversion functions.
11434 MultiVersionKind MVKind) {
11435 // Note: this list/diagnosis must match the list in
11436 // checkMultiversionAttributesAllSame.
11437 switch (Kind) {
11438 default:
11439 return false;
11440 case attr::ArmLocallyStreaming:
11441 return MVKind == MultiVersionKind::TargetVersion ||
11443 case attr::Used:
11444 return MVKind == MultiVersionKind::Target;
11445 case attr::NonNull:
11446 case attr::NoThrow:
11447 return true;
11448 }
11449}
11450
11452 const FunctionDecl *FD,
11453 const FunctionDecl *CausedFD,
11454 MultiVersionKind MVKind) {
11455 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11456 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11457 << static_cast<unsigned>(MVKind) << A;
11458 if (CausedFD)
11459 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11460 return true;
11461 };
11462
11463 for (const Attr *A : FD->attrs()) {
11464 switch (A->getKind()) {
11465 case attr::CPUDispatch:
11466 case attr::CPUSpecific:
11467 if (MVKind != MultiVersionKind::CPUDispatch &&
11469 return Diagnose(S, A);
11470 break;
11471 case attr::Target:
11472 if (MVKind != MultiVersionKind::Target)
11473 return Diagnose(S, A);
11474 break;
11475 case attr::TargetVersion:
11476 if (MVKind != MultiVersionKind::TargetVersion &&
11478 return Diagnose(S, A);
11479 break;
11480 case attr::TargetClones:
11481 if (MVKind != MultiVersionKind::TargetClones &&
11483 return Diagnose(S, A);
11484 break;
11485 default:
11486 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11487 return Diagnose(S, A);
11488 break;
11489 }
11490 }
11491 return false;
11492}
11493
11495 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11496 const PartialDiagnostic &NoProtoDiagID,
11497 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11498 const PartialDiagnosticAt &NoSupportDiagIDAt,
11499 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11500 bool ConstexprSupported, bool CLinkageMayDiffer) {
11501 enum DoesntSupport {
11502 FuncTemplates = 0,
11503 VirtFuncs = 1,
11504 DeducedReturn = 2,
11505 Constructors = 3,
11506 Destructors = 4,
11507 DeletedFuncs = 5,
11508 DefaultedFuncs = 6,
11509 ConstexprFuncs = 7,
11510 ConstevalFuncs = 8,
11511 Lambda = 9,
11512 };
11513 enum Different {
11514 CallingConv = 0,
11515 ReturnType = 1,
11516 ConstexprSpec = 2,
11517 InlineSpec = 3,
11518 Linkage = 4,
11519 LanguageLinkage = 5,
11520 };
11521
11522 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11523 !OldFD->getType()->getAs<FunctionProtoType>()) {
11524 Diag(OldFD->getLocation(), NoProtoDiagID);
11525 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11526 return true;
11527 }
11528
11529 if (NoProtoDiagID.getDiagID() != 0 &&
11530 !NewFD->getType()->getAs<FunctionProtoType>())
11531 return Diag(NewFD->getLocation(), NoProtoDiagID);
11532
11533 if (!TemplatesSupported &&
11535 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11536 << FuncTemplates;
11537
11538 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11539 if (NewCXXFD->isVirtual())
11540 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11541 << VirtFuncs;
11542
11543 if (isa<CXXConstructorDecl>(NewCXXFD))
11544 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11545 << Constructors;
11546
11547 if (isa<CXXDestructorDecl>(NewCXXFD))
11548 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11549 << Destructors;
11550 }
11551
11552 if (NewFD->isDeleted())
11553 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11554 << DeletedFuncs;
11555
11556 if (NewFD->isDefaulted())
11557 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11558 << DefaultedFuncs;
11559
11560 if (!ConstexprSupported && NewFD->isConstexpr())
11561 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11562 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11563
11564 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11565 const auto *NewType = cast<FunctionType>(NewQType);
11566 QualType NewReturnType = NewType->getReturnType();
11567
11568 if (NewReturnType->isUndeducedType())
11569 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11570 << DeducedReturn;
11571
11572 // Ensure the return type is identical.
11573 if (OldFD) {
11574 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11575 const auto *OldType = cast<FunctionType>(OldQType);
11576 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11577 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11578
11579 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11580 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11581
11582 bool ArmStreamingCCMismatched = false;
11583 if (OldFPT && NewFPT) {
11584 unsigned Diff =
11585 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11586 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11587 // cannot be mixed.
11590 ArmStreamingCCMismatched = true;
11591 }
11592
11593 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11594 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11595
11596 QualType OldReturnType = OldType->getReturnType();
11597
11598 if (OldReturnType != NewReturnType)
11599 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11600
11601 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11602 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11603
11604 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11605 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11606
11607 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11608 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11609
11610 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11611 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11612
11613 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11614 NewFD->getLocation()))
11615 return true;
11616 }
11617 return false;
11618}
11619
11621 const FunctionDecl *NewFD,
11622 bool CausesMV,
11623 MultiVersionKind MVKind) {
11625 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11626 if (OldFD)
11627 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11628 return true;
11629 }
11630
11631 bool IsCPUSpecificCPUDispatchMVKind =
11634
11635 if (CausesMV && OldFD &&
11636 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11637 return true;
11638
11639 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11640 return true;
11641
11642 // Only allow transition to MultiVersion if it hasn't been used.
11643 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11644 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11645 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11646 return true;
11647 }
11648
11650 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11652 S.PDiag(diag::note_multiversioning_caused_here)),
11654 S.PDiag(diag::err_multiversion_doesnt_support)
11655 << static_cast<unsigned>(MVKind)),
11657 S.PDiag(diag::err_multiversion_diff)),
11658 /*TemplatesSupported=*/false,
11659 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11660 /*CLinkageMayDiffer=*/false);
11661}
11662
11663/// Check the validity of a multiversion function declaration that is the
11664/// first of its kind. Also sets the multiversion'ness' of the function itself.
11665///
11666/// This sets NewFD->isInvalidDecl() to true if there was an error.
11667///
11668/// Returns true if there was an error, false otherwise.
11671 assert(MVKind != MultiVersionKind::None &&
11672 "Function lacks multiversion attribute");
11673 const auto *TA = FD->getAttr<TargetAttr>();
11674 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11675 // The target attribute only causes MV if this declaration is the default,
11676 // otherwise it is treated as a normal function.
11677 if (TA && !TA->isDefaultVersion())
11678 return false;
11679
11680 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11681 FD->setInvalidDecl();
11682 return true;
11683 }
11684
11685 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11686 FD->setInvalidDecl();
11687 return true;
11688 }
11689
11690 FD->setIsMultiVersion();
11691 return false;
11692}
11693
11695 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11697 return true;
11698 }
11699
11700 return false;
11701}
11702
11704 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11705 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11706 return;
11707
11708 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11709 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11710
11711 if (MVKindTo == MultiVersionKind::None &&
11712 (MVKindFrom == MultiVersionKind::TargetVersion ||
11713 MVKindFrom == MultiVersionKind::TargetClones))
11714 To->addAttr(TargetVersionAttr::CreateImplicit(
11715 To->getASTContext(), "default", To->getSourceRange()));
11716}
11717
11719 FunctionDecl *NewFD,
11720 bool &Redeclaration,
11721 NamedDecl *&OldDecl,
11723 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11724
11725 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11726 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11727 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11728 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11729
11730 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11731
11732 // The definitions should be allowed in any order. If we have discovered
11733 // a new target version and the preceeding was the default, then add the
11734 // corresponding attribute to it.
11735 patchDefaultTargetVersion(NewFD, OldFD);
11736
11737 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11738 // to change, this is a simple redeclaration.
11739 if (NewTA && !NewTA->isDefaultVersion() &&
11740 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11741 return false;
11742
11743 // Otherwise, this decl causes MultiVersioning.
11744 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11747 NewFD->setInvalidDecl();
11748 return true;
11749 }
11750
11751 if (CheckMultiVersionValue(S, NewFD)) {
11752 NewFD->setInvalidDecl();
11753 return true;
11754 }
11755
11756 // If this is 'default', permit the forward declaration.
11757 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11758 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11759 Redeclaration = true;
11760 OldDecl = OldFD;
11761 OldFD->setIsMultiVersion();
11762 NewFD->setIsMultiVersion();
11763 return false;
11764 }
11765
11766 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11767 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11768 NewFD->setInvalidDecl();
11769 return true;
11770 }
11771
11772 if (NewTA) {
11773 ParsedTargetAttr OldParsed =
11775 OldTA->getFeaturesStr());
11776 llvm::sort(OldParsed.Features);
11777 ParsedTargetAttr NewParsed =
11779 NewTA->getFeaturesStr());
11780 // Sort order doesn't matter, it just needs to be consistent.
11781 llvm::sort(NewParsed.Features);
11782 if (OldParsed == NewParsed) {
11783 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11784 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11785 NewFD->setInvalidDecl();
11786 return true;
11787 }
11788 }
11789
11790 for (const auto *FD : OldFD->redecls()) {
11791 const auto *CurTA = FD->getAttr<TargetAttr>();
11792 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11793 // We allow forward declarations before ANY multiversioning attributes, but
11794 // nothing after the fact.
11796 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11797 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11798 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11799 << (NewTA ? 0 : 2);
11800 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11801 NewFD->setInvalidDecl();
11802 return true;
11803 }
11804 }
11805
11806 OldFD->setIsMultiVersion();
11807 NewFD->setIsMultiVersion();
11808 Redeclaration = false;
11809 OldDecl = nullptr;
11810 Previous.clear();
11811 return false;
11812}
11813
11815 MultiVersionKind OldKind = Old->getMultiVersionKind();
11816 MultiVersionKind NewKind = New->getMultiVersionKind();
11817
11818 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11819 NewKind == MultiVersionKind::None)
11820 return true;
11821
11822 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11823 switch (OldKind) {
11825 return NewKind == MultiVersionKind::TargetClones;
11827 return NewKind == MultiVersionKind::TargetVersion;
11828 default:
11829 return false;
11830 }
11831 } else {
11832 switch (OldKind) {
11834 return NewKind == MultiVersionKind::CPUSpecific;
11836 return NewKind == MultiVersionKind::CPUDispatch;
11837 default:
11838 return false;
11839 }
11840 }
11841}
11842
11843/// Check the validity of a new function declaration being added to an existing
11844/// multiversioned declaration collection.
11846 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11847 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11848 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11850
11851 // Disallow mixing of multiversioning types.
11852 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11853 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11854 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11855 NewFD->setInvalidDecl();
11856 return true;
11857 }
11858
11859 // Add the default target_version attribute if it's missing.
11860 patchDefaultTargetVersion(OldFD, NewFD);
11861 patchDefaultTargetVersion(NewFD, OldFD);
11862
11863 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11864 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11865 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11866 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11867
11868 ParsedTargetAttr NewParsed;
11869 if (NewTA) {
11871 NewTA->getFeaturesStr());
11872 llvm::sort(NewParsed.Features);
11873 }
11875 if (NewTVA) {
11876 NewTVA->getFeatures(NewFeats);
11877 llvm::sort(NewFeats);
11878 }
11879
11880 bool UseMemberUsingDeclRules =
11881 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11882
11883 bool MayNeedOverloadableChecks =
11885
11886 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11887 // of a previous member of the MultiVersion set.
11888 for (NamedDecl *ND : Previous) {
11889 FunctionDecl *CurFD = ND->getAsFunction();
11890 if (!CurFD || CurFD->isInvalidDecl())
11891 continue;
11892 if (MayNeedOverloadableChecks &&
11893 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11894 continue;
11895
11896 switch (NewMVKind) {
11898 assert(OldMVKind == MultiVersionKind::TargetClones &&
11899 "Only target_clones can be omitted in subsequent declarations");
11900 break;
11902 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11903 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11904 NewFD->setIsMultiVersion();
11905 Redeclaration = true;
11906 OldDecl = ND;
11907 return false;
11908 }
11909
11910 ParsedTargetAttr CurParsed =
11912 CurTA->getFeaturesStr());
11913 llvm::sort(CurParsed.Features);
11914 if (CurParsed == NewParsed) {
11915 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11916 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11917 NewFD->setInvalidDecl();
11918 return true;
11919 }
11920 break;
11921 }
11923 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11924 if (CurTVA->getName() == NewTVA->getName()) {
11925 NewFD->setIsMultiVersion();
11926 Redeclaration = true;
11927 OldDecl = ND;
11928 return false;
11929 }
11931 CurTVA->getFeatures(CurFeats);
11932 llvm::sort(CurFeats);
11933
11934 if (CurFeats == NewFeats) {
11935 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11936 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11937 NewFD->setInvalidDecl();
11938 return true;
11939 }
11940 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11941 // Default
11942 if (NewFeats.empty())
11943 break;
11944
11945 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11947 CurClones->getFeatures(CurFeats, I);
11948 llvm::sort(CurFeats);
11949
11950 if (CurFeats == NewFeats) {
11951 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11952 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11953 NewFD->setInvalidDecl();
11954 return true;
11955 }
11956 }
11957 }
11958 break;
11959 }
11961 assert(NewClones && "MultiVersionKind does not match attribute type");
11962 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11963 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11964 !std::equal(CurClones->featuresStrs_begin(),
11965 CurClones->featuresStrs_end(),
11966 NewClones->featuresStrs_begin())) {
11967 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11968 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11969 NewFD->setInvalidDecl();
11970 return true;
11971 }
11972 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11974 CurTVA->getFeatures(CurFeats);
11975 llvm::sort(CurFeats);
11976
11977 // Default
11978 if (CurFeats.empty())
11979 break;
11980
11981 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11982 NewFeats.clear();
11983 NewClones->getFeatures(NewFeats, I);
11984 llvm::sort(NewFeats);
11985
11986 if (CurFeats == NewFeats) {
11987 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11988 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11989 NewFD->setInvalidDecl();
11990 return true;
11991 }
11992 }
11993 break;
11994 }
11995 Redeclaration = true;
11996 OldDecl = CurFD;
11997 NewFD->setIsMultiVersion();
11998 return false;
11999 }
12002 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12003 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12004 // Handle CPUDispatch/CPUSpecific versions.
12005 // Only 1 CPUDispatch function is allowed, this will make it go through
12006 // the redeclaration errors.
12007 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12008 CurFD->hasAttr<CPUDispatchAttr>()) {
12009 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12010 std::equal(
12011 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
12012 NewCPUDisp->cpus_begin(),
12013 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12014 return Cur->getName() == New->getName();
12015 })) {
12016 NewFD->setIsMultiVersion();
12017 Redeclaration = true;
12018 OldDecl = ND;
12019 return false;
12020 }
12021
12022 // If the declarations don't match, this is an error condition.
12023 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
12024 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12025 NewFD->setInvalidDecl();
12026 return true;
12027 }
12028 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12029 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12030 std::equal(
12031 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
12032 NewCPUSpec->cpus_begin(),
12033 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12034 return Cur->getName() == New->getName();
12035 })) {
12036 NewFD->setIsMultiVersion();
12037 Redeclaration = true;
12038 OldDecl = ND;
12039 return false;
12040 }
12041
12042 // Only 1 version of CPUSpecific is allowed for each CPU.
12043 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12044 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12045 if (CurII == NewII) {
12046 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12047 << NewII;
12048 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12049 NewFD->setInvalidDecl();
12050 return true;
12051 }
12052 }
12053 }
12054 }
12055 break;
12056 }
12057 }
12058 }
12059
12060 // Redeclarations of a target_clones function may omit the attribute, in which
12061 // case it will be inherited during declaration merging.
12062 if (NewMVKind == MultiVersionKind::None &&
12063 OldMVKind == MultiVersionKind::TargetClones) {
12064 NewFD->setIsMultiVersion();
12065 Redeclaration = true;
12066 OldDecl = OldFD;
12067 return false;
12068 }
12069
12070 // Else, this is simply a non-redecl case. Checking the 'value' is only
12071 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12072 // handled in the attribute adding step.
12073 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12074 NewFD->setInvalidDecl();
12075 return true;
12076 }
12077
12078 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12079 !OldFD->isMultiVersion(), NewMVKind)) {
12080 NewFD->setInvalidDecl();
12081 return true;
12082 }
12083
12084 // Permit forward declarations in the case where these two are compatible.
12085 if (!OldFD->isMultiVersion()) {
12086 OldFD->setIsMultiVersion();
12087 NewFD->setIsMultiVersion();
12088 Redeclaration = true;
12089 OldDecl = OldFD;
12090 return false;
12091 }
12092
12093 NewFD->setIsMultiVersion();
12094 Redeclaration = false;
12095 OldDecl = nullptr;
12096 Previous.clear();
12097 return false;
12098}
12099
12100/// Check the validity of a mulitversion function declaration.
12101/// Also sets the multiversion'ness' of the function itself.
12102///
12103/// This sets NewFD->isInvalidDecl() to true if there was an error.
12104///
12105/// Returns true if there was an error, false otherwise.
12107 bool &Redeclaration, NamedDecl *&OldDecl,
12109 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12110
12111 // Check if FMV is disabled.
12112 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12113 return false;
12114
12115 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12116 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12117 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12118 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12119 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12120 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12121
12122 // Main isn't allowed to become a multiversion function, however it IS
12123 // permitted to have 'main' be marked with the 'target' optimization hint,
12124 // for 'target_version' only default is allowed.
12125 if (NewFD->isMain()) {
12126 if (MVKind != MultiVersionKind::None &&
12127 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12128 !(MVKind == MultiVersionKind::TargetVersion &&
12129 NewTVA->isDefaultVersion())) {
12130 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12131 NewFD->setInvalidDecl();
12132 return true;
12133 }
12134 return false;
12135 }
12136
12137 // Target attribute on AArch64 is not used for multiversioning
12138 if (NewTA && TI.getTriple().isAArch64())
12139 return false;
12140
12141 // Target attribute on RISCV is not used for multiversioning
12142 if (NewTA && TI.getTriple().isRISCV())
12143 return false;
12144
12145 if (!OldDecl || !OldDecl->getAsFunction() ||
12146 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12147 NewFD->getDeclContext()->getRedeclContext())) {
12148 // If there's no previous declaration, AND this isn't attempting to cause
12149 // multiversioning, this isn't an error condition.
12150 if (MVKind == MultiVersionKind::None)
12151 return false;
12152 return CheckMultiVersionFirstFunction(S, NewFD);
12153 }
12154
12155 FunctionDecl *OldFD = OldDecl->getAsFunction();
12156
12157 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12158 return false;
12159
12160 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12161 // for target_clones and target_version.
12162 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12165 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12167 NewFD->setInvalidDecl();
12168 return true;
12169 }
12170
12171 if (!OldFD->isMultiVersion()) {
12172 switch (MVKind) {
12176 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12178 if (OldFD->isUsed(false)) {
12179 NewFD->setInvalidDecl();
12180 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12181 }
12182 OldFD->setIsMultiVersion();
12183 break;
12184
12188 break;
12189 }
12190 }
12191
12192 // At this point, we have a multiversion function decl (in OldFD) AND an
12193 // appropriate attribute in the current function decl (unless it's allowed to
12194 // omit the attribute). Resolve that these are still compatible with previous
12195 // declarations.
12196 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12197 NewCPUSpec, NewClones, Redeclaration,
12198 OldDecl, Previous);
12199}
12200
12202 bool IsPure = NewFD->hasAttr<PureAttr>();
12203 bool IsConst = NewFD->hasAttr<ConstAttr>();
12204
12205 // If there are no pure or const attributes, there's nothing to check.
12206 if (!IsPure && !IsConst)
12207 return;
12208
12209 // If the function is marked both pure and const, we retain the const
12210 // attribute because it makes stronger guarantees than the pure attribute, and
12211 // we drop the pure attribute explicitly to prevent later confusion about
12212 // semantics.
12213 if (IsPure && IsConst) {
12214 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12215 NewFD->dropAttrs<PureAttr>();
12216 }
12217
12218 // Constructors and destructors are functions which return void, so are
12219 // handled here as well.
12220 if (NewFD->getReturnType()->isVoidType()) {
12221 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12222 << IsConst;
12223 NewFD->dropAttrs<PureAttr, ConstAttr>();
12224 }
12225}
12226
12229 bool IsMemberSpecialization,
12230 bool DeclIsDefn) {
12231 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12232 "Variably modified return types are not handled here");
12233
12234 // Determine whether the type of this function should be merged with
12235 // a previous visible declaration. This never happens for functions in C++,
12236 // and always happens in C if the previous declaration was visible.
12237 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12238 !Previous.isShadowed();
12239
12240 bool Redeclaration = false;
12241 NamedDecl *OldDecl = nullptr;
12242 bool MayNeedOverloadableChecks = false;
12243
12245 // Merge or overload the declaration with an existing declaration of
12246 // the same name, if appropriate.
12247 if (!Previous.empty()) {
12248 // Determine whether NewFD is an overload of PrevDecl or
12249 // a declaration that requires merging. If it's an overload,
12250 // there's no more work to do here; we'll just add the new
12251 // function to the scope.
12253 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12254 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12255 Redeclaration = true;
12256 OldDecl = Candidate;
12257 }
12258 } else {
12259 MayNeedOverloadableChecks = true;
12260 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12261 /*NewIsUsingDecl*/ false)) {
12263 Redeclaration = true;
12264 break;
12265
12267 Redeclaration = true;
12268 break;
12269
12271 Redeclaration = false;
12272 break;
12273 }
12274 }
12275 }
12276
12277 // Check for a previous extern "C" declaration with this name.
12278 if (!Redeclaration &&
12280 if (!Previous.empty()) {
12281 // This is an extern "C" declaration with the same name as a previous
12282 // declaration, and thus redeclares that entity...
12283 Redeclaration = true;
12284 OldDecl = Previous.getFoundDecl();
12285 MergeTypeWithPrevious = false;
12286
12287 // ... except in the presence of __attribute__((overloadable)).
12288 if (OldDecl->hasAttr<OverloadableAttr>() ||
12289 NewFD->hasAttr<OverloadableAttr>()) {
12290 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12291 MayNeedOverloadableChecks = true;
12292 Redeclaration = false;
12293 OldDecl = nullptr;
12294 }
12295 }
12296 }
12297 }
12298
12299 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12300 return Redeclaration;
12301
12302 // PPC MMA non-pointer types are not allowed as function return types.
12303 if (Context.getTargetInfo().getTriple().isPPC64() &&
12304 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12305 NewFD->setInvalidDecl();
12306 }
12307
12308 CheckConstPureAttributesUsage(*this, NewFD);
12309
12310 // C++ [dcl.spec.auto.general]p12:
12311 // Return type deduction for a templated function with a placeholder in its
12312 // declared type occurs when the definition is instantiated even if the
12313 // function body contains a return statement with a non-type-dependent
12314 // operand.
12315 //
12316 // C++ [temp.dep.expr]p3:
12317 // An id-expression is type-dependent if it is a template-id that is not a
12318 // concept-id and is dependent; or if its terminal name is:
12319 // - [...]
12320 // - associated by name lookup with one or more declarations of member
12321 // functions of a class that is the current instantiation declared with a
12322 // return type that contains a placeholder type,
12323 // - [...]
12324 //
12325 // If this is a templated function with a placeholder in its return type,
12326 // make the placeholder type dependent since it won't be deduced until the
12327 // definition is instantiated. We do this here because it needs to happen
12328 // for implicitly instantiated member functions/member function templates.
12329 if (getLangOpts().CPlusPlus14 &&
12330 (NewFD->isDependentContext() &&
12331 NewFD->getReturnType()->isUndeducedType())) {
12332 const FunctionProtoType *FPT =
12333 NewFD->getType()->castAs<FunctionProtoType>();
12334 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12335 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12336 FPT->getExtProtoInfo()));
12337 }
12338
12339 // C++11 [dcl.constexpr]p8:
12340 // A constexpr specifier for a non-static member function that is not
12341 // a constructor declares that member function to be const.
12342 //
12343 // This needs to be delayed until we know whether this is an out-of-line
12344 // definition of a static member function.
12345 //
12346 // This rule is not present in C++1y, so we produce a backwards
12347 // compatibility warning whenever it happens in C++11.
12348 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12349 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12350 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12352 CXXMethodDecl *OldMD = nullptr;
12353 if (OldDecl)
12354 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12355 if (!OldMD || !OldMD->isStatic()) {
12356 const FunctionProtoType *FPT =
12359 EPI.TypeQuals.addConst();
12360 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12361 FPT->getParamTypes(), EPI));
12362
12363 // Warn that we did this, if we're not performing template instantiation.
12364 // In that case, we'll have warned already when the template was defined.
12365 if (!inTemplateInstantiation()) {
12366 SourceLocation AddConstLoc;
12369 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12370
12371 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12372 << FixItHint::CreateInsertion(AddConstLoc, " const");
12373 }
12374 }
12375 }
12376
12377 if (Redeclaration) {
12378 // NewFD and OldDecl represent declarations that need to be
12379 // merged.
12380 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12381 DeclIsDefn)) {
12382 NewFD->setInvalidDecl();
12383 return Redeclaration;
12384 }
12385
12386 Previous.clear();
12387 Previous.addDecl(OldDecl);
12388
12389 if (FunctionTemplateDecl *OldTemplateDecl =
12390 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12391 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12392 FunctionTemplateDecl *NewTemplateDecl
12394 assert(NewTemplateDecl && "Template/non-template mismatch");
12395
12396 // The call to MergeFunctionDecl above may have created some state in
12397 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12398 // can add it as a redeclaration.
12399 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12400
12401 NewFD->setPreviousDeclaration(OldFD);
12402 if (NewFD->isCXXClassMember()) {
12403 NewFD->setAccess(OldTemplateDecl->getAccess());
12404 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12405 }
12406
12407 // If this is an explicit specialization of a member that is a function
12408 // template, mark it as a member specialization.
12409 if (IsMemberSpecialization &&
12410 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12411 NewTemplateDecl->setMemberSpecialization();
12412 assert(OldTemplateDecl->isMemberSpecialization());
12413 // Explicit specializations of a member template do not inherit deleted
12414 // status from the parent member template that they are specializing.
12415 if (OldFD->isDeleted()) {
12416 // FIXME: This assert will not hold in the presence of modules.
12417 assert(OldFD->getCanonicalDecl() == OldFD);
12418 // FIXME: We need an update record for this AST mutation.
12419 OldFD->setDeletedAsWritten(false);
12420 }
12421 }
12422
12423 } else {
12424 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12425 auto *OldFD = cast<FunctionDecl>(OldDecl);
12426 // This needs to happen first so that 'inline' propagates.
12427 NewFD->setPreviousDeclaration(OldFD);
12428 if (NewFD->isCXXClassMember())
12429 NewFD->setAccess(OldFD->getAccess());
12430 }
12431 }
12432 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12433 !NewFD->getAttr<OverloadableAttr>()) {
12434 assert((Previous.empty() ||
12435 llvm::any_of(Previous,
12436 [](const NamedDecl *ND) {
12437 return ND->hasAttr<OverloadableAttr>();
12438 })) &&
12439 "Non-redecls shouldn't happen without overloadable present");
12440
12441 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12442 const auto *FD = dyn_cast<FunctionDecl>(ND);
12443 return FD && !FD->hasAttr<OverloadableAttr>();
12444 });
12445
12446 if (OtherUnmarkedIter != Previous.end()) {
12447 Diag(NewFD->getLocation(),
12448 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12449 Diag((*OtherUnmarkedIter)->getLocation(),
12450 diag::note_attribute_overloadable_prev_overload)
12451 << false;
12452
12453 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12454 }
12455 }
12456
12457 if (LangOpts.OpenMP)
12459
12460 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12462
12463 if (NewFD->hasAttr<SYCLExternalAttr>())
12465
12466 // Semantic checking for this function declaration (in isolation).
12467
12468 if (getLangOpts().CPlusPlus) {
12469 // C++-specific checks.
12470 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12472 } else if (CXXDestructorDecl *Destructor =
12473 dyn_cast<CXXDestructorDecl>(NewFD)) {
12474 // We check here for invalid destructor names.
12475 // If we have a friend destructor declaration that is dependent, we can't
12476 // diagnose right away because cases like this are still valid:
12477 // template <class T> struct A { friend T::X::~Y(); };
12478 // struct B { struct Y { ~Y(); }; using X = Y; };
12479 // template struct A<B>;
12481 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12482 CanQualType ClassType =
12483 Context.getCanonicalTagType(Destructor->getParent());
12484
12485 DeclarationName Name =
12486 Context.DeclarationNames.getCXXDestructorName(ClassType);
12487 if (NewFD->getDeclName() != Name) {
12488 Diag(NewFD->getLocation(), diag::err_destructor_name);
12489 NewFD->setInvalidDecl();
12490 return Redeclaration;
12491 }
12492 }
12493 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12494 if (auto *TD = Guide->getDescribedFunctionTemplate())
12496
12497 // A deduction guide is not on the list of entities that can be
12498 // explicitly specialized.
12499 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12500 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12501 << /*explicit specialization*/ 1;
12502 }
12503
12504 // Find any virtual functions that this function overrides.
12505 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12506 if (!Method->isFunctionTemplateSpecialization() &&
12507 !Method->getDescribedFunctionTemplate() &&
12508 Method->isCanonicalDecl()) {
12509 AddOverriddenMethods(Method->getParent(), Method);
12510 }
12511 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12512 // C++2a [class.virtual]p6
12513 // A virtual method shall not have a requires-clause.
12515 diag::err_constrained_virtual_method);
12516
12517 if (Method->isStatic())
12519 }
12520
12521 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12522 ActOnConversionDeclarator(Conversion);
12523
12524 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12525 if (NewFD->isOverloadedOperator() &&
12527 NewFD->setInvalidDecl();
12528 return Redeclaration;
12529 }
12530
12531 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12532 if (NewFD->getLiteralIdentifier() &&
12534 NewFD->setInvalidDecl();
12535 return Redeclaration;
12536 }
12537
12538 // In C++, check default arguments now that we have merged decls. Unless
12539 // the lexical context is the class, because in this case this is done
12540 // during delayed parsing anyway.
12541 if (!CurContext->isRecord())
12543
12544 // If this function is declared as being extern "C", then check to see if
12545 // the function returns a UDT (class, struct, or union type) that is not C
12546 // compatible, and if it does, warn the user.
12547 // But, issue any diagnostic on the first declaration only.
12548 if (Previous.empty() && NewFD->isExternC()) {
12549 QualType R = NewFD->getReturnType();
12550 if (R->isIncompleteType() && !R->isVoidType())
12551 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12552 << NewFD << R;
12553 else if (!R.isPODType(Context) && !R->isVoidType() &&
12554 !R->isObjCObjectPointerType())
12555 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12556 }
12557
12558 // C++1z [dcl.fct]p6:
12559 // [...] whether the function has a non-throwing exception-specification
12560 // [is] part of the function type
12561 //
12562 // This results in an ABI break between C++14 and C++17 for functions whose
12563 // declared type includes an exception-specification in a parameter or
12564 // return type. (Exception specifications on the function itself are OK in
12565 // most cases, and exception specifications are not permitted in most other
12566 // contexts where they could make it into a mangling.)
12567 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12568 auto HasNoexcept = [&](QualType T) -> bool {
12569 // Strip off declarator chunks that could be between us and a function
12570 // type. We don't need to look far, exception specifications are very
12571 // restricted prior to C++17.
12572 if (auto *RT = T->getAs<ReferenceType>())
12573 T = RT->getPointeeType();
12574 else if (T->isAnyPointerType())
12575 T = T->getPointeeType();
12576 else if (auto *MPT = T->getAs<MemberPointerType>())
12577 T = MPT->getPointeeType();
12578 if (auto *FPT = T->getAs<FunctionProtoType>())
12579 if (FPT->isNothrow())
12580 return true;
12581 return false;
12582 };
12583
12584 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12585 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12586 for (QualType T : FPT->param_types())
12587 AnyNoexcept |= HasNoexcept(T);
12588 if (AnyNoexcept)
12589 Diag(NewFD->getLocation(),
12590 diag::warn_cxx17_compat_exception_spec_in_signature)
12591 << NewFD;
12592 }
12593
12594 if (!Redeclaration && LangOpts.CUDA) {
12595 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12596 for (auto *Parm : NewFD->parameters()) {
12597 if (!Parm->getType()->isDependentType() &&
12598 Parm->hasAttr<CUDAGridConstantAttr>() &&
12599 !(IsKernel && Parm->getType().isConstQualified()))
12600 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12601 diag::err_cuda_grid_constant_not_allowed);
12602 }
12604 }
12605 }
12606
12607 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12609
12610 return Redeclaration;
12611}
12612
12614 // [basic.start.main]p3
12615 // The main function shall not be declared with C linkage-specification.
12616 if (FD->isExternCContext())
12617 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12618
12619 // C++11 [basic.start.main]p3:
12620 // A program that [...] declares main to be inline, static or
12621 // constexpr is ill-formed.
12622 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12623 // appear in a declaration of main.
12624 // static main is not an error under C99, but we should warn about it.
12625 // We accept _Noreturn main as an extension.
12626 if (FD->getStorageClass() == SC_Static)
12628 ? diag::err_static_main : diag::warn_static_main)
12630 if (FD->isInlineSpecified())
12631 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12633 if (DS.isNoreturnSpecified()) {
12634 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12635 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12636 Diag(NoreturnLoc, diag::ext_noreturn_main);
12637 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12638 << FixItHint::CreateRemoval(NoreturnRange);
12639 }
12640 if (FD->isConstexpr()) {
12641 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12642 << FD->isConsteval()
12645 }
12646
12647 if (getLangOpts().OpenCL) {
12648 Diag(FD->getLocation(), diag::err_opencl_no_main)
12649 << FD->hasAttr<DeviceKernelAttr>();
12650 FD->setInvalidDecl();
12651 return;
12652 }
12653
12654 if (FD->hasAttr<SYCLExternalAttr>()) {
12655 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12656 << FD->getAttr<SYCLExternalAttr>();
12657 FD->setInvalidDecl();
12658 return;
12659 }
12660
12661 // Functions named main in hlsl are default entries, but don't have specific
12662 // signatures they are required to conform to.
12663 if (getLangOpts().HLSL)
12664 return;
12665
12666 QualType T = FD->getType();
12667 assert(T->isFunctionType() && "function decl is not of function type");
12668 const FunctionType* FT = T->castAs<FunctionType>();
12669
12670 // Set default calling convention for main()
12671 if (FT->getCallConv() != CC_C) {
12672 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12673 FD->setType(QualType(FT, 0));
12674 T = Context.getCanonicalType(FD->getType());
12675 }
12676
12678 // In C with GNU extensions we allow main() to have non-integer return
12679 // type, but we should warn about the extension, and we disable the
12680 // implicit-return-zero rule.
12681
12682 // GCC in C mode accepts qualified 'int'.
12683 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12684 FD->setHasImplicitReturnZero(true);
12685 else {
12686 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12687 SourceRange RTRange = FD->getReturnTypeSourceRange();
12688 if (RTRange.isValid())
12689 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12690 << FixItHint::CreateReplacement(RTRange, "int");
12691 }
12692 } else {
12693 // In C and C++, main magically returns 0 if you fall off the end;
12694 // set the flag which tells us that.
12695 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12696
12697 // All the standards say that main() should return 'int'.
12698 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12699 FD->setHasImplicitReturnZero(true);
12700 else {
12701 // Otherwise, this is just a flat-out error.
12702 SourceRange RTRange = FD->getReturnTypeSourceRange();
12703 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12704 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12705 : FixItHint());
12706 FD->setInvalidDecl(true);
12707 }
12708
12709 // [basic.start.main]p3:
12710 // A program that declares a function main that belongs to the global scope
12711 // and is attached to a named module is ill-formed.
12712 if (FD->isInNamedModule()) {
12713 const SourceLocation start = FD->getTypeSpecStartLoc();
12714 Diag(start, diag::warn_main_in_named_module)
12715 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12716 }
12717 }
12718
12719 // Treat protoless main() as nullary.
12720 if (isa<FunctionNoProtoType>(FT)) return;
12721
12723 unsigned nparams = FTP->getNumParams();
12724 assert(FD->getNumParams() == nparams);
12725
12726 bool HasExtraParameters = (nparams > 3);
12727
12728 if (FTP->isVariadic()) {
12729 Diag(FD->getLocation(), diag::ext_variadic_main);
12730 // FIXME: if we had information about the location of the ellipsis, we
12731 // could add a FixIt hint to remove it as a parameter.
12732 }
12733
12734 // Darwin passes an undocumented fourth argument of type char**. If
12735 // other platforms start sprouting these, the logic below will start
12736 // getting shifty.
12737 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12738 HasExtraParameters = false;
12739
12740 if (HasExtraParameters) {
12741 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12742 FD->setInvalidDecl(true);
12743 nparams = 3;
12744 }
12745
12746 // FIXME: a lot of the following diagnostics would be improved
12747 // if we had some location information about types.
12748
12749 QualType CharPP =
12750 Context.getPointerType(Context.getPointerType(Context.CharTy));
12751 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12752
12753 for (unsigned i = 0; i < nparams; ++i) {
12754 QualType AT = FTP->getParamType(i);
12755
12756 bool mismatch = true;
12757
12758 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12759 mismatch = false;
12760 else if (Expected[i] == CharPP) {
12761 // As an extension, the following forms are okay:
12762 // char const **
12763 // char const * const *
12764 // char * const *
12765
12767 const PointerType* PT;
12768 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12769 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12770 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12771 Context.CharTy)) {
12772 qs.removeConst();
12773 mismatch = !qs.empty();
12774 }
12775 }
12776
12777 if (mismatch) {
12778 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12779 // TODO: suggest replacing given type with expected type
12780 FD->setInvalidDecl(true);
12781 }
12782 }
12783
12784 if (nparams == 1 && !FD->isInvalidDecl()) {
12785 Diag(FD->getLocation(), diag::warn_main_one_arg);
12786 }
12787
12788 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12789 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12790 FD->setInvalidDecl();
12791 }
12792}
12793
12794static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12795
12796 // Default calling convention for main and wmain is __cdecl
12797 if (FD->getName() == "main" || FD->getName() == "wmain")
12798 return false;
12799
12800 // Default calling convention for MinGW and Cygwin is __cdecl
12801 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12802 if (T.isOSCygMing())
12803 return false;
12804
12805 // Default calling convention for WinMain, wWinMain and DllMain
12806 // is __stdcall on 32 bit Windows
12807 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12808 return true;
12809
12810 return false;
12811}
12812
12814 QualType T = FD->getType();
12815 assert(T->isFunctionType() && "function decl is not of function type");
12816 const FunctionType *FT = T->castAs<FunctionType>();
12817
12818 // Set an implicit return of 'zero' if the function can return some integral,
12819 // enumeration, pointer or nullptr type.
12823 // DllMain is exempt because a return value of zero means it failed.
12824 if (FD->getName() != "DllMain")
12825 FD->setHasImplicitReturnZero(true);
12826
12827 // Explicitly specified calling conventions are applied to MSVC entry points
12828 if (!hasExplicitCallingConv(T)) {
12829 if (isDefaultStdCall(FD, *this)) {
12830 if (FT->getCallConv() != CC_X86StdCall) {
12831 FT = Context.adjustFunctionType(
12833 FD->setType(QualType(FT, 0));
12834 }
12835 } else if (FT->getCallConv() != CC_C) {
12836 FT = Context.adjustFunctionType(FT,
12838 FD->setType(QualType(FT, 0));
12839 }
12840 }
12841
12842 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12843 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12844 FD->setInvalidDecl();
12845 }
12846}
12847
12849 // FIXME: Need strict checking. In C89, we need to check for
12850 // any assignment, increment, decrement, function-calls, or
12851 // commas outside of a sizeof. In C99, it's the same list,
12852 // except that the aforementioned are allowed in unevaluated
12853 // expressions. Everything else falls under the
12854 // "may accept other forms of constant expressions" exception.
12855 //
12856 // Regular C++ code will not end up here (exceptions: language extensions,
12857 // OpenCL C++ etc), so the constant expression rules there don't matter.
12858 if (Init->isValueDependent()) {
12859 assert(Init->containsErrors() &&
12860 "Dependent code should only occur in error-recovery path.");
12861 return true;
12862 }
12863 const Expr *Culprit;
12864 if (Init->isConstantInitializer(Context, /*ForRef=*/false, &Culprit))
12865 return false;
12866
12867 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
12868 if (getLangOpts().ObjCConstantLiterals && isa<ObjCObjectLiteral>(Culprit)) {
12869
12870 // For collection literals iterate the elements to highlight which one is
12871 // the offender.
12872 if (auto ALE = dyn_cast<ObjCArrayLiteral>(Init)) {
12873 for (auto *Elm : ALE->elements()) {
12874 if (!Elm->isConstantInitializer(Context)) {
12875 Diag(Elm->getExprLoc(),
12876 diag::err_objc_literal_nonconstant_at_file_scope)
12877 << ObjC().CheckLiteralKind(Init) << Elm->getSourceRange();
12878 return true;
12879 }
12880 }
12881 }
12882
12883 if (auto DLE = dyn_cast<ObjCDictionaryLiteral>(Init)) {
12884 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
12885 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(I);
12886
12887 // Check that the key is a string literal and is constant.
12888 if (!isa<ObjCStringLiteral>(Elm.Key) ||
12890 Diag(Elm.Key->getExprLoc(),
12891 diag::err_objc_literal_nonconstant_at_file_scope)
12893 return true;
12894 }
12895
12896 if (!Elm.Value->isConstantInitializer(Context)) {
12897 Diag(Elm.Value->getExprLoc(),
12898 diag::err_objc_literal_nonconstant_at_file_scope)
12900 return true;
12901 }
12902 }
12903 }
12904
12905 Diag(Culprit->getExprLoc(),
12906 diag::err_objc_literal_nonconstant_at_file_scope)
12907 << ObjC().CheckLiteralKind(Init) << Culprit->getSourceRange();
12908 return true;
12909 }
12910
12911 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12912 return true;
12913}
12914
12915namespace {
12916 // Visits an initialization expression to see if OrigDecl is evaluated in
12917 // its own initialization and throws a warning if it does.
12918 class SelfReferenceChecker
12919 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12920 Sema &S;
12921 Decl *OrigDecl;
12922 bool isRecordType;
12923 bool isPODType;
12924 bool isReferenceType;
12925 bool isInCXXOperatorCall;
12926
12927 bool isInitList;
12928 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12929
12930 public:
12932
12933 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12934 S(S), OrigDecl(OrigDecl) {
12935 isPODType = false;
12936 isRecordType = false;
12937 isReferenceType = false;
12938 isInCXXOperatorCall = false;
12939 isInitList = false;
12940 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12941 isPODType = VD->getType().isPODType(S.Context);
12942 isRecordType = VD->getType()->isRecordType();
12943 isReferenceType = VD->getType()->isReferenceType();
12944 }
12945 }
12946
12947 // For most expressions, just call the visitor. For initializer lists,
12948 // track the index of the field being initialized since fields are
12949 // initialized in order allowing use of previously initialized fields.
12950 void CheckExpr(Expr *E) {
12951 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12952 if (!InitList) {
12953 Visit(E);
12954 return;
12955 }
12956
12957 // Track and increment the index here.
12958 isInitList = true;
12959 InitFieldIndex.push_back(0);
12960 for (auto *Child : InitList->children()) {
12961 CheckExpr(cast<Expr>(Child));
12962 ++InitFieldIndex.back();
12963 }
12964 InitFieldIndex.pop_back();
12965 }
12966
12967 // Returns true if MemberExpr is checked and no further checking is needed.
12968 // Returns false if additional checking is required.
12969 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12970 llvm::SmallVector<FieldDecl*, 4> Fields;
12971 Expr *Base = E;
12972 bool ReferenceField = false;
12973
12974 // Get the field members used.
12975 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12976 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12977 if (!FD)
12978 return false;
12979 Fields.push_back(FD);
12980 if (FD->getType()->isReferenceType())
12981 ReferenceField = true;
12982 Base = ME->getBase()->IgnoreParenImpCasts();
12983 }
12984
12985 // Keep checking only if the base Decl is the same.
12986 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12987 if (!DRE || DRE->getDecl() != OrigDecl)
12988 return false;
12989
12990 // A reference field can be bound to an unininitialized field.
12991 if (CheckReference && !ReferenceField)
12992 return true;
12993
12994 // Convert FieldDecls to their index number.
12995 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12996 for (const FieldDecl *I : llvm::reverse(Fields))
12997 UsedFieldIndex.push_back(I->getFieldIndex());
12998
12999 // See if a warning is needed by checking the first difference in index
13000 // numbers. If field being used has index less than the field being
13001 // initialized, then the use is safe.
13002 for (auto UsedIter = UsedFieldIndex.begin(),
13003 UsedEnd = UsedFieldIndex.end(),
13004 OrigIter = InitFieldIndex.begin(),
13005 OrigEnd = InitFieldIndex.end();
13006 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13007 if (*UsedIter < *OrigIter)
13008 return true;
13009 if (*UsedIter > *OrigIter)
13010 break;
13011 }
13012
13013 // TODO: Add a different warning which will print the field names.
13014 HandleDeclRefExpr(DRE);
13015 return true;
13016 }
13017
13018 // For most expressions, the cast is directly above the DeclRefExpr.
13019 // For conditional operators, the cast can be outside the conditional
13020 // operator if both expressions are DeclRefExpr's.
13021 void HandleValue(Expr *E) {
13022 E = E->IgnoreParens();
13023 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
13024 HandleDeclRefExpr(DRE);
13025 return;
13026 }
13027
13028 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
13029 Visit(CO->getCond());
13030 HandleValue(CO->getTrueExpr());
13031 HandleValue(CO->getFalseExpr());
13032 return;
13033 }
13034
13035 if (BinaryConditionalOperator *BCO =
13036 dyn_cast<BinaryConditionalOperator>(E)) {
13037 Visit(BCO->getCond());
13038 HandleValue(BCO->getFalseExpr());
13039 return;
13040 }
13041
13042 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
13043 if (Expr *SE = OVE->getSourceExpr())
13044 HandleValue(SE);
13045 return;
13046 }
13047
13048 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13049 if (BO->getOpcode() == BO_Comma) {
13050 Visit(BO->getLHS());
13051 HandleValue(BO->getRHS());
13052 return;
13053 }
13054 }
13055
13056 if (isa<MemberExpr>(E)) {
13057 if (isInitList) {
13058 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
13059 false /*CheckReference*/))
13060 return;
13061 }
13062
13063 Expr *Base = E->IgnoreParenImpCasts();
13064 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13065 // Check for static member variables and don't warn on them.
13066 if (!isa<FieldDecl>(ME->getMemberDecl()))
13067 return;
13068 Base = ME->getBase()->IgnoreParenImpCasts();
13069 }
13070 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
13071 HandleDeclRefExpr(DRE);
13072 return;
13073 }
13074
13075 Visit(E);
13076 }
13077
13078 // Reference types not handled in HandleValue are handled here since all
13079 // uses of references are bad, not just r-value uses.
13080 void VisitDeclRefExpr(DeclRefExpr *E) {
13081 if (isReferenceType)
13082 HandleDeclRefExpr(E);
13083 }
13084
13085 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13086 if (E->getCastKind() == CK_LValueToRValue) {
13087 HandleValue(E->getSubExpr());
13088 return;
13089 }
13090
13091 Inherited::VisitImplicitCastExpr(E);
13092 }
13093
13094 void VisitMemberExpr(MemberExpr *E) {
13095 if (isInitList) {
13096 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13097 return;
13098 }
13099
13100 // Don't warn on arrays since they can be treated as pointers.
13101 if (E->getType()->canDecayToPointerType()) return;
13102
13103 // Warn when a non-static method call is followed by non-static member
13104 // field accesses, which is followed by a DeclRefExpr.
13105 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13106 bool Warn = (MD && !MD->isStatic());
13107 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13108 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13109 if (!isa<FieldDecl>(ME->getMemberDecl()))
13110 Warn = false;
13111 Base = ME->getBase()->IgnoreParenImpCasts();
13112 }
13113
13114 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13115 if (Warn)
13116 HandleDeclRefExpr(DRE);
13117 return;
13118 }
13119
13120 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13121 // Visit that expression.
13122 Visit(Base);
13123 }
13124
13125 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13126 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13127 Expr *Callee = E->getCallee();
13128
13129 if (isa<UnresolvedLookupExpr>(Callee))
13130 return Inherited::VisitCXXOperatorCallExpr(E);
13131
13132 Visit(Callee);
13133 for (auto Arg: E->arguments())
13134 HandleValue(Arg->IgnoreParenImpCasts());
13135 }
13136
13137 void VisitLambdaExpr(LambdaExpr *E) {
13138 if (!isInCXXOperatorCall) {
13139 Inherited::VisitLambdaExpr(E);
13140 return;
13141 }
13142
13143 for (Expr *Init : E->capture_inits())
13144 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13145 HandleDeclRefExpr(DRE);
13146 else if (Init)
13147 Visit(Init);
13148 }
13149
13150 void VisitUnaryOperator(UnaryOperator *E) {
13151 // For POD record types, addresses of its own members are well-defined.
13152 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13154 if (!isPODType)
13155 HandleValue(E->getSubExpr());
13156 return;
13157 }
13158
13159 if (E->isIncrementDecrementOp()) {
13160 HandleValue(E->getSubExpr());
13161 return;
13162 }
13163
13164 Inherited::VisitUnaryOperator(E);
13165 }
13166
13167 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13168
13169 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13170 if (E->getConstructor()->isCopyConstructor()) {
13171 Expr *ArgExpr = E->getArg(0);
13172 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13173 if (ILE->getNumInits() == 1)
13174 ArgExpr = ILE->getInit(0);
13175 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13176 if (ICE->getCastKind() == CK_NoOp)
13177 ArgExpr = ICE->getSubExpr();
13178 HandleValue(ArgExpr);
13179 return;
13180 }
13181 Inherited::VisitCXXConstructExpr(E);
13182 }
13183
13184 void VisitCallExpr(CallExpr *E) {
13185 // Treat std::move as a use.
13186 if (E->isCallToStdMove()) {
13187 HandleValue(E->getArg(0));
13188 return;
13189 }
13190
13191 Inherited::VisitCallExpr(E);
13192 }
13193
13194 void VisitBinaryOperator(BinaryOperator *E) {
13195 if (E->isCompoundAssignmentOp()) {
13196 HandleValue(E->getLHS());
13197 Visit(E->getRHS());
13198 return;
13199 }
13200
13201 Inherited::VisitBinaryOperator(E);
13202 }
13203
13204 // A custom visitor for BinaryConditionalOperator is needed because the
13205 // regular visitor would check the condition and true expression separately
13206 // but both point to the same place giving duplicate diagnostics.
13207 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13208 Visit(E->getCond());
13209 Visit(E->getFalseExpr());
13210 }
13211
13212 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13213 Decl* ReferenceDecl = DRE->getDecl();
13214 if (OrigDecl != ReferenceDecl) return;
13215 unsigned diag;
13216 if (isReferenceType) {
13217 diag = diag::warn_uninit_self_reference_in_reference_init;
13218 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13219 diag = diag::warn_static_self_reference_in_init;
13220 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13221 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13222 DRE->getDecl()->getType()->isRecordType()) {
13223 diag = diag::warn_uninit_self_reference_in_init;
13224 } else {
13225 // Local variables will be handled by the CFG analysis.
13226 return;
13227 }
13228
13229 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13230 S.PDiag(diag)
13231 << DRE->getDecl() << OrigDecl->getLocation()
13232 << DRE->getSourceRange());
13233 }
13234 };
13235
13236 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13237 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13238 bool DirectInit) {
13239 // Parameters arguments are occassionially constructed with itself,
13240 // for instance, in recursive functions. Skip them.
13241 if (isa<ParmVarDecl>(OrigDecl))
13242 return;
13243
13244 // Skip checking for file-scope constexpr variables - constant evaluation
13245 // will produce appropriate errors without needing runtime diagnostics.
13246 // Local constexpr should still emit runtime warnings.
13247 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13248 VD && VD->isConstexpr() && VD->isFileVarDecl())
13249 return;
13250
13251 E = E->IgnoreParens();
13252
13253 // Skip checking T a = a where T is not a record or reference type.
13254 // Doing so is a way to silence uninitialized warnings.
13255 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13256 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13257 if (ICE->getCastKind() == CK_LValueToRValue)
13258 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13259 if (DRE->getDecl() == OrigDecl)
13260 return;
13261
13262 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13263 }
13264} // end anonymous namespace
13265
13266namespace {
13267 // Simple wrapper to add the name of a variable or (if no variable is
13268 // available) a DeclarationName into a diagnostic.
13269 struct VarDeclOrName {
13270 VarDecl *VDecl;
13271 DeclarationName Name;
13272
13273 friend const Sema::SemaDiagnosticBuilder &
13274 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13275 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13276 }
13277 };
13278} // end anonymous namespace
13279
13282 TypeSourceInfo *TSI,
13283 SourceRange Range, bool DirectInit,
13284 Expr *Init) {
13285 bool IsInitCapture = !VDecl;
13286 assert((!VDecl || !VDecl->isInitCapture()) &&
13287 "init captures are expected to be deduced prior to initialization");
13288
13289 VarDeclOrName VN{VDecl, Name};
13290
13291 DeducedType *Deduced = Type->getContainedDeducedType();
13292 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13293
13294 // Diagnose auto array declarations in C23, unless it's a supported extension.
13295 if (getLangOpts().C23 && Type->isArrayType() &&
13296 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13297 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13298 << (int)Deduced->getContainedAutoType()->getKeyword()
13299 << /*in array decl*/ 23 << Range;
13300 return QualType();
13301 }
13302
13303 // C++11 [dcl.spec.auto]p3
13304 if (!Init) {
13305 assert(VDecl && "no init for init capture deduction?");
13306
13307 // Except for class argument deduction, and then for an initializing
13308 // declaration only, i.e. no static at class scope or extern.
13310 VDecl->hasExternalStorage() ||
13311 VDecl->isStaticDataMember()) {
13312 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13313 << VDecl->getDeclName() << Type;
13314 return QualType();
13315 }
13316 }
13317
13318 ArrayRef<Expr*> DeduceInits;
13319 if (Init)
13320 DeduceInits = Init;
13321
13322 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13323 if (DirectInit && PL)
13324 DeduceInits = PL->exprs();
13325
13327 assert(VDecl && "non-auto type for init capture deduction?");
13330 VDecl->getLocation(), DirectInit, Init);
13331 // FIXME: Initialization should not be taking a mutable list of inits.
13332 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13333 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13334 InitsCopy);
13335 }
13336
13337 if (DirectInit) {
13338 if (auto *IL = dyn_cast<InitListExpr>(Init))
13339 DeduceInits = IL->inits();
13340 }
13341
13342 // Deduction only works if we have exactly one source expression.
13343 if (DeduceInits.empty()) {
13344 // It isn't possible to write this directly, but it is possible to
13345 // end up in this situation with "auto x(some_pack...);"
13346 Diag(Init->getBeginLoc(), IsInitCapture
13347 ? diag::err_init_capture_no_expression
13348 : diag::err_auto_var_init_no_expression)
13349 << VN << Type << Range;
13350 return QualType();
13351 }
13352
13353 if (DeduceInits.size() > 1) {
13354 Diag(DeduceInits[1]->getBeginLoc(),
13355 IsInitCapture ? diag::err_init_capture_multiple_expressions
13356 : diag::err_auto_var_init_multiple_expressions)
13357 << VN << Type << Range;
13358 return QualType();
13359 }
13360
13361 Expr *DeduceInit = DeduceInits[0];
13362 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13363 Diag(Init->getBeginLoc(), IsInitCapture
13364 ? diag::err_init_capture_paren_braces
13365 : diag::err_auto_var_init_paren_braces)
13366 << isa<InitListExpr>(Init) << VN << Type << Range;
13367 return QualType();
13368 }
13369
13370 // Expressions default to 'id' when we're in a debugger.
13371 bool DefaultedAnyToId = false;
13372 if (getLangOpts().DebuggerCastResultToId &&
13373 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13375 if (Result.isInvalid()) {
13376 return QualType();
13377 }
13378 Init = Result.get();
13379 DefaultedAnyToId = true;
13380 }
13381
13382 // C++ [dcl.decomp]p1:
13383 // If the assignment-expression [...] has array type A and no ref-qualifier
13384 // is present, e has type cv A
13385 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13386 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13387 DeduceInit->getType()->isConstantArrayType())
13388 return Context.getQualifiedType(DeduceInit->getType(),
13389 Type.getQualifiers());
13390
13391 QualType DeducedType;
13392 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13394 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13397 if (!IsInitCapture)
13398 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13399 else if (isa<InitListExpr>(Init))
13400 Diag(Range.getBegin(),
13401 diag::err_init_capture_deduction_failure_from_init_list)
13402 << VN
13403 << (DeduceInit->getType().isNull() ? TSI->getType()
13404 : DeduceInit->getType())
13405 << DeduceInit->getSourceRange();
13406 else
13407 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13408 << VN << TSI->getType()
13409 << (DeduceInit->getType().isNull() ? TSI->getType()
13410 : DeduceInit->getType())
13411 << DeduceInit->getSourceRange();
13412 }
13413
13414 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13415 // 'id' instead of a specific object type prevents most of our usual
13416 // checks.
13417 // We only want to warn outside of template instantiations, though:
13418 // inside a template, the 'id' could have come from a parameter.
13419 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13420 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13421 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13422 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13423 }
13424
13425 return DeducedType;
13426}
13427
13429 Expr *Init) {
13430 assert(!Init || !Init->containsErrors());
13432 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13433 VDecl->getSourceRange(), DirectInit, Init);
13434 if (DeducedType.isNull()) {
13435 VDecl->setInvalidDecl();
13436 return true;
13437 }
13438
13439 VDecl->setType(DeducedType);
13440 assert(VDecl->isLinkageValid());
13441
13442 // In ARC, infer lifetime.
13443 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13444 VDecl->setInvalidDecl();
13445
13446 if (getLangOpts().OpenCL)
13448
13449 if (getLangOpts().HLSL)
13450 HLSL().deduceAddressSpace(VDecl);
13451
13452 // If this is a redeclaration, check that the type we just deduced matches
13453 // the previously declared type.
13454 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13455 // We never need to merge the type, because we cannot form an incomplete
13456 // array of auto, nor deduce such a type.
13457 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13458 }
13459
13460 // Check the deduced type is valid for a variable declaration.
13462 return VDecl->isInvalidDecl();
13463}
13464
13466 SourceLocation Loc) {
13467 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13468 Init = EWC->getSubExpr();
13469
13470 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13471 Init = CE->getSubExpr();
13472
13473 QualType InitType = Init->getType();
13476 "shouldn't be called if type doesn't have a non-trivial C struct");
13477 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13478 for (auto *I : ILE->inits()) {
13479 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13480 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13481 continue;
13482 SourceLocation SL = I->getExprLoc();
13483 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13484 }
13485 return;
13486 }
13487
13490 checkNonTrivialCUnion(InitType, Loc,
13492 NTCUK_Init);
13493 } else {
13494 // Assume all other explicit initializers involving copying some existing
13495 // object.
13496 // TODO: ignore any explicit initializers where we can guarantee
13497 // copy-elision.
13500 NTCUK_Copy);
13501 }
13502}
13503
13504namespace {
13505
13506bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13507 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13508 // in the source code or implicitly by the compiler if it is in a union
13509 // defined in a system header and has non-trivial ObjC ownership
13510 // qualifications. We don't want those fields to participate in determining
13511 // whether the containing union is non-trivial.
13512 return FD->hasAttr<UnavailableAttr>();
13513}
13514
13515struct DiagNonTrivalCUnionDefaultInitializeVisitor
13516 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13517 void> {
13518 using Super =
13519 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13520 void>;
13521
13522 DiagNonTrivalCUnionDefaultInitializeVisitor(
13523 QualType OrigTy, SourceLocation OrigLoc,
13524 NonTrivialCUnionContext UseContext, Sema &S)
13525 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13526
13527 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13528 const FieldDecl *FD, bool InNonTrivialUnion) {
13529 if (const auto *AT = S.Context.getAsArrayType(QT))
13530 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13531 InNonTrivialUnion);
13532 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13533 }
13534
13535 void visitARCStrong(QualType QT, const FieldDecl *FD,
13536 bool InNonTrivialUnion) {
13537 if (InNonTrivialUnion)
13538 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13539 << 1 << 0 << QT << FD->getName();
13540 }
13541
13542 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13543 if (InNonTrivialUnion)
13544 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13545 << 1 << 0 << QT << FD->getName();
13546 }
13547
13548 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13549 const auto *RD = QT->castAsRecordDecl();
13550 if (RD->isUnion()) {
13551 if (OrigLoc.isValid()) {
13552 bool IsUnion = false;
13553 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13554 IsUnion = OrigRD->isUnion();
13555 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13556 << 0 << OrigTy << IsUnion << UseContext;
13557 // Reset OrigLoc so that this diagnostic is emitted only once.
13558 OrigLoc = SourceLocation();
13559 }
13560 InNonTrivialUnion = true;
13561 }
13562
13563 if (InNonTrivialUnion)
13564 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13565 << 0 << 0 << QT.getUnqualifiedType() << "";
13566
13567 for (const FieldDecl *FD : RD->fields())
13568 if (!shouldIgnoreForRecordTriviality(FD))
13569 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13570 }
13571
13572 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13573
13574 // The non-trivial C union type or the struct/union type that contains a
13575 // non-trivial C union.
13576 QualType OrigTy;
13577 SourceLocation OrigLoc;
13578 NonTrivialCUnionContext UseContext;
13579 Sema &S;
13580};
13581
13582struct DiagNonTrivalCUnionDestructedTypeVisitor
13583 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13584 using Super =
13585 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13586
13587 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13588 SourceLocation OrigLoc,
13589 NonTrivialCUnionContext UseContext,
13590 Sema &S)
13591 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13592
13593 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13594 const FieldDecl *FD, bool InNonTrivialUnion) {
13595 if (const auto *AT = S.Context.getAsArrayType(QT))
13596 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13597 InNonTrivialUnion);
13598 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13599 }
13600
13601 void visitARCStrong(QualType QT, const FieldDecl *FD,
13602 bool InNonTrivialUnion) {
13603 if (InNonTrivialUnion)
13604 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13605 << 1 << 1 << QT << FD->getName();
13606 }
13607
13608 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13609 if (InNonTrivialUnion)
13610 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13611 << 1 << 1 << QT << FD->getName();
13612 }
13613
13614 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13615 const auto *RD = QT->castAsRecordDecl();
13616 if (RD->isUnion()) {
13617 if (OrigLoc.isValid()) {
13618 bool IsUnion = false;
13619 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13620 IsUnion = OrigRD->isUnion();
13621 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13622 << 1 << OrigTy << IsUnion << UseContext;
13623 // Reset OrigLoc so that this diagnostic is emitted only once.
13624 OrigLoc = SourceLocation();
13625 }
13626 InNonTrivialUnion = true;
13627 }
13628
13629 if (InNonTrivialUnion)
13630 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13631 << 0 << 1 << QT.getUnqualifiedType() << "";
13632
13633 for (const FieldDecl *FD : RD->fields())
13634 if (!shouldIgnoreForRecordTriviality(FD))
13635 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13636 }
13637
13638 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13639 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13640 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 DiagNonTrivalCUnionCopyVisitor
13651 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13652 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13653
13654 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13655 NonTrivialCUnionContext UseContext, Sema &S)
13656 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13657
13658 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13659 const FieldDecl *FD, bool InNonTrivialUnion) {
13660 if (const auto *AT = S.Context.getAsArrayType(QT))
13661 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13662 InNonTrivialUnion);
13663 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13664 }
13665
13666 void visitARCStrong(QualType QT, const FieldDecl *FD,
13667 bool InNonTrivialUnion) {
13668 if (InNonTrivialUnion)
13669 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13670 << 1 << 2 << QT << FD->getName();
13671 }
13672
13673 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13674 if (InNonTrivialUnion)
13675 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13676 << 1 << 2 << QT << FD->getName();
13677 }
13678
13679 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13680 const auto *RD = QT->castAsRecordDecl();
13681 if (RD->isUnion()) {
13682 if (OrigLoc.isValid()) {
13683 bool IsUnion = false;
13684 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13685 IsUnion = OrigRD->isUnion();
13686 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13687 << 2 << OrigTy << IsUnion << UseContext;
13688 // Reset OrigLoc so that this diagnostic is emitted only once.
13689 OrigLoc = SourceLocation();
13690 }
13691 InNonTrivialUnion = true;
13692 }
13693
13694 if (InNonTrivialUnion)
13695 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13696 << 0 << 2 << QT.getUnqualifiedType() << "";
13697
13698 for (const FieldDecl *FD : RD->fields())
13699 if (!shouldIgnoreForRecordTriviality(FD))
13700 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13701 }
13702
13703 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13704 if (InNonTrivialUnion)
13705 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13706 << 1 << 2 << QT << FD->getName();
13707 }
13708
13709 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13710 const FieldDecl *FD, bool InNonTrivialUnion) {}
13711 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13712 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13713 bool InNonTrivialUnion) {}
13714
13715 // The non-trivial C union type or the struct/union type that contains a
13716 // non-trivial C union.
13717 QualType OrigTy;
13718 SourceLocation OrigLoc;
13719 NonTrivialCUnionContext UseContext;
13720 Sema &S;
13721};
13722
13723} // namespace
13724
13726 NonTrivialCUnionContext UseContext,
13727 unsigned NonTrivialKind) {
13731 "shouldn't be called if type doesn't have a non-trivial C union");
13732
13733 if ((NonTrivialKind & NTCUK_Init) &&
13735 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13736 .visit(QT, nullptr, false);
13737 if ((NonTrivialKind & NTCUK_Destruct) &&
13739 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13740 .visit(QT, nullptr, false);
13741 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13742 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13743 .visit(QT, nullptr, false);
13744}
13745
13747 const VarDecl *Dcl) {
13748 if (!getLangOpts().CPlusPlus)
13749 return false;
13750
13751 // We only need to warn if the definition is in a header file, so wait to
13752 // diagnose until we've seen the definition.
13753 if (!Dcl->isThisDeclarationADefinition())
13754 return false;
13755
13756 // If an object is defined in a source file, its definition can't get
13757 // duplicated since it will never appear in more than one TU.
13759 return false;
13760
13761 // If the variable we're looking at is a static local, then we actually care
13762 // about the properties of the function containing it.
13763 const ValueDecl *Target = Dcl;
13764 // VarDecls and FunctionDecls have different functions for checking
13765 // inline-ness, and whether they were originally templated, so we have to
13766 // call the appropriate functions manually.
13767 bool TargetIsInline = Dcl->isInline();
13768 bool TargetWasTemplated =
13770
13771 // Update the Target and TargetIsInline property if necessary
13772 if (Dcl->isStaticLocal()) {
13773 const DeclContext *Ctx = Dcl->getDeclContext();
13774 if (!Ctx)
13775 return false;
13776
13777 const FunctionDecl *FunDcl =
13778 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13779 if (!FunDcl)
13780 return false;
13781
13782 Target = FunDcl;
13783 // IsInlined() checks for the C++ inline property
13784 TargetIsInline = FunDcl->isInlined();
13785 TargetWasTemplated =
13787 }
13788
13789 // Non-inline functions/variables can only legally appear in one TU
13790 // unless they were part of a template. Unfortunately, making complex
13791 // template instantiations visible is infeasible in practice, since
13792 // everything the template depends on also has to be visible. To avoid
13793 // giving impractical-to-fix warnings, don't warn if we're inside
13794 // something that was templated, even on inline stuff.
13795 if (!TargetIsInline || TargetWasTemplated)
13796 return false;
13797
13798 // If the object isn't hidden, the dynamic linker will prevent duplication.
13799 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13800
13801 // The target is "hidden" (from the dynamic linker) if:
13802 // 1. On posix, it has hidden visibility, or
13803 // 2. On windows, it has no import/export annotation, and neither does the
13804 // class which directly contains it.
13805 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13806 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13807 return false;
13808
13809 // If the variable isn't directly annotated, check to see if it's a member
13810 // of an annotated class.
13811 const CXXRecordDecl *Ctx =
13812 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13813 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13814 return false;
13815
13816 } else if (Lnk.getVisibility() != HiddenVisibility) {
13817 // Posix case
13818 return false;
13819 }
13820
13821 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13823 return false;
13824
13825 return true;
13826}
13827
13828// Determine whether the object seems mutable for the purpose of diagnosing
13829// possible unique object duplication, i.e. non-const-qualified, and
13830// not an always-constant type like a function.
13831// Not perfect: doesn't account for mutable members, for example, or
13832// elements of container types.
13833// For nested pointers, any individual level being non-const is sufficient.
13834static bool looksMutable(QualType T, const ASTContext &Ctx) {
13835 T = T.getNonReferenceType();
13836 if (T->isFunctionType())
13837 return false;
13838 if (!T.isConstant(Ctx))
13839 return true;
13840 if (T->isPointerType())
13841 return looksMutable(T->getPointeeType(), Ctx);
13842 return false;
13843}
13844
13846 // If this object has external linkage and hidden visibility, it might be
13847 // duplicated when built into a shared library, which causes problems if it's
13848 // mutable (since the copies won't be in sync) or its initialization has side
13849 // effects (since it will run once per copy instead of once globally).
13850
13851 // Don't diagnose if we're inside a template, because it's not practical to
13852 // fix the warning in most cases.
13853 if (!VD->isTemplated() &&
13855
13856 QualType Type = VD->getType();
13857 if (looksMutable(Type, VD->getASTContext())) {
13858 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13859 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13860 }
13861
13862 // To keep false positives low, only warn if we're certain that the
13863 // initializer has side effects. Don't warn on operator new, since a mutable
13864 // pointer will trigger the previous warning, and an immutable pointer
13865 // getting duplicated just results in a little extra memory usage.
13866 const Expr *Init = VD->getAnyInitializer();
13867 if (Init &&
13868 Init->HasSideEffects(VD->getASTContext(),
13869 /*IncludePossibleEffects=*/false) &&
13870 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13871 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13872 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13873 }
13874 }
13875}
13876
13878 llvm::scope_exit ResetDeclForInitializer([this]() {
13879 if (!this->ExprEvalContexts.empty())
13880 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13881 });
13882
13883 // If there is no declaration, there was an error parsing it. Just ignore
13884 // the initializer.
13885 if (!RealDecl) {
13886 return;
13887 }
13888
13889 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13890 if (!Method->isInvalidDecl()) {
13891 // Pure-specifiers are handled in ActOnPureSpecifier.
13892 Diag(Method->getLocation(), diag::err_member_function_initialization)
13893 << Method->getDeclName() << Init->getSourceRange();
13894 Method->setInvalidDecl();
13895 }
13896 return;
13897 }
13898
13899 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13900 if (!VDecl) {
13901 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13902 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13903 RealDecl->setInvalidDecl();
13904 return;
13905 }
13906
13907 if (VDecl->isInvalidDecl()) {
13908 ExprResult Recovery =
13909 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13910 if (Expr *E = Recovery.get())
13911 VDecl->setInit(E);
13912 return;
13913 }
13914
13915 // __amdgpu_feature_predicate_t cannot be initialised
13916 if (VDecl->getType().getDesugaredType(Context) ==
13917 Context.AMDGPUFeaturePredicateTy) {
13918 Diag(VDecl->getLocation(),
13919 diag::err_amdgcn_predicate_type_is_not_constructible)
13920 << VDecl;
13921 VDecl->setInvalidDecl();
13922 return;
13923 }
13924
13925 // WebAssembly tables can't be used to initialise a variable.
13926 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13927 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13928 VDecl->setInvalidDecl();
13929 return;
13930 }
13931
13932 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13933 if (VDecl->getType()->isUndeducedType()) {
13934 if (Init->containsErrors()) {
13935 // Invalidate the decl as we don't know the type for recovery-expr yet.
13936 RealDecl->setInvalidDecl();
13937 VDecl->setInit(Init);
13938 return;
13939 }
13940
13942 assert(VDecl->isInvalidDecl() &&
13943 "decl should be invalidated when deduce fails");
13944 if (auto *RecoveryExpr =
13945 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init})
13946 .get())
13947 VDecl->setInit(RecoveryExpr);
13948 return;
13949 }
13950 }
13951
13952 this->CheckAttributesOnDeducedType(RealDecl);
13953
13954 // we don't initialize groupshared variables so warn and return
13955 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
13956 Diag(VDecl->getLocation(), diag::warn_hlsl_groupshared_init);
13957 return;
13958 }
13959
13960 // dllimport cannot be used on variable definitions.
13961 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13962 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13963 VDecl->setInvalidDecl();
13964 return;
13965 }
13966
13967 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13968 // the identifier has external or internal linkage, the declaration shall
13969 // have no initializer for the identifier.
13970 // C++14 [dcl.init]p5 is the same restriction for C++.
13971 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13972 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13973 VDecl->setInvalidDecl();
13974 return;
13975 }
13976
13977 if (!VDecl->getType()->isDependentType()) {
13978 // A definition must end up with a complete type, which means it must be
13979 // complete with the restriction that an array type might be completed by
13980 // the initializer; note that later code assumes this restriction.
13981 QualType BaseDeclType = VDecl->getType();
13982 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13983 BaseDeclType = Array->getElementType();
13984 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13985 diag::err_typecheck_decl_incomplete_type)) {
13986 RealDecl->setInvalidDecl();
13987 return;
13988 }
13989
13990 // The variable can not have an abstract class type.
13991 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13992 diag::err_abstract_type_in_decl,
13994 VDecl->setInvalidDecl();
13995 }
13996
13997 // C++ [module.import/6]
13998 // ...
13999 // A header unit shall not contain a definition of a non-inline function or
14000 // variable whose name has external linkage.
14001 //
14002 // We choose to allow weak & selectany definitions, as they are common in
14003 // headers, and have semantics similar to inline definitions which are allowed
14004 // in header units.
14005 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14006 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14007 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14008 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
14010 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14011 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
14012 VDecl->setInvalidDecl();
14013 }
14014
14015 // If adding the initializer will turn this declaration into a definition,
14016 // and we already have a definition for this variable, diagnose or otherwise
14017 // handle the situation.
14018 if (VarDecl *Def = VDecl->getDefinition())
14019 if (Def != VDecl &&
14020 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14022 checkVarDeclRedefinition(Def, VDecl))
14023 return;
14024
14025 if (getLangOpts().CPlusPlus) {
14026 // C++ [class.static.data]p4
14027 // If a static data member is of const integral or const
14028 // enumeration type, its declaration in the class definition can
14029 // specify a constant-initializer which shall be an integral
14030 // constant expression (5.19). In that case, the member can appear
14031 // in integral constant expressions. The member shall still be
14032 // defined in a namespace scope if it is used in the program and the
14033 // namespace scope definition shall not contain an initializer.
14034 //
14035 // We already performed a redefinition check above, but for static
14036 // data members we also need to check whether there was an in-class
14037 // declaration with an initializer.
14038 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14039 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
14040 << VDecl->getDeclName();
14041 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14042 diag::note_previous_initializer)
14043 << 0;
14044 return;
14045 }
14046
14048 VDecl->setInvalidDecl();
14049 return;
14050 }
14051 }
14052
14053 // If the variable has an initializer and local storage, check whether
14054 // anything jumps over the initialization.
14055 if (VDecl->hasLocalStorage())
14057
14058 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14059 // a kernel function cannot be initialized."
14060 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14061 Diag(VDecl->getLocation(), diag::err_local_cant_init);
14062 VDecl->setInvalidDecl();
14063 return;
14064 }
14065
14066 // The LoaderUninitialized attribute acts as a definition (of undef).
14067 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14068 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
14069 VDecl->setInvalidDecl();
14070 return;
14071 }
14072
14073 if (getLangOpts().HLSL)
14074 if (!HLSL().handleInitialization(VDecl, Init))
14075 return;
14076
14077 // Get the decls type and save a reference for later, since
14078 // CheckInitializerTypes may change it.
14079 QualType DclT = VDecl->getType(), SavT = DclT;
14080
14081 // Expressions default to 'id' when we're in a debugger
14082 // and we are assigning it to a variable of Objective-C pointer type.
14083 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14084 Init->getType() == Context.UnknownAnyTy) {
14086 if (!Result.isUsable()) {
14087 VDecl->setInvalidDecl();
14088 return;
14089 }
14090 Init = Result.get();
14091 }
14092
14093 // Perform the initialization.
14094 bool InitializedFromParenListExpr = false;
14095 bool IsParenListInit = false;
14096 if (!VDecl->isInvalidDecl()) {
14099 VDecl->getLocation(), DirectInit, Init);
14100
14101 MultiExprArg Args = Init;
14102 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
14103 Args =
14104 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14105 InitializedFromParenListExpr = true;
14106 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
14107 Args = CXXDirectInit->getInitExprs();
14108 InitializedFromParenListExpr = true;
14109 }
14110
14111 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14112 /*TopLevelOfInitList=*/false,
14113 /*TreatUnavailableAsInvalid=*/false);
14114 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14115 if (!Result.isUsable()) {
14116 // If the provided initializer fails to initialize the var decl,
14117 // we attach a recovery expr for better recovery.
14118 auto RecoveryExpr =
14119 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14120 if (RecoveryExpr.get())
14121 VDecl->setInit(RecoveryExpr.get());
14122 // In general, for error recovery purposes, the initializer doesn't play
14123 // part in the valid bit of the declaration. There are a few exceptions:
14124 // 1) if the var decl has a deduced auto type, and the type cannot be
14125 // deduced by an invalid initializer;
14126 // 2) if the var decl is a decomposition decl with a non-deduced type,
14127 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14128 // Case 1) was already handled elsewhere.
14129 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14130 VDecl->setInvalidDecl();
14131 return;
14132 }
14133
14134 Init = Result.getAs<Expr>();
14135 IsParenListInit = !InitSeq.steps().empty() &&
14136 InitSeq.step_begin()->Kind ==
14138 QualType VDeclType = VDecl->getType();
14139 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14140 !VDeclType->isDependentType() &&
14141 Context.getAsIncompleteArrayType(VDeclType) &&
14142 Context.getAsIncompleteArrayType(Init->getType())) {
14143 // Bail out if it is not possible to deduce array size from the
14144 // initializer.
14145 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14146 << VDeclType;
14147 VDecl->setInvalidDecl();
14148 return;
14149 }
14150 }
14151
14152 // Check for self-references within variable initializers.
14153 // Variables declared within a function/method body (except for references)
14154 // are handled by a dataflow analysis.
14155 // This is undefined behavior in C++, but valid in C.
14156 if (getLangOpts().CPlusPlus)
14157 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14158 VDecl->getType()->isReferenceType())
14159 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14160
14161 // If the type changed, it means we had an incomplete type that was
14162 // completed by the initializer. For example:
14163 // int ary[] = { 1, 3, 5 };
14164 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14165 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14166 VDecl->setType(DclT);
14167
14168 if (!VDecl->isInvalidDecl()) {
14169 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14170
14171 if (VDecl->hasAttr<BlocksAttr>())
14172 ObjC().checkRetainCycles(VDecl, Init);
14173
14174 // It is safe to assign a weak reference into a strong variable.
14175 // Although this code can still have problems:
14176 // id x = self.weakProp;
14177 // id y = self.weakProp;
14178 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14179 // paths through the function. This should be revisited if
14180 // -Wrepeated-use-of-weak is made flow-sensitive.
14181 if (FunctionScopeInfo *FSI = getCurFunction())
14182 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14184 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14185 Init->getBeginLoc()))
14186 FSI->markSafeWeakUse(Init);
14187 }
14188
14189 // The initialization is usually a full-expression.
14190 //
14191 // FIXME: If this is a braced initialization of an aggregate, it is not
14192 // an expression, and each individual field initializer is a separate
14193 // full-expression. For instance, in:
14194 //
14195 // struct Temp { ~Temp(); };
14196 // struct S { S(Temp); };
14197 // struct T { S a, b; } t = { Temp(), Temp() }
14198 //
14199 // we should destroy the first Temp before constructing the second.
14200
14201 // Set context flag for OverflowBehaviorType initialization analysis
14203 true);
14206 /*DiscardedValue*/ false, VDecl->isConstexpr());
14207 if (!Result.isUsable()) {
14208 VDecl->setInvalidDecl();
14209 return;
14210 }
14211 Init = Result.get();
14212
14213 // Attach the initializer to the decl.
14214 VDecl->setInit(Init);
14215
14216 if (VDecl->isLocalVarDecl()) {
14217 // Don't check the initializer if the declaration is malformed.
14218 if (VDecl->isInvalidDecl()) {
14219 // do nothing
14220
14221 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14222 // This is true even in C++ for OpenCL.
14223 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14225
14226 // Otherwise, C++ does not restrict the initializer.
14227 } else if (getLangOpts().CPlusPlus) {
14228 // do nothing
14229
14230 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14231 // static storage duration shall be constant expressions or string literals.
14232 } else if (VDecl->getStorageClass() == SC_Static) {
14233 // Avoid evaluating the initializer twice for constexpr variables. It will
14234 // be evaluated later.
14235 if (!VDecl->isConstexpr())
14237
14238 // C89 is stricter than C99 for aggregate initializers.
14239 // C89 6.5.7p3: All the expressions [...] in an initializer list
14240 // for an object that has aggregate or union type shall be
14241 // constant expressions.
14242 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14244 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14245 }
14246
14247 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14248 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14249 if (VDecl->hasLocalStorage())
14250 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14251 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14252 VDecl->getLexicalDeclContext()->isRecord()) {
14253 // This is an in-class initialization for a static data member, e.g.,
14254 //
14255 // struct S {
14256 // static const int value = 17;
14257 // };
14258
14259 // C++ [class.mem]p4:
14260 // A member-declarator can contain a constant-initializer only
14261 // if it declares a static member (9.4) of const integral or
14262 // const enumeration type, see 9.4.2.
14263 //
14264 // C++11 [class.static.data]p3:
14265 // If a non-volatile non-inline const static data member is of integral
14266 // or enumeration type, its declaration in the class definition can
14267 // specify a brace-or-equal-initializer in which every initializer-clause
14268 // that is an assignment-expression is a constant expression. A static
14269 // data member of literal type can be declared in the class definition
14270 // with the constexpr specifier; if so, its declaration shall specify a
14271 // brace-or-equal-initializer in which every initializer-clause that is
14272 // an assignment-expression is a constant expression.
14273
14274 // Do nothing on dependent types.
14275 if (DclT->isDependentType()) {
14276
14277 // Allow any 'static constexpr' members, whether or not they are of literal
14278 // type. We separately check that every constexpr variable is of literal
14279 // type.
14280 } else if (VDecl->isConstexpr()) {
14281
14282 // Require constness.
14283 } else if (!DclT.isConstQualified()) {
14284 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14285 << Init->getSourceRange();
14286 VDecl->setInvalidDecl();
14287
14288 // We allow integer constant expressions in all cases.
14289 } else if (DclT->isIntegralOrEnumerationType()) {
14291 // In C++11, a non-constexpr const static data member with an
14292 // in-class initializer cannot be volatile.
14293 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14294
14295 // We allow foldable floating-point constants as an extension.
14296 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14297 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14298 // it anyway and provide a fixit to add the 'constexpr'.
14299 if (getLangOpts().CPlusPlus11) {
14300 Diag(VDecl->getLocation(),
14301 diag::ext_in_class_initializer_float_type_cxx11)
14302 << DclT << Init->getSourceRange();
14303 Diag(VDecl->getBeginLoc(),
14304 diag::note_in_class_initializer_float_type_cxx11)
14305 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14306 } else {
14307 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14308 << DclT << Init->getSourceRange();
14309
14310 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14311 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14312 << Init->getSourceRange();
14313 VDecl->setInvalidDecl();
14314 }
14315 }
14316
14317 // Suggest adding 'constexpr' in C++11 for literal types.
14318 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14319 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14320 << DclT << Init->getSourceRange()
14321 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14322 VDecl->setConstexpr(true);
14323
14324 } else {
14325 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14326 << DclT << Init->getSourceRange();
14327 VDecl->setInvalidDecl();
14328 }
14329 } else if (VDecl->isFileVarDecl()) {
14330 // In C, extern is typically used to avoid tentative definitions when
14331 // declaring variables in headers, but adding an initializer makes it a
14332 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14333 // In C++, extern is often used to give implicitly static const variables
14334 // external linkage, so don't warn in that case. If selectany is present,
14335 // this might be header code intended for C and C++ inclusion, so apply the
14336 // C++ rules.
14337 if (VDecl->getStorageClass() == SC_Extern &&
14338 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14339 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14340 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14342 Diag(VDecl->getLocation(), diag::warn_extern_init);
14343
14344 // In Microsoft C++ mode, a const variable defined in namespace scope has
14345 // external linkage by default if the variable is declared with
14346 // __declspec(dllexport).
14347 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14349 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14350 VDecl->setStorageClass(SC_Extern);
14351
14352 // C99 6.7.8p4. All file scoped initializers need to be constant.
14353 // Avoid duplicate diagnostics for constexpr variables.
14354 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14355 !VDecl->isConstexpr())
14357 }
14358
14359 QualType InitType = Init->getType();
14360 if (!InitType.isNull() &&
14364
14365 // We will represent direct-initialization similarly to copy-initialization:
14366 // int x(1); -as-> int x = 1;
14367 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14368 //
14369 // Clients that want to distinguish between the two forms, can check for
14370 // direct initializer using VarDecl::getInitStyle().
14371 // A major benefit is that clients that don't particularly care about which
14372 // exactly form was it (like the CodeGen) can handle both cases without
14373 // special case code.
14374
14375 // C++ 8.5p11:
14376 // The form of initialization (using parentheses or '=') matters
14377 // when the entity being initialized has class type.
14378 if (InitializedFromParenListExpr) {
14379 assert(DirectInit && "Call-style initializer must be direct init.");
14380 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14382 } else if (DirectInit) {
14383 // This must be list-initialization. No other way is direct-initialization.
14385 }
14386
14387 if (LangOpts.OpenMP &&
14388 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14389 VDecl->isFileVarDecl())
14390 DeclsToCheckForDeferredDiags.insert(VDecl);
14392
14393 if (LangOpts.OpenACC && !InitType.isNull())
14394 OpenACC().ActOnVariableInit(VDecl, InitType);
14395}
14396
14398 // Our main concern here is re-establishing invariants like "a
14399 // variable's type is either dependent or complete".
14400 if (!D || D->isInvalidDecl()) return;
14401
14402 VarDecl *VD = dyn_cast<VarDecl>(D);
14403 if (!VD) return;
14404
14405 // Bindings are not usable if we can't make sense of the initializer.
14406 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14407 for (auto *BD : DD->bindings())
14408 BD->setInvalidDecl();
14409
14410 // Auto types are meaningless if we can't make sense of the initializer.
14411 if (VD->getType()->isUndeducedType()) {
14412 D->setInvalidDecl();
14413 return;
14414 }
14415
14416 QualType Ty = VD->getType();
14417 if (Ty->isDependentType()) return;
14418
14419 // Require a complete type.
14421 Context.getBaseElementType(Ty),
14422 diag::err_typecheck_decl_incomplete_type)) {
14423 VD->setInvalidDecl();
14424 return;
14425 }
14426
14427 // Require a non-abstract type.
14428 if (RequireNonAbstractType(VD->getLocation(), Ty,
14429 diag::err_abstract_type_in_decl,
14431 VD->setInvalidDecl();
14432 return;
14433 }
14434
14435 // Don't bother complaining about constructors or destructors,
14436 // though.
14437}
14438
14440 // If there is no declaration, there was an error parsing it. Just ignore it.
14441 if (!RealDecl)
14442 return;
14443
14444 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14445 QualType Type = Var->getType();
14446
14447 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14448 Diag(Var->getLocation(),
14449 diag::err_amdgcn_predicate_type_is_not_constructible)
14450 << Var;
14451 Var->setInvalidDecl();
14452 return;
14453 }
14454 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14455 if (isa<DecompositionDecl>(RealDecl)) {
14456 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14457 Var->setInvalidDecl();
14458 return;
14459 }
14460
14461 if (Type->isUndeducedType() &&
14462 DeduceVariableDeclarationType(Var, false, nullptr))
14463 return;
14464
14465 this->CheckAttributesOnDeducedType(RealDecl);
14466
14467 // C++11 [class.static.data]p3: A static data member can be declared with
14468 // the constexpr specifier; if so, its declaration shall specify
14469 // a brace-or-equal-initializer.
14470 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14471 // the definition of a variable [...] or the declaration of a static data
14472 // member.
14473 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14474 !Var->isThisDeclarationADemotedDefinition()) {
14475 if (Var->isStaticDataMember()) {
14476 // C++1z removes the relevant rule; the in-class declaration is always
14477 // a definition there.
14478 if (!getLangOpts().CPlusPlus17 &&
14479 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14480 Diag(Var->getLocation(),
14481 diag::err_constexpr_static_mem_var_requires_init)
14482 << Var;
14483 Var->setInvalidDecl();
14484 return;
14485 }
14486 } else {
14487 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14488 Var->setInvalidDecl();
14489 return;
14490 }
14491 }
14492
14493 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14494 // be initialized.
14495 if (!Var->isInvalidDecl() &&
14496 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14497 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14498 bool HasConstExprDefaultConstructor = false;
14499 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14500 for (auto *Ctor : RD->ctors()) {
14501 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14502 Ctor->getMethodQualifiers().getAddressSpace() ==
14504 HasConstExprDefaultConstructor = true;
14505 }
14506 }
14507 }
14508 if (!HasConstExprDefaultConstructor) {
14509 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14510 Var->setInvalidDecl();
14511 return;
14512 }
14513 }
14514
14515 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14516 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14517 Diag(Var->getLocation(), diag::err_specialization_const);
14518 Var->setInvalidDecl();
14519 return;
14520 }
14521
14522 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14523 if (Var->getStorageClass() == SC_Extern) {
14524 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14525 << Var;
14526 Var->setInvalidDecl();
14527 return;
14528 }
14529 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14530 diag::err_typecheck_decl_incomplete_type)) {
14531 Var->setInvalidDecl();
14532 return;
14533 }
14534 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14535 if (!RD->hasTrivialDefaultConstructor()) {
14536 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14537 Var->setInvalidDecl();
14538 return;
14539 }
14540 }
14541 // The declaration is uninitialized, no need for further checks.
14542 return;
14543 }
14544
14545 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14546 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14547 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14548 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14550 NTCUK_Init);
14551
14552 switch (DefKind) {
14554 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14555 break;
14556
14557 // We have an out-of-line definition of a static data member
14558 // that has an in-class initializer, so we type-check this like
14559 // a declaration.
14560 //
14561 [[fallthrough]];
14562
14564 // It's only a declaration.
14565
14566 // Block scope. C99 6.7p7: If an identifier for an object is
14567 // declared with no linkage (C99 6.2.2p6), the type for the
14568 // object shall be complete.
14569 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14570 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14571 RequireCompleteType(Var->getLocation(), Type,
14572 diag::err_typecheck_decl_incomplete_type))
14573 Var->setInvalidDecl();
14574
14575 // Make sure that the type is not abstract.
14576 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14577 RequireNonAbstractType(Var->getLocation(), Type,
14578 diag::err_abstract_type_in_decl,
14580 Var->setInvalidDecl();
14581 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14582 Var->getStorageClass() == SC_PrivateExtern) {
14583 Diag(Var->getLocation(), diag::warn_private_extern);
14584 Diag(Var->getLocation(), diag::note_private_extern);
14585 }
14586
14587 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14588 !Var->isInvalidDecl())
14589 ExternalDeclarations.push_back(Var);
14590
14591 return;
14592
14594 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14595 // object that has file scope without an initializer, and without a
14596 // storage-class specifier or with the storage-class specifier "static",
14597 // constitutes a tentative definition. Note: A tentative definition with
14598 // external linkage is valid (C99 6.2.2p5).
14599 if (!Var->isInvalidDecl()) {
14600 if (const IncompleteArrayType *ArrayT
14601 = Context.getAsIncompleteArrayType(Type)) {
14603 Var->getLocation(), ArrayT->getElementType(),
14604 diag::err_array_incomplete_or_sizeless_type))
14605 Var->setInvalidDecl();
14606 }
14607 if (Var->getStorageClass() == SC_Static) {
14608 // C99 6.9.2p3: If the declaration of an identifier for an object is
14609 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14610 // declared type shall not be an incomplete type.
14611 // NOTE: code such as the following
14612 // static struct s;
14613 // struct s { int a; };
14614 // is accepted by gcc. Hence here we issue a warning instead of
14615 // an error and we do not invalidate the static declaration.
14616 // NOTE: to avoid multiple warnings, only check the first declaration.
14617 if (Var->isFirstDecl())
14618 RequireCompleteType(Var->getLocation(), Type,
14619 diag::ext_typecheck_decl_incomplete_type,
14620 Type->isArrayType());
14621 }
14622 }
14623
14624 // Record the tentative definition; we're done.
14625 if (!Var->isInvalidDecl())
14626 TentativeDefinitions.push_back(Var);
14627 return;
14628 }
14629
14630 // Provide a specific diagnostic for uninitialized variable definitions
14631 // with incomplete array type, unless it is a global unbounded HLSL resource
14632 // array.
14633 if (Type->isIncompleteArrayType() &&
14634 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14636 if (Var->isConstexpr())
14637 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14638 << Var;
14639 else
14640 Diag(Var->getLocation(),
14641 diag::err_typecheck_incomplete_array_needs_initializer);
14642 Var->setInvalidDecl();
14643 return;
14644 }
14645
14646 // Provide a specific diagnostic for uninitialized variable
14647 // definitions with reference type.
14648 if (Type->isReferenceType()) {
14649 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14650 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14651 return;
14652 }
14653
14654 // Do not attempt to type-check the default initializer for a
14655 // variable with dependent type.
14656 if (Type->isDependentType())
14657 return;
14658
14659 if (Var->isInvalidDecl())
14660 return;
14661
14662 if (!Var->hasAttr<AliasAttr>()) {
14663 if (RequireCompleteType(Var->getLocation(),
14664 Context.getBaseElementType(Type),
14665 diag::err_typecheck_decl_incomplete_type)) {
14666 Var->setInvalidDecl();
14667 return;
14668 }
14669 } else {
14670 return;
14671 }
14672
14673 // The variable can not have an abstract class type.
14674 if (RequireNonAbstractType(Var->getLocation(), Type,
14675 diag::err_abstract_type_in_decl,
14677 Var->setInvalidDecl();
14678 return;
14679 }
14680
14681 // In C, if the definition is const-qualified and has no initializer, it
14682 // is left uninitialized unless it has static or thread storage duration.
14683 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14684 unsigned DiagID = diag::warn_default_init_const_unsafe;
14685 if (Var->getStorageDuration() == SD_Static ||
14686 Var->getStorageDuration() == SD_Thread)
14687 DiagID = diag::warn_default_init_const;
14688
14689 bool EmitCppCompat = !Diags.isIgnored(
14690 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14691 Var->getLocation());
14692
14693 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14694 }
14695
14696 // Check for jumps past the implicit initializer. C++0x
14697 // clarifies that this applies to a "variable with automatic
14698 // storage duration", not a "local variable".
14699 // C++11 [stmt.dcl]p3
14700 // A program that jumps from a point where a variable with automatic
14701 // storage duration is not in scope to a point where it is in scope is
14702 // ill-formed unless the variable has scalar type, class type with a
14703 // trivial default constructor and a trivial destructor, a cv-qualified
14704 // version of one of these types, or an array of one of the preceding
14705 // types and is declared without an initializer.
14706 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14707 if (const auto *CXXRecord =
14708 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14709 // Mark the function (if we're in one) for further checking even if the
14710 // looser rules of C++11 do not require such checks, so that we can
14711 // diagnose incompatibilities with C++98.
14712 if (!CXXRecord->isPOD())
14714 }
14715 }
14716 // In OpenCL, we can't initialize objects in the __local address space,
14717 // even implicitly, so don't synthesize an implicit initializer.
14718 if (getLangOpts().OpenCL &&
14719 Var->getType().getAddressSpace() == LangAS::opencl_local)
14720 return;
14721
14722 // Handle HLSL uninitialized decls
14723 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14724 return;
14725
14726 // HLSL input & push-constant variables are expected to be externally
14727 // initialized, even when marked `static`.
14728 if (getLangOpts().HLSL &&
14729 hlsl::isInitializedByPipeline(Var->getType().getAddressSpace()))
14730 return;
14731
14732 // C++03 [dcl.init]p9:
14733 // If no initializer is specified for an object, and the
14734 // object is of (possibly cv-qualified) non-POD class type (or
14735 // array thereof), the object shall be default-initialized; if
14736 // the object is of const-qualified type, the underlying class
14737 // type shall have a user-declared default
14738 // constructor. Otherwise, if no initializer is specified for
14739 // a non- static object, the object and its subobjects, if
14740 // any, have an indeterminate initial value); if the object
14741 // or any of its subobjects are of const-qualified type, the
14742 // program is ill-formed.
14743 // C++0x [dcl.init]p11:
14744 // If no initializer is specified for an object, the object is
14745 // default-initialized; [...].
14748 = InitializationKind::CreateDefault(Var->getLocation());
14749
14750 InitializationSequence InitSeq(*this, Entity, Kind, {});
14751 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14752
14753 if (Init.get()) {
14754 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14755 // This is important for template substitution.
14756 Var->setInitStyle(VarDecl::CallInit);
14757 } else if (Init.isInvalid()) {
14758 // If default-init fails, attach a recovery-expr initializer to track
14759 // that initialization was attempted and failed.
14760 auto RecoveryExpr =
14761 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14762 if (RecoveryExpr.get())
14763 Var->setInit(RecoveryExpr.get());
14764 }
14765
14767 }
14768}
14769
14771 // If there is no declaration, there was an error parsing it. Ignore it.
14772 if (!D)
14773 return;
14774
14775 VarDecl *VD = dyn_cast<VarDecl>(D);
14776 if (!VD) {
14777 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14778 D->setInvalidDecl();
14779 return;
14780 }
14781
14782 VD->setCXXForRangeDecl(true);
14783
14784 // for-range-declaration cannot be given a storage class specifier.
14785 int Error = -1;
14786 switch (VD->getStorageClass()) {
14787 case SC_None:
14788 break;
14789 case SC_Extern:
14790 Error = 0;
14791 break;
14792 case SC_Static:
14793 Error = 1;
14794 break;
14795 case SC_PrivateExtern:
14796 Error = 2;
14797 break;
14798 case SC_Auto:
14799 Error = 3;
14800 break;
14801 case SC_Register:
14802 Error = 4;
14803 break;
14804 }
14805
14806 // for-range-declaration cannot be given a storage class specifier con't.
14807 switch (VD->getTSCSpec()) {
14808 case TSCS_thread_local:
14809 Error = 6;
14810 break;
14811 case TSCS___thread:
14812 case TSCS__Thread_local:
14813 case TSCS_unspecified:
14814 break;
14815 }
14816
14817 if (Error != -1) {
14818 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14819 << VD << Error;
14820 D->setInvalidDecl();
14821 }
14822}
14823
14825 IdentifierInfo *Ident,
14826 ParsedAttributes &Attrs) {
14827 // C++1y [stmt.iter]p1:
14828 // A range-based for statement of the form
14829 // for ( for-range-identifier : for-range-initializer ) statement
14830 // is equivalent to
14831 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14832 DeclSpec DS(Attrs.getPool().getFactory());
14833
14834 const char *PrevSpec;
14835 unsigned DiagID;
14836 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14838
14840 D.SetIdentifier(Ident, IdentLoc);
14841 D.takeAttributesAppending(Attrs);
14842
14843 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14844 IdentLoc);
14845 Decl *Var = ActOnDeclarator(S, D);
14846 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14848 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14849 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14850 : IdentLoc);
14851}
14852
14855 return;
14856 auto *Attr = LifetimeBoundAttr::CreateImplicit(Context, MD->getLocation());
14857 QualType MethodType = MD->getType();
14858 QualType AttributedType =
14859 Context.getAttributedType(Attr, MethodType, MethodType);
14860 TypeLocBuilder TLB;
14861 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14862 TLB.pushFullCopy(TSI->getTypeLoc());
14863 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(AttributedType);
14864 TyLoc.setAttr(Attr);
14865 MD->setType(AttributedType);
14866 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, AttributedType));
14867}
14868
14870 if (var->isInvalidDecl()) return;
14871
14873
14874 if (getLangOpts().OpenCL) {
14875 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14876 // initialiser
14877 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14878 !var->hasInit()) {
14879 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14880 << 1 /*Init*/;
14881 var->setInvalidDecl();
14882 return;
14883 }
14884 }
14885
14886 // In Objective-C, don't allow jumps past the implicit initialization of a
14887 // local retaining variable.
14888 if (getLangOpts().ObjC &&
14889 var->hasLocalStorage()) {
14890 switch (var->getType().getObjCLifetime()) {
14894 break;
14895
14899 break;
14900 }
14901 }
14902
14903 if (var->hasLocalStorage() &&
14904 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14906
14907 // Warn about externally-visible variables being defined without a
14908 // prior declaration. We only want to do this for global
14909 // declarations, but we also specifically need to avoid doing it for
14910 // class members because the linkage of an anonymous class can
14911 // change if it's later given a typedef name.
14912 if (var->isThisDeclarationADefinition() &&
14913 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14914 var->isExternallyVisible() && var->hasLinkage() &&
14915 !var->isInline() && !var->getDescribedVarTemplate() &&
14916 var->getStorageClass() != SC_Register &&
14918 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14919 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14920 var->getLocation())) {
14921 // Find a previous declaration that's not a definition.
14922 VarDecl *prev = var->getPreviousDecl();
14923 while (prev && prev->isThisDeclarationADefinition())
14924 prev = prev->getPreviousDecl();
14925
14926 if (!prev) {
14927 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14928 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14929 << /* variable */ 0;
14930 }
14931 }
14932
14933 // Cache the result of checking for constant initialization.
14934 std::optional<bool> CacheHasConstInit;
14935 const Expr *CacheCulprit = nullptr;
14936 auto checkConstInit = [&]() mutable {
14937 const Expr *Init = var->getInit();
14938 if (Init->isInstantiationDependent())
14939 return true;
14940
14941 if (!CacheHasConstInit)
14942 CacheHasConstInit = var->getInit()->isConstantInitializer(
14943 Context, var->getType()->isReferenceType(), &CacheCulprit);
14944 return *CacheHasConstInit;
14945 };
14946
14947 if (var->getTLSKind() == VarDecl::TLS_Static) {
14948 if (var->getType().isDestructedType()) {
14949 // GNU C++98 edits for __thread, [basic.start.term]p3:
14950 // The type of an object with thread storage duration shall not
14951 // have a non-trivial destructor.
14952 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14954 Diag(var->getLocation(), diag::note_use_thread_local);
14955 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14956 if (!checkConstInit()) {
14957 // GNU C++98 edits for __thread, [basic.start.init]p4:
14958 // An object of thread storage duration shall not require dynamic
14959 // initialization.
14960 // FIXME: Need strict checking here.
14961 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14962 << CacheCulprit->getSourceRange();
14964 Diag(var->getLocation(), diag::note_use_thread_local);
14965 }
14966 }
14967 }
14968
14969
14970 if (!var->getType()->isStructureType() && var->hasInit() &&
14971 isa<InitListExpr>(var->getInit())) {
14972 const auto *ILE = cast<InitListExpr>(var->getInit());
14973 unsigned NumInits = ILE->getNumInits();
14974 if (NumInits > 2)
14975 for (unsigned I = 0; I < NumInits; ++I) {
14976 const auto *Init = ILE->getInit(I);
14977 if (!Init)
14978 break;
14979 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14980 if (!SL)
14981 break;
14982
14983 unsigned NumConcat = SL->getNumConcatenated();
14984 // Diagnose missing comma in string array initialization.
14985 // Do not warn when all the elements in the initializer are concatenated
14986 // together. Do not warn for macros too.
14987 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14988 bool OnlyOneMissingComma = true;
14989 for (unsigned J = I + 1; J < NumInits; ++J) {
14990 const auto *Init = ILE->getInit(J);
14991 if (!Init)
14992 break;
14993 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14994 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14995 OnlyOneMissingComma = false;
14996 break;
14997 }
14998 }
14999
15000 if (OnlyOneMissingComma) {
15002 for (unsigned i = 0; i < NumConcat - 1; ++i)
15003 Hints.push_back(FixItHint::CreateInsertion(
15004 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
15005
15006 Diag(SL->getStrTokenLoc(1),
15007 diag::warn_concatenated_literal_array_init)
15008 << Hints;
15009 Diag(SL->getBeginLoc(),
15010 diag::note_concatenated_string_literal_silence);
15011 }
15012 // In any case, stop now.
15013 break;
15014 }
15015 }
15016 }
15017
15018
15019 QualType type = var->getType();
15020
15021 if (var->hasAttr<BlocksAttr>())
15023
15024 Expr *Init = var->getInit();
15025 bool GlobalStorage = var->hasGlobalStorage();
15026 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15027 QualType baseType = Context.getBaseElementType(type);
15028 bool HasConstInit = true;
15029
15030 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15031 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
15032 << var;
15033
15034 // Check whether the initializer is sufficiently constant.
15035 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15036 !type->isDependentType() && Init && !Init->isValueDependent() &&
15037 (GlobalStorage || var->isConstexpr() ||
15038 var->mightBeUsableInConstantExpressions(Context))) {
15039 // If this variable might have a constant initializer or might be usable in
15040 // constant expressions, check whether or not it actually is now. We can't
15041 // do this lazily, because the result might depend on things that change
15042 // later, such as which constexpr functions happen to be defined.
15044 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15045 // Prior to C++11, in contexts where a constant initializer is required,
15046 // the set of valid constant initializers is described by syntactic rules
15047 // in [expr.const]p2-6.
15048 // FIXME: Stricter checking for these rules would be useful for constinit /
15049 // -Wglobal-constructors.
15050 HasConstInit = checkConstInit();
15051
15052 // Compute and cache the constant value, and remember that we have a
15053 // constant initializer.
15054 if (HasConstInit) {
15055 if (var->isStaticDataMember() && !var->isInline() &&
15056 var->getLexicalDeclContext()->isRecord() &&
15057 type->isIntegralOrEnumerationType()) {
15058 // In C++98, in-class initialization for a static data member must
15059 // be an integer constant expression.
15060 if (!Init->isIntegerConstantExpr(Context)) {
15061 Diag(Init->getExprLoc(),
15062 diag::ext_in_class_initializer_non_constant)
15063 << Init->getSourceRange();
15064 }
15065 }
15066 (void)var->checkForConstantInitialization(Notes);
15067 Notes.clear();
15068 } else if (CacheCulprit) {
15069 Notes.emplace_back(CacheCulprit->getExprLoc(),
15070 PDiag(diag::note_invalid_subexpr_in_const_expr));
15071 Notes.back().second << CacheCulprit->getSourceRange();
15072 }
15073 } else {
15074 // Evaluate the initializer to see if it's a constant initializer.
15075 HasConstInit = var->checkForConstantInitialization(Notes);
15076 }
15077
15078 if (HasConstInit) {
15079 // FIXME: Consider replacing the initializer with a ConstantExpr.
15080 } else if (var->isConstexpr()) {
15081 SourceLocation DiagLoc = var->getLocation();
15082 // If the note doesn't add any useful information other than a source
15083 // location, fold it into the primary diagnostic.
15084 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15085 diag::note_invalid_subexpr_in_const_expr) {
15086 DiagLoc = Notes[0].first;
15087 Notes.clear();
15088 }
15089 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
15090 << var << Init->getSourceRange();
15091 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15092 Diag(Notes[I].first, Notes[I].second);
15093 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15094 auto *Attr = var->getAttr<ConstInitAttr>();
15095 Diag(var->getLocation(), diag::err_require_constant_init_failed)
15096 << Init->getSourceRange();
15097 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
15098 << Attr->getRange() << Attr->isConstinit();
15099 for (auto &it : Notes)
15100 Diag(it.first, it.second);
15101 } else if (var->isStaticDataMember() && !var->isInline() &&
15102 var->getLexicalDeclContext()->isRecord()) {
15103 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
15104 << Init->getSourceRange();
15105 for (auto &it : Notes)
15106 Diag(it.first, it.second);
15107 var->setInvalidDecl();
15108 } else if (IsGlobal &&
15109 !getDiagnostics().isIgnored(diag::warn_global_constructor,
15110 var->getLocation())) {
15111 // Warn about globals which don't have a constant initializer. Don't
15112 // warn about globals with a non-trivial destructor because we already
15113 // warned about them.
15114 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15115 if (!(RD && !RD->hasTrivialDestructor())) {
15116 // checkConstInit() here permits trivial default initialization even in
15117 // C++11 onwards, where such an initializer is not a constant initializer
15118 // but nonetheless doesn't require a global constructor.
15119 if (!checkConstInit())
15120 Diag(var->getLocation(), diag::warn_global_constructor)
15121 << Init->getSourceRange();
15122 }
15123 }
15124 }
15125
15126 // Apply section attributes and pragmas to global variables.
15127 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15129 PragmaStack<StringLiteral *> *Stack = nullptr;
15130 int SectionFlags = ASTContext::PSF_Read;
15131 bool MSVCEnv =
15132 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15133 std::optional<QualType::NonConstantStorageReason> Reason;
15134 if (HasConstInit &&
15135 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
15136 Stack = &ConstSegStack;
15137 } else {
15138 SectionFlags |= ASTContext::PSF_Write;
15139 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15140 }
15141 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15142 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15143 SectionFlags |= ASTContext::PSF_Implicit;
15144 UnifySection(SA->getName(), SectionFlags, var);
15145 } else if (Stack->CurrentValue) {
15146 if (Stack != &ConstSegStack && MSVCEnv &&
15147 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15148 var->getType().isConstQualified()) {
15149 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15150 NonConstNonReferenceType) &&
15151 "This case should've already been handled elsewhere");
15152 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15153 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15155 : *Reason);
15156 }
15157 SectionFlags |= ASTContext::PSF_Implicit;
15158 auto SectionName = Stack->CurrentValue->getString();
15159 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15160 Stack->CurrentPragmaLocation,
15161 SectionAttr::Declspec_allocate));
15162 if (UnifySection(SectionName, SectionFlags, var))
15163 var->dropAttr<SectionAttr>();
15164 }
15165
15166 // Apply the init_seg attribute if this has an initializer. If the
15167 // initializer turns out to not be dynamic, we'll end up ignoring this
15168 // attribute.
15169 if (CurInitSeg && var->getInit())
15170 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15171 CurInitSegLoc));
15172 }
15173
15174 // All the following checks are C++ only.
15175 if (!getLangOpts().CPlusPlus) {
15176 // If this variable must be emitted, add it as an initializer for the
15177 // current module.
15178 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15179 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15180 return;
15181 }
15182
15184
15185 // Require the destructor.
15186 if (!type->isDependentType())
15187 if (auto *RD = baseType->getAsCXXRecordDecl())
15189
15190 // If this variable must be emitted, add it as an initializer for the current
15191 // module.
15192 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty() &&
15193 (ModuleScopes.back().Module->isHeaderLikeModule() ||
15194 // For named modules, we may only emit non discardable variables.
15195 !isDiscardableGVALinkage(Context.GetGVALinkageForVariable(var))))
15196 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15197
15198 // Build the bindings if this is a structured binding declaration.
15199 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15201}
15202
15204 assert(VD->isStaticLocal());
15205
15206 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15207
15208 // Find outermost function when VD is in lambda function.
15209 while (FD && !getDLLAttr(FD) &&
15210 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15211 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15212 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15213 }
15214
15215 if (!FD)
15216 return;
15217
15218 // Static locals inherit dll attributes from their function.
15219 if (Attr *A = getDLLAttr(FD)) {
15220 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15221 NewAttr->setInherited(true);
15222 VD->addAttr(NewAttr);
15223 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15224 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15225 NewAttr->setInherited(true);
15226 VD->addAttr(NewAttr);
15227
15228 // Export this function to enforce exporting this static variable even
15229 // if it is not used in this compilation unit.
15230 if (!FD->hasAttr<DLLExportAttr>())
15231 FD->addAttr(NewAttr);
15232
15233 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15234 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15235 NewAttr->setInherited(true);
15236 VD->addAttr(NewAttr);
15237 }
15238}
15239
15241 assert(VD->getTLSKind());
15242
15243 // Perform TLS alignment check here after attributes attached to the variable
15244 // which may affect the alignment have been processed. Only perform the check
15245 // if the target has a maximum TLS alignment (zero means no constraints).
15246 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15247 // Protect the check so that it's not performed on dependent types and
15248 // dependent alignments (we can't determine the alignment in that case).
15249 if (!VD->hasDependentAlignment()) {
15250 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15251 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15252 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15253 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15254 << (unsigned)MaxAlignChars.getQuantity();
15255 }
15256 }
15257 }
15258}
15259
15261 // Note that we are no longer parsing the initializer for this declaration.
15262 ParsingInitForAutoVars.erase(ThisDecl);
15263
15264 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15265 if (!VD)
15266 return;
15267
15268 // Emit any deferred warnings for the variable's initializer, even if the
15269 // variable is invalid
15270 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15271
15272 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15274 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15275 if (PragmaClangBSSSection.Valid)
15276 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15277 Context, PragmaClangBSSSection.SectionName,
15278 PragmaClangBSSSection.PragmaLocation));
15279 if (PragmaClangDataSection.Valid)
15280 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15281 Context, PragmaClangDataSection.SectionName,
15282 PragmaClangDataSection.PragmaLocation));
15283 if (PragmaClangRodataSection.Valid)
15284 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15285 Context, PragmaClangRodataSection.SectionName,
15286 PragmaClangRodataSection.PragmaLocation));
15287 if (PragmaClangRelroSection.Valid)
15288 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15289 Context, PragmaClangRelroSection.SectionName,
15290 PragmaClangRelroSection.PragmaLocation));
15291 }
15292
15293 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15294 for (auto *BD : DD->bindings()) {
15296 }
15297 }
15298
15299 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15301
15302 checkAttributesAfterMerging(*this, *VD);
15303
15304 if (VD->isStaticLocal())
15306
15307 if (VD->getTLSKind())
15309
15310 // Perform check for initializers of device-side global variables.
15311 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15312 // 7.5). We must also apply the same checks to all __shared__
15313 // variables whether they are local or not. CUDA also allows
15314 // constant initializers for __constant__ and __device__ variables.
15315 if (getLangOpts().CUDA)
15317
15318 // Grab the dllimport or dllexport attribute off of the VarDecl.
15319 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15320
15321 // Imported static data members cannot be defined out-of-line.
15322 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15323 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15325 // We allow definitions of dllimport class template static data members
15326 // with a warning.
15329 bool IsClassTemplateMember =
15331 Context->getDescribedClassTemplate();
15332
15333 Diag(VD->getLocation(),
15334 IsClassTemplateMember
15335 ? diag::warn_attribute_dllimport_static_field_definition
15336 : diag::err_attribute_dllimport_static_field_definition);
15337 Diag(IA->getLocation(), diag::note_attribute);
15338 if (!IsClassTemplateMember)
15339 VD->setInvalidDecl();
15340 }
15341 }
15342
15343 // dllimport/dllexport variables cannot be thread local, their TLS index
15344 // isn't exported with the variable.
15345 if (DLLAttr && VD->getTLSKind()) {
15346 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15347 if (F && getDLLAttr(F)) {
15348 assert(VD->isStaticLocal());
15349 // But if this is a static local in a dlimport/dllexport function, the
15350 // function will never be inlined, which means the var would never be
15351 // imported, so having it marked import/export is safe.
15352 } else {
15353 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15354 << DLLAttr;
15355 VD->setInvalidDecl();
15356 }
15357 }
15358
15359 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15360 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15361 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15362 << Attr;
15363 VD->dropAttr<UsedAttr>();
15364 }
15365 }
15366 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15367 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15368 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15369 << Attr;
15370 VD->dropAttr<RetainAttr>();
15371 }
15372 }
15373
15374 const DeclContext *DC = VD->getDeclContext();
15375 // If there's a #pragma GCC visibility in scope, and this isn't a class
15376 // member, set the visibility of this variable.
15379
15380 // FIXME: Warn on unused var template partial specializations.
15383
15384 // Now we have parsed the initializer and can update the table of magic
15385 // tag values.
15386 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15388 return;
15389
15390 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15391 const Expr *MagicValueExpr = VD->getInit();
15392 if (!MagicValueExpr) {
15393 continue;
15394 }
15395 std::optional<llvm::APSInt> MagicValueInt;
15396 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15397 Diag(I->getRange().getBegin(),
15398 diag::err_type_tag_for_datatype_not_ice)
15399 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15400 continue;
15401 }
15402 if (MagicValueInt->getActiveBits() > 64) {
15403 Diag(I->getRange().getBegin(),
15404 diag::err_type_tag_for_datatype_too_large)
15405 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15406 continue;
15407 }
15408 uint64_t MagicValue = MagicValueInt->getZExtValue();
15409 RegisterTypeTagForDatatype(I->getArgumentKind(),
15410 MagicValue,
15411 I->getMatchingCType(),
15412 I->getLayoutCompatible(),
15413 I->getMustBeNull());
15414 }
15415}
15416
15418 auto *VD = dyn_cast<VarDecl>(DD);
15419 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15420}
15421
15423 ArrayRef<Decl *> Group) {
15425
15426 if (DS.isTypeSpecOwned())
15427 Decls.push_back(DS.getRepAsDecl());
15428
15429 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15430 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15431 bool DiagnosedMultipleDecomps = false;
15432 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15433 bool DiagnosedNonDeducedAuto = false;
15434
15435 for (Decl *D : Group) {
15436 if (!D)
15437 continue;
15438 // Check if the Decl has been declared in '#pragma omp declare target'
15439 // directive and has static storage duration.
15440 if (auto *VD = dyn_cast<VarDecl>(D);
15441 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15442 VD->hasGlobalStorage())
15444 // For declarators, there are some additional syntactic-ish checks we need
15445 // to perform.
15446 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15447 if (!FirstDeclaratorInGroup)
15448 FirstDeclaratorInGroup = DD;
15449 if (!FirstDecompDeclaratorInGroup)
15450 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15451 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15452 !hasDeducedAuto(DD))
15453 FirstNonDeducedAutoInGroup = DD;
15454
15455 if (FirstDeclaratorInGroup != DD) {
15456 // A decomposition declaration cannot be combined with any other
15457 // declaration in the same group.
15458 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15459 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15460 diag::err_decomp_decl_not_alone)
15461 << FirstDeclaratorInGroup->getSourceRange()
15462 << DD->getSourceRange();
15463 DiagnosedMultipleDecomps = true;
15464 }
15465
15466 // A declarator that uses 'auto' in any way other than to declare a
15467 // variable with a deduced type cannot be combined with any other
15468 // declarator in the same group.
15469 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15470 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15471 diag::err_auto_non_deduced_not_alone)
15472 << FirstNonDeducedAutoInGroup->getType()
15474 << FirstDeclaratorInGroup->getSourceRange()
15475 << DD->getSourceRange();
15476 DiagnosedNonDeducedAuto = true;
15477 }
15478 }
15479 }
15480
15481 Decls.push_back(D);
15482 }
15483
15485 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15486 handleTagNumbering(Tag, S);
15487 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15489 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15490 }
15491 }
15492
15493 return BuildDeclaratorGroup(Decls);
15494}
15495
15498 // C++14 [dcl.spec.auto]p7: (DR1347)
15499 // If the type that replaces the placeholder type is not the same in each
15500 // deduction, the program is ill-formed.
15501 if (Group.size() > 1) {
15503 VarDecl *DeducedDecl = nullptr;
15504 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15505 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15506 if (!D || D->isInvalidDecl())
15507 break;
15508 DeducedType *DT = D->getType()->getContainedDeducedType();
15509 if (!DT || DT->getDeducedType().isNull())
15510 continue;
15511 if (Deduced.isNull()) {
15512 Deduced = DT->getDeducedType();
15513 DeducedDecl = D;
15514 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15515 auto *AT = dyn_cast<AutoType>(DT);
15516 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15517 diag::err_auto_different_deductions)
15518 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15519 << DeducedDecl->getDeclName() << DT->getDeducedType()
15520 << D->getDeclName();
15521 if (DeducedDecl->hasInit())
15522 Dia << DeducedDecl->getInit()->getSourceRange();
15523 if (D->getInit())
15524 Dia << D->getInit()->getSourceRange();
15525 D->setInvalidDecl();
15526 break;
15527 }
15528 }
15529 }
15530
15532
15533 return DeclGroupPtrTy::make(
15534 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15535}
15536
15540
15542 // Don't parse the comment if Doxygen diagnostics are ignored.
15543 if (Group.empty() || !Group[0])
15544 return;
15545
15546 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15547 Group[0]->getLocation()) &&
15548 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15549 Group[0]->getLocation()))
15550 return;
15551
15552 if (Group.size() >= 2) {
15553 // This is a decl group. Normally it will contain only declarations
15554 // produced from declarator list. But in case we have any definitions or
15555 // additional declaration references:
15556 // 'typedef struct S {} S;'
15557 // 'typedef struct S *S;'
15558 // 'struct S *pS;'
15559 // FinalizeDeclaratorGroup adds these as separate declarations.
15560 Decl *MaybeTagDecl = Group[0];
15561 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15562 Group = Group.slice(1);
15563 }
15564 }
15565
15566 // FIXME: We assume every Decl in the group is in the same file.
15567 // This is false when preprocessor constructs the group from decls in
15568 // different files (e. g. macros or #include).
15569 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15570}
15571
15573 // Check that there are no default arguments inside the type of this
15574 // parameter.
15575 if (getLangOpts().CPlusPlus)
15577
15578 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15579 if (D.getCXXScopeSpec().isSet()) {
15580 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15581 << D.getCXXScopeSpec().getRange();
15582 }
15583
15584 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15585 // simple identifier except [...irrelevant cases...].
15586 switch (D.getName().getKind()) {
15588 break;
15589
15597 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15599 break;
15600
15603 // GetNameForDeclarator would not produce a useful name in this case.
15604 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15605 break;
15606 }
15607}
15608
15610 // This only matters in C.
15611 if (getLangOpts().CPlusPlus)
15612 return;
15613
15614 // This only matters if the declaration has a type.
15615 const auto *VD = dyn_cast<ValueDecl>(D);
15616 if (!VD)
15617 return;
15618
15619 // Get the type, this only matters for tag types.
15620 QualType QT = VD->getType();
15621 const auto *TD = QT->getAsTagDecl();
15622 if (!TD)
15623 return;
15624
15625 // Check if the tag declaration is lexically declared somewhere different
15626 // from the lexical declaration of the given object, then it will be hidden
15627 // in C++ and we should warn on it.
15628 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15629 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15630 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15631 Diag(TD->getLocation(), diag::note_declared_at);
15632 }
15633}
15634
15636 SourceLocation ExplicitThisLoc) {
15637 if (!ExplicitThisLoc.isValid())
15638 return;
15639 assert(S.getLangOpts().CPlusPlus &&
15640 "explicit parameter in non-cplusplus mode");
15641 if (!S.getLangOpts().CPlusPlus23)
15642 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15643 << P->getSourceRange();
15644
15645 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15646 // parameter pack.
15647 if (P->isParameterPack()) {
15648 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15649 << P->getSourceRange();
15650 return;
15651 }
15652 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15653 if (LambdaScopeInfo *LSI = S.getCurLambda())
15654 LSI->ExplicitObjectParameter = P;
15655}
15656
15658 SourceLocation ExplicitThisLoc) {
15659 const DeclSpec &DS = D.getDeclSpec();
15660
15661 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15662 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15663 // except for the special case of a single unnamed parameter of type void
15664 // with no storage class specifier, no type qualifier, and no following
15665 // ellipsis terminator.
15666 // Clang applies the C2y rules for 'register void' in all C language modes,
15667 // same as GCC, because it's questionable what that could possibly mean.
15668
15669 // C++03 [dcl.stc]p2 also permits 'auto'.
15670 StorageClass SC = SC_None;
15672 SC = SC_Register;
15673 // In C++11, the 'register' storage class specifier is deprecated.
15674 // In C++17, it is not allowed, but we tolerate it as an extension.
15675 if (getLangOpts().CPlusPlus11) {
15677 ? diag::ext_register_storage_class
15678 : diag::warn_deprecated_register)
15680 } else if (!getLangOpts().CPlusPlus &&
15682 D.getNumTypeObjects() == 0) {
15684 diag::err_invalid_storage_class_in_func_decl)
15687 }
15688 } else if (getLangOpts().CPlusPlus &&
15690 SC = SC_Auto;
15693 diag::err_invalid_storage_class_in_func_decl);
15695 }
15696
15698 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15700 if (DS.isInlineSpecified())
15701 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15702 << getLangOpts().CPlusPlus17;
15703 if (DS.hasConstexprSpecifier())
15704 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15705 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15706
15708
15710
15712 QualType parmDeclType = TInfo->getType();
15713
15714 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15715 const IdentifierInfo *II = D.getIdentifier();
15716 if (II) {
15719 LookupName(R, S);
15720 if (!R.empty()) {
15721 NamedDecl *PrevDecl = *R.begin();
15722 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15723 // Maybe we will complain about the shadowed template parameter.
15725 // Just pretend that we didn't see the previous declaration.
15726 PrevDecl = nullptr;
15727 }
15728 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15729 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15730 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15731 // Recover by removing the name
15732 II = nullptr;
15733 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15734 D.setInvalidType(true);
15735 }
15736 }
15737 }
15738
15739 // Incomplete resource arrays are not allowed as function parameters in HLSL
15740 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15741 parmDeclType->isHLSLResourceRecordArray()) {
15743 diag::err_hlsl_incomplete_resource_array_in_function_param);
15744 D.setInvalidType(true);
15745 }
15746
15747 // Temporarily put parameter variables in the translation unit, not
15748 // the enclosing context. This prevents them from accidentally
15749 // looking like class members in C++.
15750 ParmVarDecl *New =
15751 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15752 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15753
15754 if (D.isInvalidType())
15755 New->setInvalidDecl();
15756
15757 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15758
15759 assert(S->isFunctionPrototypeScope());
15760 assert(S->getFunctionPrototypeDepth() >= 1);
15761 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15763
15765
15766 // Add the parameter declaration into this scope.
15767 S->AddDecl(New);
15768 if (II)
15769 IdResolver.AddDecl(New);
15770
15772
15774 Diag(New->getLocation(), diag::err_module_private_local)
15777
15778 if (New->hasAttr<BlocksAttr>()) {
15779 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15780 }
15781
15782 New->deduceParmAddressSpace(Context);
15783
15784 return New;
15785}
15786
15788 SourceLocation Loc,
15789 QualType T) {
15790 /* FIXME: setting StartLoc == Loc.
15791 Would it be worth to modify callers so as to provide proper source
15792 location for the unnamed parameters, embedding the parameter's type? */
15793 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15794 T, Context.getTrivialTypeSourceInfo(T, Loc),
15795 SC_None, nullptr);
15796 Param->setImplicit();
15797 return Param;
15798}
15799
15801 // Don't diagnose unused-parameter errors in template instantiations; we
15802 // will already have done so in the template itself.
15804 return;
15805
15806 for (const ParmVarDecl *Parameter : Parameters) {
15807 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15808 !Parameter->hasAttr<UnusedAttr>() &&
15809 !Parameter->getIdentifier()->isPlaceholder()) {
15810 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15811 << Parameter->getDeclName();
15812 }
15813 }
15814}
15815
15817 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15818 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15819 return;
15820
15821 // Warn if the return value is pass-by-value and larger than the specified
15822 // threshold.
15823 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15824 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15825 if (Size > LangOpts.NumLargeByValueCopy)
15826 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15827 }
15828
15829 // Warn if any parameter is pass-by-value and larger than the specified
15830 // threshold.
15831 for (const ParmVarDecl *Parameter : Parameters) {
15832 QualType T = Parameter->getType();
15833 if (T->isDependentType() || !T.isPODType(Context))
15834 continue;
15835 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15836 if (Size > LangOpts.NumLargeByValueCopy)
15837 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15838 << Parameter << Size;
15839 }
15840}
15841
15843 SourceLocation NameLoc,
15844 const IdentifierInfo *Name, QualType T,
15845 TypeSourceInfo *TSInfo, StorageClass SC) {
15846 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15847 if (getLangOpts().ObjCAutoRefCount &&
15848 T.getObjCLifetime() == Qualifiers::OCL_None &&
15849 T->isObjCLifetimeType()) {
15850
15851 Qualifiers::ObjCLifetime lifetime;
15852
15853 // Special cases for arrays:
15854 // - if it's const, use __unsafe_unretained
15855 // - otherwise, it's an error
15856 if (T->isArrayType()) {
15857 if (!T.isConstQualified()) {
15861 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15862 else
15863 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15864 << TSInfo->getTypeLoc().getSourceRange();
15865 }
15867 } else {
15868 lifetime = T->getObjCARCImplicitLifetime();
15869 }
15870 T = Context.getLifetimeQualifiedType(T, lifetime);
15871 }
15872
15873 if (getLangOpts().OpenCL) {
15874 assert(!isa<DecayedType>(T));
15875 if (T->isArrayType() && !T.hasAddressSpace()) {
15876 QualType ET = Context.getAsArrayType(T)->getElementType();
15877 if (!ET.hasAddressSpace()) {
15878 // Add the private address space to the contents of the pointer when a
15879 // pointer parameter is declared as an array and not declared.
15881 T = Context.getAddrSpaceQualType(T, ImplAS);
15882 T = QualType(Context.getAsArrayType(T), 0);
15883 }
15884 }
15885 }
15886
15887 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15888 Context.getAdjustedParameterType(T),
15889 TSInfo, SC, nullptr);
15890
15891 // Make a note if we created a new pack in the scope of a lambda, so that
15892 // we know that references to that pack must also be expanded within the
15893 // lambda scope.
15894 if (New->isParameterPack())
15895 if (auto *CSI = getEnclosingLambdaOrBlock())
15896 CSI->LocalPacks.push_back(New);
15897
15898 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15899 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15900 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15903
15904 // Parameter declarators cannot be interface types. All ObjC objects are
15905 // passed by reference.
15906 if (T->isObjCObjectType()) {
15907 SourceLocation TypeEndLoc =
15909 Diag(NameLoc,
15910 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15911 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15912 T = Context.getObjCObjectPointerType(T);
15913 New->setType(T);
15914 }
15915
15916 // __ptrauth is forbidden on parameters.
15917 if (T.getPointerAuth()) {
15918 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15919 New->setInvalidDecl();
15920 }
15921
15922 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15923 // duration shall not be qualified by an address-space qualifier."
15924 // Since all parameters have automatic store duration, they can not have
15925 // an address space.
15926 if (T.getAddressSpace() != LangAS::Default &&
15927 // OpenCL allows function arguments declared to be an array of a type
15928 // to be qualified with an address space.
15929 !(getLangOpts().OpenCL &&
15930 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15931 // WebAssembly allows reference types as parameters. Funcref in particular
15932 // lives in a different address space.
15933 !(T->isFunctionPointerType() &&
15934 T.getAddressSpace() == LangAS::wasm_funcref) &&
15935 // HLSL allows function arguments to be qualified with an address space
15936 // if the groupshared annotation is used.
15937 !(getLangOpts().HLSL &&
15938 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
15939 Diag(NameLoc, diag::err_arg_with_address_space);
15940 New->setInvalidDecl();
15941 }
15942
15943 // PPC MMA non-pointer types are not allowed as function argument types.
15944 if (Context.getTargetInfo().getTriple().isPPC64() &&
15945 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15946 New->setInvalidDecl();
15947 }
15948
15949 return New;
15950}
15951
15953 SourceLocation LocAfterDecls) {
15955
15956 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15957 // in the declaration list shall have at least one declarator, those
15958 // declarators shall only declare identifiers from the identifier list, and
15959 // every identifier in the identifier list shall be declared.
15960 //
15961 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15962 // identifiers it names shall be declared in the declaration list."
15963 //
15964 // This is why we only diagnose in C99 and later. Note, the other conditions
15965 // listed are checked elsewhere.
15966 if (!FTI.hasPrototype) {
15967 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15968 --i;
15969 if (FTI.Params[i].Param == nullptr) {
15970 if (getLangOpts().C99) {
15971 SmallString<256> Code;
15972 llvm::raw_svector_ostream(Code)
15973 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15974 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15975 << FTI.Params[i].Ident
15976 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15977 }
15978
15979 // Implicitly declare the argument as type 'int' for lack of a better
15980 // type.
15981 AttributeFactory attrs;
15982 DeclSpec DS(attrs);
15983 const char* PrevSpec; // unused
15984 unsigned DiagID; // unused
15985 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15986 DiagID, Context.getPrintingPolicy());
15987 // Use the identifier location for the type source range.
15988 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15989 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15992 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15993 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15994 }
15995 }
15996 }
15997}
15998
15999Decl *
16001 MultiTemplateParamsArg TemplateParameterLists,
16002 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16003 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16004 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16005 Scope *ParentScope = FnBodyScope->getParent();
16006
16007 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16008 // we define a non-templated function definition, we will create a declaration
16009 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16010 // The base function declaration will have the equivalent of an `omp declare
16011 // variant` annotation which specifies the mangled definition as a
16012 // specialization function under the OpenMP context defined as part of the
16013 // `omp begin declare variant`.
16015 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16017 ParentScope, D, TemplateParameterLists, Bases);
16018
16020 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
16021 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
16022
16023 if (!Bases.empty())
16025 Bases);
16026
16027 return Dcl;
16028}
16029
16031 Consumer.HandleInlineFunctionDefinition(D);
16032}
16033
16035 const FunctionDecl *&PossiblePrototype) {
16036 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16037 Prev = Prev->getPreviousDecl()) {
16038 // Ignore any declarations that occur in function or method
16039 // scope, because they aren't visible from the header.
16040 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16041 continue;
16042
16043 PossiblePrototype = Prev;
16044 return Prev->getType()->isFunctionProtoType();
16045 }
16046 return false;
16047}
16048
16049static bool
16051 const FunctionDecl *&PossiblePrototype) {
16052 // Don't warn about invalid declarations.
16053 if (FD->isInvalidDecl())
16054 return false;
16055
16056 // Or declarations that aren't global.
16057 if (!FD->isGlobal())
16058 return false;
16059
16060 // Don't warn about C++ member functions.
16061 if (isa<CXXMethodDecl>(FD))
16062 return false;
16063
16064 // Don't warn about 'main'.
16066 if (IdentifierInfo *II = FD->getIdentifier())
16067 if (II->isStr("main") || II->isStr("efi_main"))
16068 return false;
16069
16070 if (FD->isMSVCRTEntryPoint())
16071 return false;
16072
16073 // Don't warn about inline functions.
16074 if (FD->isInlined())
16075 return false;
16076
16077 // Don't warn about function templates.
16079 return false;
16080
16081 // Don't warn about function template specializations.
16083 return false;
16084
16085 // Don't warn for OpenCL kernels.
16086 if (FD->hasAttr<DeviceKernelAttr>())
16087 return false;
16088
16089 // Don't warn on explicitly deleted functions.
16090 if (FD->isDeleted())
16091 return false;
16092
16093 // Don't warn on implicitly local functions (such as having local-typed
16094 // parameters).
16095 if (!FD->isExternallyVisible())
16096 return false;
16097
16098 // If we were able to find a potential prototype, don't warn.
16099 if (FindPossiblePrototype(FD, PossiblePrototype))
16100 return false;
16101
16102 return true;
16103}
16104
16105void
16107 const FunctionDecl *EffectiveDefinition,
16108 SkipBodyInfo *SkipBody) {
16109 const FunctionDecl *Definition = EffectiveDefinition;
16110 if (!Definition &&
16111 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16112 return;
16113
16114 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16115 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16116 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16117 // A merged copy of the same function, instantiated as a member of
16118 // the same class, is OK.
16119 if (declaresSameEntity(OrigFD, OrigDef) &&
16120 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
16122 return;
16123 }
16124 }
16125 }
16126
16128 return;
16129
16130 // Don't emit an error when this is redefinition of a typo-corrected
16131 // definition.
16133 return;
16134
16135 bool DefinitionVisible = false;
16136 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
16137 (Definition->getFormalLinkage() == Linkage::Internal ||
16138 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16139 !Definition->getTemplateParameterLists().empty())) {
16140 SkipBody->ShouldSkip = true;
16141 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16142 if (!DefinitionVisible) {
16143 if (auto *TD = Definition->getDescribedFunctionTemplate())
16146 }
16147 return;
16148 }
16149
16150 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16151 Definition->getStorageClass() == SC_Extern)
16152 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
16153 << FD << getLangOpts().CPlusPlus;
16154 else
16155 Diag(FD->getLocation(), diag::err_redefinition) << FD;
16156
16157 Diag(Definition->getLocation(), diag::note_previous_definition);
16158 FD->setInvalidDecl();
16159}
16160
16162 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16163
16165 LSI->CallOperator = CallOperator;
16166 LSI->Lambda = LambdaClass;
16167 LSI->ReturnType = CallOperator->getReturnType();
16168 // When this function is called in situation where the context of the call
16169 // operator is not entered, we set AfterParameterList to false, so that
16170 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16171 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16172 // where we would set the CurContext to the lambda operator before
16173 // substituting into it. In this case the flag needs to be true such that
16174 // tryCaptureVariable can correctly handle potential captures thereof.
16175 LSI->AfterParameterList = CurContext == CallOperator;
16176
16177 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16178 // used at the point of dealing with potential captures.
16179 //
16180 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16181 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16182 // associated. (Technically, we could recover that list from their
16183 // instantiation patterns, but for now, the GLTemplateParameterList seems
16184 // unnecessary in these cases.)
16185 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16186 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16187 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16188
16189 if (LCD == LCD_None)
16191 else if (LCD == LCD_ByCopy)
16193 else if (LCD == LCD_ByRef)
16195 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16196
16198 LSI->Mutable = !CallOperator->isConst();
16199 if (CallOperator->isExplicitObjectMemberFunction())
16200 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16201
16202 // Add the captures to the LSI so they can be noted as already
16203 // captured within tryCaptureVar.
16204 auto I = LambdaClass->field_begin();
16205 for (const auto &C : LambdaClass->captures()) {
16206 if (C.capturesVariable()) {
16207 ValueDecl *VD = C.getCapturedVar();
16208 if (VD->isInitCapture())
16209 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16210 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16211 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16212 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16213 /*EllipsisLoc*/C.isPackExpansion()
16214 ? C.getEllipsisLoc() : SourceLocation(),
16215 I->getType(), /*Invalid*/false);
16216
16217 } else if (C.capturesThis()) {
16218 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16219 C.getCaptureKind() == LCK_StarThis);
16220 } else {
16221 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16222 I->getType());
16223 }
16224 ++I;
16225 }
16226 return LSI;
16227}
16228
16230 SkipBodyInfo *SkipBody,
16231 FnBodyKind BodyKind) {
16232 if (!D) {
16233 // Parsing the function declaration failed in some way. Push on a fake scope
16234 // anyway so we can try to parse the function body.
16237 return D;
16238 }
16239
16240 FunctionDecl *FD = nullptr;
16241
16242 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16243 FD = FunTmpl->getTemplatedDecl();
16244 else
16245 FD = cast<FunctionDecl>(D);
16246
16247 // Do not push if it is a lambda because one is already pushed when building
16248 // the lambda in ActOnStartOfLambdaDefinition().
16249 if (!isLambdaCallOperator(FD))
16251 FD);
16252
16253 // Check for defining attributes before the check for redefinition.
16254 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16255 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16256 FD->dropAttr<AliasAttr>();
16257 FD->setInvalidDecl();
16258 }
16259 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16260 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16261 FD->dropAttr<IFuncAttr>();
16262 FD->setInvalidDecl();
16263 }
16264 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16265 if (Context.getTargetInfo().getTriple().isAArch64() &&
16266 !Context.getTargetInfo().hasFeature("fmv") &&
16267 !Attr->isDefaultVersion()) {
16268 // If function multi versioning disabled skip parsing function body
16269 // defined with non-default target_version attribute
16270 if (SkipBody)
16271 SkipBody->ShouldSkip = true;
16272 return nullptr;
16273 }
16274 }
16275
16276 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16277 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16278 Ctor->isDefaultConstructor() &&
16279 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16280 // If this is an MS ABI dllexport default constructor, instantiate any
16281 // default arguments.
16283 }
16284 }
16285
16286 // See if this is a redefinition. If 'will have body' (or similar) is already
16287 // set, then these checks were already performed when it was set.
16288 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16290 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16291
16292 // If we're skipping the body, we're done. Don't enter the scope.
16293 if (SkipBody && SkipBody->ShouldSkip)
16294 return D;
16295 }
16296
16297 // Mark this function as "will have a body eventually". This lets users to
16298 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16299 // this function.
16300 FD->setWillHaveBody();
16301
16302 // If we are instantiating a generic lambda call operator, push
16303 // a LambdaScopeInfo onto the function stack. But use the information
16304 // that's already been calculated (ActOnLambdaExpr) to prime the current
16305 // LambdaScopeInfo.
16306 // When the template operator is being specialized, the LambdaScopeInfo,
16307 // has to be properly restored so that tryCaptureVariable doesn't try
16308 // and capture any new variables. In addition when calculating potential
16309 // captures during transformation of nested lambdas, it is necessary to
16310 // have the LSI properly restored.
16312 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16313 // specialized.
16315 Diag(FD->getLocation(), diag::err_lambda_explicit_temp_spec)
16316 << /*specialization*/ 0;
16318 Diag(RD->getLocation(), diag::note_defined_here) << RD;
16319
16320 FD->setInvalidDecl();
16322 } else {
16323 assert(inTemplateInstantiation() &&
16324 "There should be an active template instantiation on the stack "
16325 "when instantiating a generic lambda!");
16327 }
16328 } else {
16329 // Enter a new function scope
16331 }
16332
16333 // Builtin functions cannot be defined.
16334 if (unsigned BuiltinID = FD->getBuiltinID()) {
16335 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16336 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16337 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16338 FD->setInvalidDecl();
16339 }
16340 }
16341
16342 // The return type of a function definition must be complete (C99 6.9.1p3).
16343 // C++23 [dcl.fct.def.general]/p2
16344 // The type of [...] the return for a function definition
16345 // shall not be a (possibly cv-qualified) class type that is incomplete
16346 // or abstract within the function body unless the function is deleted.
16347 QualType ResultType = FD->getReturnType();
16348 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16349 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16350 (RequireCompleteType(FD->getLocation(), ResultType,
16351 diag::err_func_def_incomplete_result) ||
16353 diag::err_abstract_type_in_decl,
16355 FD->setInvalidDecl();
16356
16357 if (FnBodyScope)
16358 PushDeclContext(FnBodyScope, FD);
16359
16360 // Check the validity of our function parameters
16361 if (BodyKind != FnBodyKind::Delete)
16363 /*CheckParameterNames=*/true);
16364
16365 // Add non-parameter declarations already in the function to the current
16366 // scope.
16367 if (FnBodyScope) {
16368 for (Decl *NPD : FD->decls()) {
16369 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16370 if (!NonParmDecl)
16371 continue;
16372 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16373 "parameters should not be in newly created FD yet");
16374
16375 // If the decl has a name, make it accessible in the current scope.
16376 if (NonParmDecl->getDeclName())
16377 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16378
16379 // Similarly, dive into enums and fish their constants out, making them
16380 // accessible in this scope.
16381 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16382 for (auto *EI : ED->enumerators())
16383 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16384 }
16385 }
16386 }
16387
16388 // Introduce our parameters into the function scope
16389 for (auto *Param : FD->parameters()) {
16390 Param->setOwningFunction(FD);
16391
16392 // If this has an identifier, add it to the scope stack.
16393 if (Param->getIdentifier() && FnBodyScope) {
16394 CheckShadow(FnBodyScope, Param);
16395
16396 PushOnScopeChains(Param, FnBodyScope);
16397 }
16398 }
16399
16400 // C++ [module.import/6]
16401 // ...
16402 // A header unit shall not contain a definition of a non-inline function or
16403 // variable whose name has external linkage.
16404 //
16405 // Deleted and Defaulted functions are implicitly inline (but the
16406 // inline state is not set at this point, so check the BodyKind explicitly).
16407 // We choose to allow weak & selectany definitions, as they are common in
16408 // headers, and have semantics similar to inline definitions which are allowed
16409 // in header units.
16410 // FIXME: Consider an alternate location for the test where the inlined()
16411 // state is complete.
16412 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16413 !FD->isInvalidDecl() && !FD->isInlined() &&
16414 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16415 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16416 !FD->isTemplateInstantiation() &&
16417 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16418 assert(FD->isThisDeclarationADefinition());
16419 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16420 FD->setInvalidDecl();
16421 }
16422
16423 // Ensure that the function's exception specification is instantiated.
16424 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16426
16427 // dllimport cannot be applied to non-inline function definitions.
16428 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16429 !FD->isTemplateInstantiation()) {
16430 assert(!FD->hasAttr<DLLExportAttr>());
16431 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16432 FD->setInvalidDecl();
16433 return D;
16434 }
16435
16436 // Some function attributes (like OptimizeNoneAttr) need actions before
16437 // parsing body started.
16439
16440 // We want to attach documentation to original Decl (which might be
16441 // a function template).
16443 if (getCurLexicalContext()->isObjCContainer() &&
16444 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16445 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16446 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16447
16449
16450 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16451 FnBodyScope) {
16452 // An implicit call expression is synthesized for functions declared with
16453 // the sycl_kernel_entry_point attribute. The call may resolve to a
16454 // function template, a member function template, or a call operator
16455 // of a variable template depending on the results of unqualified lookup
16456 // for 'sycl_kernel_launch' from the beginning of the function body.
16457 // Performing that lookup requires the stack of parsing scopes active
16458 // when the definition is parsed and is thus done here; the result is
16459 // cached in FunctionScopeInfo and used to synthesize the (possibly
16460 // unresolved) call expression after the function body has been parsed.
16461 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16462 if (!SKEPAttr->isInvalidAttr()) {
16463 ExprResult LaunchIdExpr =
16464 SYCL().BuildSYCLKernelLaunchIdExpr(FD, SKEPAttr->getKernelName());
16465 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16466 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16467 // treated as an error in the definition of 'FD'; treating it as an error
16468 // of the declaration would affect overload resolution which would
16469 // potentially result in additional errors. If construction of
16470 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16471 // a null pointer value below; that is expected.
16472 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16473 }
16474 }
16475
16476 return D;
16477}
16478
16480 if (!FD || FD->isInvalidDecl())
16481 return;
16482 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16483 FD = TD->getTemplatedDecl();
16484 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16487 CurFPFeatures.applyChanges(FPO);
16488 FpPragmaStack.CurrentValue =
16489 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16490 }
16491}
16492
16494 ReturnStmt **Returns = Scope->Returns.data();
16495
16496 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16497 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16498 if (!NRVOCandidate->isNRVOVariable()) {
16499 Diag(Returns[I]->getRetValue()->getExprLoc(),
16500 diag::warn_not_eliding_copy_on_return);
16501 Returns[I]->setNRVOCandidate(nullptr);
16502 }
16503 }
16504 }
16505}
16506
16508 // We can't delay parsing the body of a constexpr function template (yet).
16510 return false;
16511
16512 // We can't delay parsing the body of a function template with a deduced
16513 // return type (yet).
16514 if (D.getDeclSpec().hasAutoTypeSpec()) {
16515 // If the placeholder introduces a non-deduced trailing return type,
16516 // we can still delay parsing it.
16517 if (D.getNumTypeObjects()) {
16518 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16519 if (Outer.Kind == DeclaratorChunk::Function &&
16520 Outer.Fun.hasTrailingReturnType()) {
16521 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16522 return Ty.isNull() || !Ty->isUndeducedType();
16523 }
16524 }
16525 return false;
16526 }
16527
16528 return true;
16529}
16530
16532 // We cannot skip the body of a function (or function template) which is
16533 // constexpr, since we may need to evaluate its body in order to parse the
16534 // rest of the file.
16535 // We cannot skip the body of a function with an undeduced return type,
16536 // because any callers of that function need to know the type.
16537 if (const FunctionDecl *FD = D->getAsFunction()) {
16538 if (FD->isConstexpr())
16539 return false;
16540 // We can't simply call Type::isUndeducedType here, because inside template
16541 // auto can be deduced to a dependent type, which is not considered
16542 // "undeduced".
16543 if (FD->getReturnType()->getContainedDeducedType())
16544 return false;
16545 }
16546 return Consumer.shouldSkipFunctionBody(D);
16547}
16548
16550 if (!Decl)
16551 return nullptr;
16552 if (FunctionDecl *FD = Decl->getAsFunction())
16553 FD->setHasSkippedBody();
16554 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16555 MD->setHasSkippedBody();
16556 return Decl;
16557}
16558
16559/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16560/// body.
16562public:
16563 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16565 if (!IsLambda)
16566 S.PopExpressionEvaluationContext();
16567 }
16568
16569private:
16570 Sema &S;
16571 bool IsLambda = false;
16572};
16573
16575 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16576
16577 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16578 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16579 if (!Inserted)
16580 return It->second;
16581
16582 bool R = false;
16583 const BlockDecl *CurBD = BD;
16584
16585 do {
16586 R = !CurBD->doesNotEscape();
16587 if (R)
16588 break;
16589 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16590 } while (CurBD);
16591
16592 return It->second = R;
16593 };
16594
16595 // If the location where 'self' is implicitly retained is inside a escaping
16596 // block, emit a diagnostic.
16597 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16599 if (IsOrNestedInEscapingBlock(P.second))
16600 S.Diag(P.first, diag::warn_implicitly_retains_self)
16601 << FixItHint::CreateInsertion(P.first, "self->");
16602}
16603
16604static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16605 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16606 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16607}
16608
16610 return methodHasName(FD, "get_return_object");
16611}
16612
16614 return FD->isStatic() &&
16615 methodHasName(FD, "get_return_object_on_allocation_failure");
16616}
16617
16620 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16621 return;
16622 // Allow some_promise_type::get_return_object().
16624 return;
16625 if (!FD->hasAttr<CoroWrapperAttr>())
16626 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16627}
16628
16629Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16630 bool RetainFunctionScopeInfo) {
16632 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16633
16634 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16635 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16636
16637 SourceLocation AnalysisLoc;
16638 if (Body)
16639 AnalysisLoc = Body->getEndLoc();
16640 else if (FD)
16641 AnalysisLoc = FD->getEndLoc();
16643 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16644 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16645
16646 // If we skip function body, we can't tell if a function is a coroutine.
16647 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16648 if (FSI->isCoroutine())
16650 else
16652 }
16653
16654 // Diagnose invalid SYCL kernel entry point function declarations
16655 // and build SYCLKernelCallStmts for valid ones.
16656 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16657 SYCLKernelEntryPointAttr *SKEPAttr =
16658 FD->getAttr<SYCLKernelEntryPointAttr>();
16659 if (FD->isDefaulted()) {
16660 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16661 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16662 SKEPAttr->setInvalidAttr();
16663 } else if (FD->isDeleted()) {
16664 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16665 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16666 SKEPAttr->setInvalidAttr();
16667 } else if (FSI->isCoroutine()) {
16668 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16669 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16670 SKEPAttr->setInvalidAttr();
16671 } else if (Body && isa<CXXTryStmt>(Body)) {
16672 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16673 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16674 SKEPAttr->setInvalidAttr();
16675 }
16676
16677 // Build an unresolved SYCL kernel call statement for a function template,
16678 // validate that a SYCL kernel call statement was instantiated for an
16679 // (implicit or explicit) instantiation of a function template, or otherwise
16680 // build a (resolved) SYCL kernel call statement for a non-templated
16681 // function or an explicit specialization.
16682 if (Body && !SKEPAttr->isInvalidAttr()) {
16683 StmtResult SR;
16684 if (FD->isTemplateInstantiation()) {
16685 // The function body should already be a SYCLKernelCallStmt in this
16686 // case, but might not be if there were previous errors.
16687 SR = Body;
16688 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16689 // If name lookup for a template named sycl_kernel_launch failed
16690 // earlier, don't try to build a SYCL kernel call statement as that
16691 // would cause additional errors to be issued; just proceed with the
16692 // original function body.
16693 SR = Body;
16694 } else if (FD->isTemplated()) {
16696 cast<CompoundStmt>(Body), getCurFunction()->SYCLKernelLaunchIdExpr);
16697 } else {
16699 FD, cast<CompoundStmt>(Body),
16700 getCurFunction()->SYCLKernelLaunchIdExpr);
16701 }
16702 // If construction of the replacement body fails, just continue with the
16703 // original function body. An early error return here is not valid; the
16704 // current declaration context and function scopes must be popped before
16705 // returning.
16706 if (SR.isUsable())
16707 Body = SR.get();
16708 }
16709 }
16710
16711 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16712 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16713 if (FD->isDeletedAsWritten())
16714 Diag(SEAttr->getLocation(),
16715 diag::err_sycl_external_invalid_deleted_function)
16716 << SEAttr;
16717 }
16718
16719 {
16720 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16721 // one is already popped when finishing the lambda in BuildLambdaExpr().
16722 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16723 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16724 if (FD) {
16725 // The function body and the DefaultedOrDeletedInfo, if present, use
16726 // the same storage; don't overwrite the latter if the former is null
16727 // (the body is initialised to null anyway, so even if the latter isn't
16728 // present, this would still be a no-op).
16729 if (Body)
16730 FD->setBody(Body);
16731 FD->setWillHaveBody(false);
16732
16733 if (getLangOpts().CPlusPlus14) {
16734 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16735 FD->getReturnType()->isUndeducedType()) {
16736 // For a function with a deduced result type to return void,
16737 // the result type as written must be 'auto' or 'decltype(auto)',
16738 // possibly cv-qualified or constrained, but not ref-qualified.
16739 if (!FD->getReturnType()->getAs<AutoType>()) {
16740 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16741 << FD->getReturnType();
16742 FD->setInvalidDecl();
16743 } else {
16744 // Falling off the end of the function is the same as 'return;'.
16745 Expr *Dummy = nullptr;
16747 FD, dcl->getLocation(), Dummy,
16748 FD->getReturnType()->getAs<AutoType>()))
16749 FD->setInvalidDecl();
16750 }
16751 }
16752 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16753 // In C++11, we don't use 'auto' deduction rules for lambda call
16754 // operators because we don't support return type deduction.
16755 auto *LSI = getCurLambda();
16756 if (LSI->HasImplicitReturnType) {
16758
16759 // C++11 [expr.prim.lambda]p4:
16760 // [...] if there are no return statements in the compound-statement
16761 // [the deduced type is] the type void
16762 QualType RetType =
16763 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16764
16765 // Update the return type to the deduced type.
16766 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16767 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16768 Proto->getExtProtoInfo()));
16769 }
16770 }
16771
16772 // If the function implicitly returns zero (like 'main') or is naked,
16773 // don't complain about missing return statements.
16774 // Clang implicitly returns 0 in C89 mode, but that's considered an
16775 // extension. The check is necessary to ensure the expected extension
16776 // warning is emitted in C89 mode.
16777 if ((FD->hasImplicitReturnZero() &&
16778 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16779 FD->hasAttr<NakedAttr>())
16781
16782 // MSVC permits the use of pure specifier (=0) on function definition,
16783 // defined at class scope, warn about this non-standard construct.
16784 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16785 !FD->isOutOfLine())
16786 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16787
16788 if (!FD->isInvalidDecl()) {
16789 // Don't diagnose unused parameters of defaulted, deleted or naked
16790 // functions.
16791 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16792 !FD->hasAttr<NakedAttr>())
16795 FD->getReturnType(), FD);
16796
16797 // If this is a structor, we need a vtable.
16798 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16799 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16800 else if (CXXDestructorDecl *Destructor =
16801 dyn_cast<CXXDestructorDecl>(FD))
16802 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16803
16804 // Try to apply the named return value optimization. We have to check
16805 // if we can do this here because lambdas keep return statements around
16806 // to deduce an implicit return type.
16807 if (FD->getReturnType()->isRecordType() &&
16809 computeNRVO(Body, FSI);
16810 }
16811
16812 // GNU warning -Wmissing-prototypes:
16813 // Warn if a global function is defined without a previous
16814 // prototype declaration. This warning is issued even if the
16815 // definition itself provides a prototype. The aim is to detect
16816 // global functions that fail to be declared in header files.
16817 const FunctionDecl *PossiblePrototype = nullptr;
16818 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16819 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16820
16821 if (PossiblePrototype) {
16822 // We found a declaration that is not a prototype,
16823 // but that could be a zero-parameter prototype
16824 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16825 TypeLoc TL = TI->getTypeLoc();
16827 Diag(PossiblePrototype->getLocation(),
16828 diag::note_declaration_not_a_prototype)
16829 << (FD->getNumParams() != 0)
16831 FTL.getRParenLoc(), "void")
16832 : FixItHint{});
16833 }
16834 } else {
16835 // Returns true if the token beginning at this Loc is `const`.
16836 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16837 const LangOptions &LangOpts) {
16838 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16839 if (LocInfo.first.isInvalid())
16840 return false;
16841
16842 bool Invalid = false;
16843 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16844 if (Invalid)
16845 return false;
16846
16847 if (LocInfo.second > Buffer.size())
16848 return false;
16849
16850 const char *LexStart = Buffer.data() + LocInfo.second;
16851 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16852
16853 return StartTok.consume_front("const") &&
16854 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16855 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16856 };
16857
16858 auto findBeginLoc = [&]() {
16859 // If the return type has `const` qualifier, we want to insert
16860 // `static` before `const` (and not before the typename).
16861 if ((FD->getReturnType()->isAnyPointerType() &&
16864 // But only do this if we can determine where the `const` is.
16865
16866 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16867 getLangOpts()))
16868
16869 return FD->getBeginLoc();
16870 }
16871 return FD->getTypeSpecStartLoc();
16872 };
16874 diag::note_static_for_internal_linkage)
16875 << /* function */ 1
16876 << (FD->getStorageClass() == SC_None
16877 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16878 : FixItHint{});
16879 }
16880 }
16881
16882 // We might not have found a prototype because we didn't wish to warn on
16883 // the lack of a missing prototype. Try again without the checks for
16884 // whether we want to warn on the missing prototype.
16885 if (!PossiblePrototype)
16886 (void)FindPossiblePrototype(FD, PossiblePrototype);
16887
16888 // If the function being defined does not have a prototype, then we may
16889 // need to diagnose it as changing behavior in C23 because we now know
16890 // whether the function accepts arguments or not. This only handles the
16891 // case where the definition has no prototype but does have parameters
16892 // and either there is no previous potential prototype, or the previous
16893 // potential prototype also has no actual prototype. This handles cases
16894 // like:
16895 // void f(); void f(a) int a; {}
16896 // void g(a) int a; {}
16897 // See MergeFunctionDecl() for other cases of the behavior change
16898 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16899 // type without a prototype.
16900 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16901 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16902 !PossiblePrototype->isImplicit()))) {
16903 // The function definition has parameters, so this will change behavior
16904 // in C23. If there is a possible prototype, it comes before the
16905 // function definition.
16906 // FIXME: The declaration may have already been diagnosed as being
16907 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16908 // there's no way to test for the "changes behavior" condition in
16909 // SemaType.cpp when forming the declaration's function type. So, we do
16910 // this awkward dance instead.
16911 //
16912 // If we have a possible prototype and it declares a function with a
16913 // prototype, we don't want to diagnose it; if we have a possible
16914 // prototype and it has no prototype, it may have already been
16915 // diagnosed in SemaType.cpp as deprecated depending on whether
16916 // -Wstrict-prototypes is enabled. If we already warned about it being
16917 // deprecated, add a note that it also changes behavior. If we didn't
16918 // warn about it being deprecated (because the diagnostic is not
16919 // enabled), warn now that it is deprecated and changes behavior.
16920
16921 // This K&R C function definition definitely changes behavior in C23,
16922 // so diagnose it.
16923 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16924 << /*definition*/ 1 << /* not supported in C23 */ 0;
16925
16926 // If we have a possible prototype for the function which is a user-
16927 // visible declaration, we already tested that it has no prototype.
16928 // This will change behavior in C23. This gets a warning rather than a
16929 // note because it's the same behavior-changing problem as with the
16930 // definition.
16931 if (PossiblePrototype)
16932 Diag(PossiblePrototype->getLocation(),
16933 diag::warn_non_prototype_changes_behavior)
16934 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16935 << /*definition*/ 1;
16936 }
16937
16938 // Warn on CPUDispatch with an actual body.
16939 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16940 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16941 if (!CmpndBody->body_empty())
16942 Diag(CmpndBody->body_front()->getBeginLoc(),
16943 diag::warn_dispatch_body_ignored);
16944
16945 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16946 const CXXMethodDecl *KeyFunction;
16947 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16948 MD->isVirtual() &&
16949 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16950 MD == KeyFunction->getCanonicalDecl()) {
16951 // Update the key-function state if necessary for this ABI.
16952 if (FD->isInlined() &&
16953 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16954 Context.setNonKeyFunction(MD);
16955
16956 // If the newly-chosen key function is already defined, then we
16957 // need to mark the vtable as used retroactively.
16958 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16959 const FunctionDecl *Definition;
16960 if (KeyFunction && KeyFunction->isDefined(Definition))
16961 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16962 } else {
16963 // We just defined they key function; mark the vtable as used.
16964 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16965 }
16966 }
16967 }
16968
16969 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16970 "Function parsing confused");
16971 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16972 assert(MD == getCurMethodDecl() && "Method parsing confused");
16973 MD->setBody(Body);
16974 if (!MD->isInvalidDecl()) {
16976 MD->getReturnType(), MD);
16977
16978 if (Body)
16979 computeNRVO(Body, FSI);
16980 }
16981 if (FSI->ObjCShouldCallSuper) {
16982 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16983 << MD->getSelector().getAsString();
16984 FSI->ObjCShouldCallSuper = false;
16985 }
16987 const ObjCMethodDecl *InitMethod = nullptr;
16988 bool isDesignated =
16989 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16990 assert(isDesignated && InitMethod);
16991 (void)isDesignated;
16992
16993 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16994 auto IFace = MD->getClassInterface();
16995 if (!IFace)
16996 return false;
16997 auto SuperD = IFace->getSuperClass();
16998 if (!SuperD)
16999 return false;
17000 return SuperD->getIdentifier() ==
17001 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
17002 };
17003 // Don't issue this warning for unavailable inits or direct subclasses
17004 // of NSObject.
17005 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17006 Diag(MD->getLocation(),
17007 diag::warn_objc_designated_init_missing_super_call);
17008 Diag(InitMethod->getLocation(),
17009 diag::note_objc_designated_init_marked_here);
17010 }
17012 }
17013 if (FSI->ObjCWarnForNoInitDelegation) {
17014 // Don't issue this warning for unavailable inits.
17015 if (!MD->isUnavailable())
17016 Diag(MD->getLocation(),
17017 diag::warn_objc_secondary_init_missing_init_call);
17018 FSI->ObjCWarnForNoInitDelegation = false;
17019 }
17020
17022 } else {
17023 // Parsing the function declaration failed in some way. Pop the fake scope
17024 // we pushed on.
17025 PopFunctionScopeInfo(ActivePolicy, dcl);
17026 return nullptr;
17027 }
17028
17029 if (Body) {
17032 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17034 }
17035
17036 assert(!FSI->ObjCShouldCallSuper &&
17037 "This should only be set for ObjC methods, which should have been "
17038 "handled in the block above.");
17039
17040 // Verify and clean out per-function state.
17041 if (Body && (!FD || !FD->isDefaulted())) {
17042 // C++ constructors that have function-try-blocks can't have return
17043 // statements in the handlers of that block. (C++ [except.handle]p14)
17044 // Verify this.
17045 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
17047
17048 // Verify that gotos and switch cases don't jump into scopes illegally.
17049 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17051
17052 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
17053 if (!Destructor->getParent()->isDependentType())
17055
17057 Destructor->getParent());
17058 }
17059
17060 // If any errors have occurred, clear out any temporaries that may have
17061 // been leftover. This ensures that these temporaries won't be picked up
17062 // for deletion in some later function.
17065 getDiagnostics().getSuppressAllDiagnostics()) {
17067 }
17069 // Since the body is valid, issue any analysis-based warnings that are
17070 // enabled.
17071 ActivePolicy = &WP;
17072 }
17073
17074 if (!IsInstantiation && FD &&
17075 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17076 !FD->isInvalidDecl() &&
17078 FD->setInvalidDecl();
17079
17080 if (FD && FD->hasAttr<NakedAttr>()) {
17081 for (const Stmt *S : Body->children()) {
17082 // Allow local register variables without initializer as they don't
17083 // require prologue.
17084 bool RegisterVariables = false;
17085 if (auto *DS = dyn_cast<DeclStmt>(S)) {
17086 for (const auto *Decl : DS->decls()) {
17087 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
17088 RegisterVariables =
17089 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17090 if (!RegisterVariables)
17091 break;
17092 }
17093 }
17094 }
17095 if (RegisterVariables)
17096 continue;
17097 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
17098 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
17099 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
17100 FD->setInvalidDecl();
17101 break;
17102 }
17103 }
17104 }
17105
17106 assert(ExprCleanupObjects.size() ==
17107 ExprEvalContexts.back().NumCleanupObjects &&
17108 "Leftover temporaries in function");
17109 assert(!Cleanup.exprNeedsCleanups() &&
17110 "Unaccounted cleanups in function");
17111 assert(MaybeODRUseExprs.empty() &&
17112 "Leftover expressions for odr-use checking");
17113 }
17114 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17115 // the declaration context below. Otherwise, we're unable to transform
17116 // 'this' expressions when transforming immediate context functions.
17117
17118 if (FD)
17120
17121 if (!IsInstantiation)
17123
17124 if (!RetainFunctionScopeInfo)
17125 PopFunctionScopeInfo(ActivePolicy, dcl);
17126 // If any errors have occurred, clear out any temporaries that may have
17127 // been leftover. This ensures that these temporaries won't be picked up for
17128 // deletion in some later function.
17131 }
17132
17133 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17134 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17135 auto ES = getEmissionStatus(FD);
17139 }
17140
17141 if (FD && !FD->isDeleted())
17142 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
17143
17144 return dcl;
17145}
17146
17147/// When we finish delayed parsing of an attribute, we must attach it to the
17148/// relevant Decl.
17150 ParsedAttributes &Attrs) {
17151 // Always attach attributes to the underlying decl.
17152 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
17153 D = TD->getTemplatedDecl();
17154 ProcessDeclAttributeList(S, D, Attrs);
17155 ProcessAPINotes(D);
17156
17157 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
17158 if (Method->isStatic())
17160}
17161
17163 IdentifierInfo &II, Scope *S) {
17164 // It is not valid to implicitly define a function in C23.
17165 assert(LangOpts.implicitFunctionsAllowed() &&
17166 "Implicit function declarations aren't allowed in this language mode");
17167
17168 // Find the scope in which the identifier is injected and the corresponding
17169 // DeclContext.
17170 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17171 // In that case, we inject the declaration into the translation unit scope
17172 // instead.
17173 Scope *BlockScope = S;
17174 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17175 BlockScope = BlockScope->getParent();
17176
17177 // Loop until we find a DeclContext that is either a function/method or the
17178 // translation unit, which are the only two valid places to implicitly define
17179 // a function. This avoids accidentally defining the function within a tag
17180 // declaration, for example.
17181 Scope *ContextScope = BlockScope;
17182 while (!ContextScope->getEntity() ||
17183 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17184 !ContextScope->getEntity()->isTranslationUnit()))
17185 ContextScope = ContextScope->getParent();
17186 ContextRAII SavedContext(*this, ContextScope->getEntity());
17187
17188 // Before we produce a declaration for an implicitly defined
17189 // function, see whether there was a locally-scoped declaration of
17190 // this name as a function or variable. If so, use that
17191 // (non-visible) declaration, and complain about it.
17192 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
17193 if (ExternCPrev) {
17194 // We still need to inject the function into the enclosing block scope so
17195 // that later (non-call) uses can see it.
17196 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
17197
17198 // C89 footnote 38:
17199 // If in fact it is not defined as having type "function returning int",
17200 // the behavior is undefined.
17201 if (!isa<FunctionDecl>(ExternCPrev) ||
17202 !Context.typesAreCompatible(
17203 cast<FunctionDecl>(ExternCPrev)->getType(),
17204 Context.getFunctionNoProtoType(Context.IntTy))) {
17205 Diag(Loc, diag::ext_use_out_of_scope_declaration)
17206 << ExternCPrev << !getLangOpts().C99;
17207 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
17208 return ExternCPrev;
17209 }
17210 }
17211
17212 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17213 unsigned diag_id;
17214 if (II.getName().starts_with("__builtin_"))
17215 diag_id = diag::warn_builtin_unknown;
17216 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17217 else if (getLangOpts().C99)
17218 diag_id = diag::ext_implicit_function_decl_c99;
17219 else
17220 diag_id = diag::warn_implicit_function_decl;
17221
17222 TypoCorrection Corrected;
17223 // Because typo correction is expensive, only do it if the implicit
17224 // function declaration is going to be treated as an error.
17225 //
17226 // Perform the correction before issuing the main diagnostic, as some
17227 // consumers use typo-correction callbacks to enhance the main diagnostic.
17228 if (S && !ExternCPrev &&
17229 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17231 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17232 S, nullptr, CCC, CorrectTypoKind::NonError);
17233 }
17234
17235 Diag(Loc, diag_id) << &II;
17236 if (Corrected) {
17237 // If the correction is going to suggest an implicitly defined function,
17238 // skip the correction as not being a particularly good idea.
17239 bool Diagnose = true;
17240 if (const auto *D = Corrected.getCorrectionDecl())
17241 Diagnose = !D->isImplicit();
17242 if (Diagnose)
17243 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17244 /*ErrorRecovery*/ false);
17245 }
17246
17247 // If we found a prior declaration of this function, don't bother building
17248 // another one. We've already pushed that one into scope, so there's nothing
17249 // more to do.
17250 if (ExternCPrev)
17251 return ExternCPrev;
17252
17253 // Set a Declarator for the implicit definition: int foo();
17254 const char *Dummy;
17255 AttributeFactory attrFactory;
17256 DeclSpec DS(attrFactory);
17257 unsigned DiagID;
17258 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17259 Context.getPrintingPolicy());
17260 (void)Error; // Silence warning.
17261 assert(!Error && "Error setting up implicit decl!");
17262 SourceLocation NoLoc;
17264 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17265 /*IsAmbiguous=*/false,
17266 /*LParenLoc=*/NoLoc,
17267 /*Params=*/nullptr,
17268 /*NumParams=*/0,
17269 /*EllipsisLoc=*/NoLoc,
17270 /*RParenLoc=*/NoLoc,
17271 /*RefQualifierIsLvalueRef=*/true,
17272 /*RefQualifierLoc=*/NoLoc,
17273 /*MutableLoc=*/NoLoc, EST_None,
17274 /*ESpecRange=*/SourceRange(),
17275 /*Exceptions=*/nullptr,
17276 /*ExceptionRanges=*/nullptr,
17277 /*NumExceptions=*/0,
17278 /*NoexceptExpr=*/nullptr,
17279 /*ExceptionSpecTokens=*/nullptr,
17280 /*DeclsInPrototype=*/{}, Loc, Loc,
17281 D),
17282 std::move(DS.getAttributes()), SourceLocation());
17283 D.SetIdentifier(&II, Loc);
17284
17285 // Insert this function into the enclosing block scope.
17286 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17287 FD->setImplicit();
17288
17290
17291 return FD;
17292}
17293
17295 FunctionDecl *FD) {
17296 if (FD->isInvalidDecl())
17297 return;
17298
17299 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17300 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17301 return;
17302
17303 UnsignedOrNone AlignmentParam = std::nullopt;
17304 bool IsNothrow = false;
17305 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17306 return;
17307
17308 // C++2a [basic.stc.dynamic.allocation]p4:
17309 // An allocation function that has a non-throwing exception specification
17310 // indicates failure by returning a null pointer value. Any other allocation
17311 // function never returns a null pointer value and indicates failure only by
17312 // throwing an exception [...]
17313 //
17314 // However, -fcheck-new invalidates this possible assumption, so don't add
17315 // NonNull when that is enabled.
17316 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17317 !getLangOpts().CheckNew)
17318 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17319
17320 // C++2a [basic.stc.dynamic.allocation]p2:
17321 // An allocation function attempts to allocate the requested amount of
17322 // storage. [...] If the request succeeds, the value returned by a
17323 // replaceable allocation function is a [...] pointer value p0 different
17324 // from any previously returned value p1 [...]
17325 //
17326 // However, this particular information is being added in codegen,
17327 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17328
17329 // C++2a [basic.stc.dynamic.allocation]p2:
17330 // An allocation function attempts to allocate the requested amount of
17331 // storage. If it is successful, it returns the address of the start of a
17332 // block of storage whose length in bytes is at least as large as the
17333 // requested size.
17334 if (!FD->hasAttr<AllocSizeAttr>()) {
17335 FD->addAttr(AllocSizeAttr::CreateImplicit(
17336 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17337 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17338 }
17339
17340 // C++2a [basic.stc.dynamic.allocation]p3:
17341 // For an allocation function [...], the pointer returned on a successful
17342 // call shall represent the address of storage that is aligned as follows:
17343 // (3.1) If the allocation function takes an argument of type
17344 // std​::​align_­val_­t, the storage will have the alignment
17345 // specified by the value of this argument.
17346 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17347 FD->addAttr(AllocAlignAttr::CreateImplicit(
17348 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17349 }
17350
17351 // FIXME:
17352 // C++2a [basic.stc.dynamic.allocation]p3:
17353 // For an allocation function [...], the pointer returned on a successful
17354 // call shall represent the address of storage that is aligned as follows:
17355 // (3.2) Otherwise, if the allocation function is named operator new[],
17356 // the storage is aligned for any object that does not have
17357 // new-extended alignment ([basic.align]) and is no larger than the
17358 // requested size.
17359 // (3.3) Otherwise, the storage is aligned for any object that does not
17360 // have new-extended alignment and is of the requested size.
17361}
17362
17364 if (FD->isInvalidDecl())
17365 return;
17366
17367 // If this is a built-in function, map its builtin attributes to
17368 // actual attributes.
17369 if (unsigned BuiltinID = FD->getBuiltinID()) {
17370 // Handle printf-formatting attributes.
17371 unsigned FormatIdx;
17372 bool HasVAListArg;
17373 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17374 if (!FD->hasAttr<FormatAttr>()) {
17375 const char *fmt = "printf";
17376 unsigned int NumParams = FD->getNumParams();
17377 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17378 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17379 fmt = "NSString";
17380 FD->addAttr(FormatAttr::CreateImplicit(Context,
17381 &Context.Idents.get(fmt),
17382 FormatIdx+1,
17383 HasVAListArg ? 0 : FormatIdx+2,
17384 FD->getLocation()));
17385 }
17386 }
17387 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17388 HasVAListArg)) {
17389 if (!FD->hasAttr<FormatAttr>())
17390 FD->addAttr(FormatAttr::CreateImplicit(Context,
17391 &Context.Idents.get("scanf"),
17392 FormatIdx+1,
17393 HasVAListArg ? 0 : FormatIdx+2,
17394 FD->getLocation()));
17395 }
17396
17397 // Handle automatically recognized callbacks.
17398 SmallVector<int, 4> Encoding;
17399 if (!FD->hasAttr<CallbackAttr>() &&
17400 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17401 FD->addAttr(CallbackAttr::CreateImplicit(
17402 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17403
17404 // Mark const if we don't care about errno and/or floating point exceptions
17405 // that are the only thing preventing the function from being const. This
17406 // allows IRgen to use LLVM intrinsics for such functions.
17407 bool NoExceptions =
17409 bool ConstWithoutErrnoAndExceptions =
17410 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17411 bool ConstWithoutExceptions =
17412 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17413 if (!FD->hasAttr<ConstAttr>() &&
17414 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17415 (!ConstWithoutErrnoAndExceptions ||
17416 (!getLangOpts().MathErrno && NoExceptions)) &&
17417 (!ConstWithoutExceptions || NoExceptions))
17418 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17419
17420 // We make "fma" on GNU or Windows const because we know it does not set
17421 // errno in those environments even though it could set errno based on the
17422 // C standard.
17423 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17424 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17425 !FD->hasAttr<ConstAttr>()) {
17426 switch (BuiltinID) {
17427 case Builtin::BI__builtin_fma:
17428 case Builtin::BI__builtin_fmaf:
17429 case Builtin::BI__builtin_fmal:
17430 case Builtin::BIfma:
17431 case Builtin::BIfmaf:
17432 case Builtin::BIfmal:
17433 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17434 break;
17435 default:
17436 break;
17437 }
17438 }
17439
17440 SmallVector<int, 4> Indxs;
17442 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17443 !FD->hasAttr<NonNullAttr>()) {
17445 for (int I : Indxs) {
17446 ParmVarDecl *PVD = FD->getParamDecl(I);
17447 QualType T = PVD->getType();
17448 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17449 PVD->setType(T);
17450 }
17451 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17453 for (int I : Indxs)
17454 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17455 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17456 ParamIndxs.size()));
17457 }
17458 }
17459 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17460 !FD->hasAttr<ReturnsTwiceAttr>())
17461 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17462 FD->getLocation()));
17463 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17464 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17465 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17466 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17467 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17468 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17469 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17470 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17471 // Add the appropriate attribute, depending on the CUDA compilation mode
17472 // and which target the builtin belongs to. For example, during host
17473 // compilation, aux builtins are __device__, while the rest are __host__.
17474 if (getLangOpts().CUDAIsDevice !=
17475 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17476 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17477 else
17478 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17479 }
17480
17481 // Add known guaranteed alignment for allocation functions.
17482 switch (BuiltinID) {
17483 case Builtin::BImemalign:
17484 case Builtin::BIaligned_alloc:
17485 if (!FD->hasAttr<AllocAlignAttr>())
17486 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17487 FD->getLocation()));
17488 break;
17489 default:
17490 break;
17491 }
17492
17493 // Add allocsize attribute for allocation functions.
17494 switch (BuiltinID) {
17495 case Builtin::BIcalloc:
17496 FD->addAttr(AllocSizeAttr::CreateImplicit(
17497 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17498 break;
17499 case Builtin::BImemalign:
17500 case Builtin::BIaligned_alloc:
17501 case Builtin::BIrealloc:
17502 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17503 ParamIdx(), FD->getLocation()));
17504 break;
17505 case Builtin::BImalloc:
17506 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17507 ParamIdx(), FD->getLocation()));
17508 break;
17509 default:
17510 break;
17511 }
17512 }
17513
17518
17519 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17520 // throw, add an implicit nothrow attribute to any extern "C" function we come
17521 // across.
17522 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17523 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17524 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17525 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17526 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17527 }
17528
17529 IdentifierInfo *Name = FD->getIdentifier();
17530 if (!Name)
17531 return;
17534 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17536 // Okay: this could be a libc/libm/Objective-C function we know
17537 // about.
17538 } else
17539 return;
17540
17541 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17542 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17543 // target-specific builtins, perhaps?
17544 if (!FD->hasAttr<FormatAttr>())
17545 FD->addAttr(FormatAttr::CreateImplicit(Context,
17546 &Context.Idents.get("printf"), 2,
17547 Name->isStr("vasprintf") ? 0 : 3,
17548 FD->getLocation()));
17549 }
17550
17551 if (Name->isStr("__CFStringMakeConstantString")) {
17552 // We already have a __builtin___CFStringMakeConstantString,
17553 // but builds that use -fno-constant-cfstrings don't go through that.
17554 if (!FD->hasAttr<FormatArgAttr>())
17555 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17556 FD->getLocation()));
17557 }
17558}
17559
17561 TypeSourceInfo *TInfo) {
17562 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17563 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17564
17565 if (!TInfo) {
17566 assert(D.isInvalidType() && "no declarator info for valid type");
17567 TInfo = Context.getTrivialTypeSourceInfo(T);
17568 }
17569
17570 // Scope manipulation handled by caller.
17571 TypedefDecl *NewTD =
17573 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17574
17575 // Bail out immediately if we have an invalid declaration.
17576 if (D.isInvalidType()) {
17577 NewTD->setInvalidDecl();
17578 return NewTD;
17579 }
17580
17582 if (CurContext->isFunctionOrMethod())
17583 Diag(NewTD->getLocation(), diag::err_module_private_local)
17584 << 2 << NewTD
17588 else
17589 NewTD->setModulePrivate();
17590 }
17591
17592 // C++ [dcl.typedef]p8:
17593 // If the typedef declaration defines an unnamed class (or
17594 // enum), the first typedef-name declared by the declaration
17595 // to be that class type (or enum type) is used to denote the
17596 // class type (or enum type) for linkage purposes only.
17597 // We need to check whether the type was declared in the declaration.
17598 switch (D.getDeclSpec().getTypeSpecType()) {
17599 case TST_enum:
17600 case TST_struct:
17601 case TST_interface:
17602 case TST_union:
17603 case TST_class: {
17604 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17605 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17606 break;
17607 }
17608
17609 default:
17610 break;
17611 }
17612
17613 return NewTD;
17614}
17615
17617 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17618 QualType T = TI->getType();
17619
17620 if (T->isDependentType())
17621 return false;
17622
17623 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17624 // integral type; any cv-qualification is ignored.
17625 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17626 // non-atomic version of the type specified by the type specifiers in the
17627 // specifier qualifier list.
17628 // Because of how odd C's rule is, we'll let the user know that operations
17629 // involving the enumeration type will be non-atomic.
17630 if (T->isAtomicType())
17631 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17632
17633 Qualifiers Q = T.getQualifiers();
17634 std::optional<unsigned> QualSelect;
17635 if (Q.hasConst() && Q.hasVolatile())
17636 QualSelect = diag::CVQualList::Both;
17637 else if (Q.hasConst())
17638 QualSelect = diag::CVQualList::Const;
17639 else if (Q.hasVolatile())
17640 QualSelect = diag::CVQualList::Volatile;
17641
17642 if (QualSelect)
17643 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17644
17645 T = T.getAtomicUnqualifiedType();
17646
17647 // This doesn't use 'isIntegralType' despite the error message mentioning
17648 // integral type because isIntegralType would also allow enum types in C.
17649 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17650 if (BT->isInteger())
17651 return false;
17652
17653 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17654 << T << T->isBitIntType();
17655}
17656
17658 QualType EnumUnderlyingTy, bool IsFixed,
17659 const EnumDecl *Prev) {
17660 if (IsScoped != Prev->isScoped()) {
17661 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17662 << Prev->isScoped();
17663 Diag(Prev->getLocation(), diag::note_previous_declaration);
17664 return true;
17665 }
17666
17667 if (IsFixed && Prev->isFixed()) {
17668 if (!EnumUnderlyingTy->isDependentType() &&
17669 !Prev->getIntegerType()->isDependentType() &&
17670 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17671 Prev->getIntegerType())) {
17672 // TODO: Highlight the underlying type of the redeclaration.
17673 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17674 << EnumUnderlyingTy << Prev->getIntegerType();
17675 Diag(Prev->getLocation(), diag::note_previous_declaration)
17676 << Prev->getIntegerTypeRange();
17677 return true;
17678 }
17679 } else if (IsFixed != Prev->isFixed()) {
17680 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17681 << Prev->isFixed();
17682 Diag(Prev->getLocation(), diag::note_previous_declaration);
17683 return true;
17684 }
17685
17686 return false;
17687}
17688
17689/// Get diagnostic %select index for tag kind for
17690/// redeclaration diagnostic message.
17691/// WARNING: Indexes apply to particular diagnostics only!
17692///
17693/// \returns diagnostic %select index.
17695 switch (Tag) {
17697 return 0;
17699 return 1;
17700 case TagTypeKind::Class:
17701 return 2;
17702 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17703 }
17704}
17705
17706/// Determine if tag kind is a class-key compatible with
17707/// class for redeclaration (class, struct, or __interface).
17708///
17709/// \returns true iff the tag kind is compatible.
17711{
17712 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17714}
17715
17717 if (isa<TypedefDecl>(PrevDecl))
17718 return NonTagKind::Typedef;
17719 else if (isa<TypeAliasDecl>(PrevDecl))
17720 return NonTagKind::TypeAlias;
17721 else if (isa<ClassTemplateDecl>(PrevDecl))
17722 return NonTagKind::Template;
17723 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17725 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17727 switch (TTK) {
17730 case TagTypeKind::Class:
17731 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17733 case TagTypeKind::Union:
17734 return NonTagKind::NonUnion;
17735 case TagTypeKind::Enum:
17736 return NonTagKind::NonEnum;
17737 }
17738 llvm_unreachable("invalid TTK");
17739}
17740
17742 TagTypeKind NewTag, bool isDefinition,
17743 SourceLocation NewTagLoc,
17744 const IdentifierInfo *Name) {
17745 // C++ [dcl.type.elab]p3:
17746 // The class-key or enum keyword present in the
17747 // elaborated-type-specifier shall agree in kind with the
17748 // declaration to which the name in the elaborated-type-specifier
17749 // refers. This rule also applies to the form of
17750 // elaborated-type-specifier that declares a class-name or
17751 // friend class since it can be construed as referring to the
17752 // definition of the class. Thus, in any
17753 // elaborated-type-specifier, the enum keyword shall be used to
17754 // refer to an enumeration (7.2), the union class-key shall be
17755 // used to refer to a union (clause 9), and either the class or
17756 // struct class-key shall be used to refer to a class (clause 9)
17757 // declared using the class or struct class-key.
17758 TagTypeKind OldTag = Previous->getTagKind();
17759 if (OldTag != NewTag &&
17761 return false;
17762
17763 // Tags are compatible, but we might still want to warn on mismatched tags.
17764 // Non-class tags can't be mismatched at this point.
17766 return true;
17767
17768 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17769 // by our warning analysis. We don't want to warn about mismatches with (eg)
17770 // declarations in system headers that are designed to be specialized, but if
17771 // a user asks us to warn, we should warn if their code contains mismatched
17772 // declarations.
17773 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17774 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17775 Loc);
17776 };
17777 if (IsIgnoredLoc(NewTagLoc))
17778 return true;
17779
17780 auto IsIgnored = [&](const TagDecl *Tag) {
17781 return IsIgnoredLoc(Tag->getLocation());
17782 };
17783 while (IsIgnored(Previous)) {
17784 Previous = Previous->getPreviousDecl();
17785 if (!Previous)
17786 return true;
17787 OldTag = Previous->getTagKind();
17788 }
17789
17790 bool isTemplate = false;
17791 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17792 isTemplate = Record->getDescribedClassTemplate();
17793
17795 if (OldTag != NewTag) {
17796 // In a template instantiation, do not offer fix-its for tag mismatches
17797 // since they usually mess up the template instead of fixing the problem.
17798 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17800 << getRedeclDiagFromTagKind(OldTag);
17801 // FIXME: Note previous location?
17802 }
17803 return true;
17804 }
17805
17806 if (isDefinition) {
17807 // On definitions, check all previous tags and issue a fix-it for each
17808 // one that doesn't match the current tag.
17809 if (Previous->getDefinition()) {
17810 // Don't suggest fix-its for redefinitions.
17811 return true;
17812 }
17813
17814 bool previousMismatch = false;
17815 for (const TagDecl *I : Previous->redecls()) {
17816 if (I->getTagKind() != NewTag) {
17817 // Ignore previous declarations for which the warning was disabled.
17818 if (IsIgnored(I))
17819 continue;
17820
17821 if (!previousMismatch) {
17822 previousMismatch = true;
17823 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17825 << getRedeclDiagFromTagKind(I->getTagKind());
17826 }
17827 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17829 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17831 }
17832 }
17833 return true;
17834 }
17835
17836 // Identify the prevailing tag kind: this is the kind of the definition (if
17837 // there is a non-ignored definition), or otherwise the kind of the prior
17838 // (non-ignored) declaration.
17839 const TagDecl *PrevDef = Previous->getDefinition();
17840 if (PrevDef && IsIgnored(PrevDef))
17841 PrevDef = nullptr;
17842 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17843 if (Redecl->getTagKind() != NewTag) {
17844 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17846 << getRedeclDiagFromTagKind(OldTag);
17847 Diag(Redecl->getLocation(), diag::note_previous_use);
17848
17849 // If there is a previous definition, suggest a fix-it.
17850 if (PrevDef) {
17851 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17855 }
17856 }
17857
17858 return true;
17859}
17860
17861/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17862/// from an outer enclosing namespace or file scope inside a friend declaration.
17863/// This should provide the commented out code in the following snippet:
17864/// namespace N {
17865/// struct X;
17866/// namespace M {
17867/// struct Y { friend struct /*N::*/ X; };
17868/// }
17869/// }
17871 SourceLocation NameLoc) {
17872 // While the decl is in a namespace, do repeated lookup of that name and see
17873 // if we get the same namespace back. If we do not, continue until
17874 // translation unit scope, at which point we have a fully qualified NNS.
17877 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17878 // This tag should be declared in a namespace, which can only be enclosed by
17879 // other namespaces. Bail if there's an anonymous namespace in the chain.
17880 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17881 if (!Namespace || Namespace->isAnonymousNamespace())
17882 return FixItHint();
17883 IdentifierInfo *II = Namespace->getIdentifier();
17884 Namespaces.push_back(II);
17885 NamedDecl *Lookup = SemaRef.LookupSingleName(
17886 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17887 if (Lookup == Namespace)
17888 break;
17889 }
17890
17891 // Once we have all the namespaces, reverse them to go outermost first, and
17892 // build an NNS.
17893 SmallString<64> Insertion;
17894 llvm::raw_svector_ostream OS(Insertion);
17895 if (DC->isTranslationUnit())
17896 OS << "::";
17897 std::reverse(Namespaces.begin(), Namespaces.end());
17898 for (auto *II : Namespaces)
17899 OS << II->getName() << "::";
17900 return FixItHint::CreateInsertion(NameLoc, Insertion);
17901}
17902
17903/// Determine whether a tag originally declared in context \p OldDC can
17904/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17905/// found a declaration in \p OldDC as a previous decl, perhaps through a
17906/// using-declaration).
17908 DeclContext *NewDC) {
17909 OldDC = OldDC->getRedeclContext();
17910 NewDC = NewDC->getRedeclContext();
17911
17912 if (OldDC->Equals(NewDC))
17913 return true;
17914
17915 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17916 // encloses the other).
17917 if (S.getLangOpts().MSVCCompat &&
17918 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17919 return true;
17920
17921 return false;
17922}
17923
17925Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17926 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17927 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17928 SourceLocation ModulePrivateLoc,
17929 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17930 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17931 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17932 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17933 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17934 // If this is not a definition, it must have a name.
17935 IdentifierInfo *OrigName = Name;
17936 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17937 "Nameless record must be a definition!");
17938 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17939
17940 OwnedDecl = false;
17942 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17943
17944 // FIXME: Check member specializations more carefully.
17945 bool isMemberSpecialization = false;
17946 bool IsInjectedClassName = false;
17947 bool Invalid = false;
17948
17949 // We only need to do this matching if we have template parameters
17950 // or a scope specifier, which also conveniently avoids this work
17951 // for non-C++ cases.
17952 if (TemplateParameterLists.size() > 0 ||
17953 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17954 TemplateParameterList *TemplateParams =
17956 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17957 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17958
17959 // C++23 [dcl.type.elab] p2:
17960 // If an elaborated-type-specifier is the sole constituent of a
17961 // declaration, the declaration is ill-formed unless it is an explicit
17962 // specialization, an explicit instantiation or it has one of the
17963 // following forms: [...]
17964 // C++23 [dcl.enum] p1:
17965 // If the enum-head-name of an opaque-enum-declaration contains a
17966 // nested-name-specifier, the declaration shall be an explicit
17967 // specialization.
17968 //
17969 // FIXME: Class template partial specializations can be forward declared
17970 // per CWG2213, but the resolution failed to allow qualified forward
17971 // declarations. This is almost certainly unintentional, so we allow them.
17972 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17973 !isMemberSpecialization)
17974 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17976
17977 if (TemplateParams) {
17978 if (Kind == TagTypeKind::Enum) {
17979 Diag(KWLoc, diag::err_enum_template);
17980 return true;
17981 }
17982
17983 if (TemplateParams->size() > 0) {
17984 // This is a declaration or definition of a class template (which may
17985 // be a member of another template).
17986
17987 if (Invalid)
17988 return true;
17989
17990 OwnedDecl = false;
17992 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17993 AS, ModulePrivateLoc,
17994 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17995 TemplateParameterLists.data(), SkipBody);
17996 return Result.get();
17997 } else {
17998 // The "template<>" header is extraneous.
17999 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18000 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18001 isMemberSpecialization = true;
18002 }
18003 }
18004
18005 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18006 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
18007 return true;
18008 }
18009
18010 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18011 // C++23 [dcl.type.elab]p4:
18012 // If an elaborated-type-specifier appears with the friend specifier as
18013 // an entire member-declaration, the member-declaration shall have one
18014 // of the following forms:
18015 // friend class-key nested-name-specifier(opt) identifier ;
18016 // friend class-key simple-template-id ;
18017 // friend class-key nested-name-specifier template(opt)
18018 // simple-template-id ;
18019 //
18020 // Since enum is not a class-key, so declarations like "friend enum E;"
18021 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18022 // invalid, most implementations accept so we issue a pedantic warning.
18023 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
18024 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18025 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18026 Diag(KWLoc, diag::note_enum_friend)
18027 << (ScopedEnum + ScopedEnumUsesClassTag);
18028 }
18029
18030 // Figure out the underlying type if this a enum declaration. We need to do
18031 // this early, because it's needed to detect if this is an incompatible
18032 // redeclaration.
18033 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18034 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18035
18036 if (Kind == TagTypeKind::Enum) {
18037 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18038 Invalid) {
18039 // No underlying type explicitly specified, or we failed to parse the
18040 // type, default to int.
18041 EnumUnderlying = Context.IntTy.getTypePtr();
18042 } else if (UnderlyingType.get()) {
18043 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18044 // integral type; any cv-qualification is ignored.
18045 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18046 // unqualified, non-atomic version of the type specified by the type
18047 // specifiers in the specifier qualifier list.
18048 TypeSourceInfo *TI = nullptr;
18049 GetTypeFromParser(UnderlyingType.get(), &TI);
18050 EnumUnderlying = TI;
18051
18053 // Recover by falling back to int.
18054 EnumUnderlying = Context.IntTy.getTypePtr();
18055
18058 EnumUnderlying = Context.IntTy.getTypePtr();
18059
18060 // If the underlying type is atomic, we need to adjust the type before
18061 // continuing. This only happens in the case we stored a TypeSourceInfo
18062 // into EnumUnderlying because the other cases are error recovery up to
18063 // this point. But because it's not possible to gin up a TypeSourceInfo
18064 // for a non-atomic type from an atomic one, we'll store into the Type
18065 // field instead. FIXME: it would be nice to have an easy way to get a
18066 // derived TypeSourceInfo which strips qualifiers including the weird
18067 // ones like _Atomic where it forms a different type.
18068 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
18069 TI && TI->getType()->isAtomicType())
18070 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18071
18072 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18073 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18074 // of 'int'. However, if this is an unfixed forward declaration, don't set
18075 // the underlying type unless the user enables -fms-compatibility. This
18076 // makes unfixed forward declared enums incomplete and is more conforming.
18077 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18078 EnumUnderlying = Context.IntTy.getTypePtr();
18079 }
18080 }
18081
18082 DeclContext *SearchDC = CurContext;
18083 DeclContext *DC = CurContext;
18084 bool isStdBadAlloc = false;
18085 bool isStdAlignValT = false;
18086
18088 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18090
18091 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18092 /// implemented asks for structural equivalence checking, the returned decl
18093 /// here is passed back to the parser, allowing the tag body to be parsed.
18094 auto createTagFromNewDecl = [&]() -> TagDecl * {
18095 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18096 // If there is an identifier, use the location of the identifier as the
18097 // location of the decl, otherwise use the location of the struct/union
18098 // keyword.
18099 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18100 TagDecl *New = nullptr;
18101
18102 if (Kind == TagTypeKind::Enum) {
18103 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
18104 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
18105 // If this is an undefined enum, bail.
18106 if (TUK != TagUseKind::Definition && !Invalid)
18107 return nullptr;
18108 if (EnumUnderlying) {
18110 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18112 else
18113 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18114 QualType EnumTy = ED->getIntegerType();
18115 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18116 ? Context.getPromotedIntegerType(EnumTy)
18117 : EnumTy);
18118 }
18119 } else { // struct/union
18120 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18121 nullptr);
18122 }
18123
18124 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18125 // Add alignment attributes if necessary; these attributes are checked
18126 // when the ASTContext lays out the structure.
18127 //
18128 // It is important for implementing the correct semantics that this
18129 // happen here (in ActOnTag). The #pragma pack stack is
18130 // maintained as a result of parser callbacks which can occur at
18131 // many points during the parsing of a struct declaration (because
18132 // the #pragma tokens are effectively skipped over during the
18133 // parsing of the struct).
18134 if (TUK == TagUseKind::Definition &&
18135 (!SkipBody || !SkipBody->ShouldSkip)) {
18136 if (LangOpts.HLSL)
18137 RD->addAttr(PackedAttr::CreateImplicit(Context));
18140 }
18141 }
18142 New->setLexicalDeclContext(CurContext);
18143 return New;
18144 };
18145
18146 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18147 if (Name && SS.isNotEmpty()) {
18148 // We have a nested-name tag ('struct foo::bar').
18149
18150 // Check for invalid 'foo::'.
18151 if (SS.isInvalid()) {
18152 Name = nullptr;
18153 goto CreateNewDecl;
18154 }
18155
18156 // If this is a friend or a reference to a class in a dependent
18157 // context, don't try to make a decl for it.
18158 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18159 DC = computeDeclContext(SS, false);
18160 if (!DC) {
18161 IsDependent = true;
18162 return true;
18163 }
18164 } else {
18165 DC = computeDeclContext(SS, true);
18166 if (!DC) {
18167 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
18168 << SS.getRange();
18169 return true;
18170 }
18171 }
18172
18173 if (RequireCompleteDeclContext(SS, DC))
18174 return true;
18175
18176 SearchDC = DC;
18177 // Look-up name inside 'foo::'.
18179
18180 if (Previous.isAmbiguous())
18181 return true;
18182
18183 if (Previous.empty()) {
18184 // Name lookup did not find anything. However, if the
18185 // nested-name-specifier refers to the current instantiation,
18186 // and that current instantiation has any dependent base
18187 // classes, we might find something at instantiation time: treat
18188 // this as a dependent elaborated-type-specifier.
18189 // But this only makes any sense for reference-like lookups.
18190 if (Previous.wasNotFoundInCurrentInstantiation() &&
18191 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18192 IsDependent = true;
18193 return true;
18194 }
18195
18196 // A tag 'foo::bar' must already exist.
18197 Diag(NameLoc, diag::err_not_tag_in_scope)
18198 << Kind << Name << DC << SS.getRange();
18199 Name = nullptr;
18200 Invalid = true;
18201 goto CreateNewDecl;
18202 }
18203 } else if (Name) {
18204 // C++14 [class.mem]p14:
18205 // If T is the name of a class, then each of the following shall have a
18206 // name different from T:
18207 // -- every member of class T that is itself a type
18208 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18209 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
18210 return true;
18211
18212 // If this is a named struct, check to see if there was a previous forward
18213 // declaration or definition.
18214 // FIXME: We're looking into outer scopes here, even when we
18215 // shouldn't be. Doing so can result in ambiguities that we
18216 // shouldn't be diagnosing.
18217 LookupName(Previous, S);
18218
18219 // When declaring or defining a tag, ignore ambiguities introduced
18220 // by types using'ed into this scope.
18221 if (Previous.isAmbiguous() &&
18223 LookupResult::Filter F = Previous.makeFilter();
18224 while (F.hasNext()) {
18225 NamedDecl *ND = F.next();
18226 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18227 SearchDC->getRedeclContext()))
18228 F.erase();
18229 }
18230 F.done();
18231 }
18232
18233 // C++11 [namespace.memdef]p3:
18234 // If the name in a friend declaration is neither qualified nor
18235 // a template-id and the declaration is a function or an
18236 // elaborated-type-specifier, the lookup to determine whether
18237 // the entity has been previously declared shall not consider
18238 // any scopes outside the innermost enclosing namespace.
18239 //
18240 // MSVC doesn't implement the above rule for types, so a friend tag
18241 // declaration may be a redeclaration of a type declared in an enclosing
18242 // scope. They do implement this rule for friend functions.
18243 //
18244 // Does it matter that this should be by scope instead of by
18245 // semantic context?
18246 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18247 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18248 LookupResult::Filter F = Previous.makeFilter();
18249 bool FriendSawTagOutsideEnclosingNamespace = false;
18250 while (F.hasNext()) {
18251 NamedDecl *ND = F.next();
18253 if (DC->isFileContext() &&
18254 !EnclosingNS->Encloses(ND->getDeclContext())) {
18255 if (getLangOpts().MSVCCompat)
18256 FriendSawTagOutsideEnclosingNamespace = true;
18257 else
18258 F.erase();
18259 }
18260 }
18261 F.done();
18262
18263 // Diagnose this MSVC extension in the easy case where lookup would have
18264 // unambiguously found something outside the enclosing namespace.
18265 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18266 NamedDecl *ND = Previous.getFoundDecl();
18267 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18268 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18269 }
18270 }
18271
18272 // Note: there used to be some attempt at recovery here.
18273 if (Previous.isAmbiguous())
18274 return true;
18275
18276 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18277 // FIXME: This makes sure that we ignore the contexts associated
18278 // with C structs, unions, and enums when looking for a matching
18279 // tag declaration or definition. See the similar lookup tweak
18280 // in Sema::LookupName; is there a better way to deal with this?
18282 SearchDC = SearchDC->getParent();
18283 } else if (getLangOpts().CPlusPlus) {
18284 // Inside ObjCContainer want to keep it as a lexical decl context but go
18285 // past it (most often to TranslationUnit) to find the semantic decl
18286 // context.
18287 while (isa<ObjCContainerDecl>(SearchDC))
18288 SearchDC = SearchDC->getParent();
18289 }
18290 } else if (getLangOpts().CPlusPlus) {
18291 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18292 // TagDecl the same way as we skip it for named TagDecl.
18293 while (isa<ObjCContainerDecl>(SearchDC))
18294 SearchDC = SearchDC->getParent();
18295 }
18296
18297 if (Previous.isSingleResult() &&
18298 Previous.getFoundDecl()->isTemplateParameter()) {
18299 // Maybe we will complain about the shadowed template parameter.
18300 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18301 // Just pretend that we didn't see the previous declaration.
18302 Previous.clear();
18303 }
18304
18305 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18306 DC->Equals(getStdNamespace())) {
18307 if (Name->isStr("bad_alloc")) {
18308 // This is a declaration of or a reference to "std::bad_alloc".
18309 isStdBadAlloc = true;
18310
18311 // If std::bad_alloc has been implicitly declared (but made invisible to
18312 // name lookup), fill in this implicit declaration as the previous
18313 // declaration, so that the declarations get chained appropriately.
18314 if (Previous.empty() && StdBadAlloc)
18315 Previous.addDecl(getStdBadAlloc());
18316 } else if (Name->isStr("align_val_t")) {
18317 isStdAlignValT = true;
18318 if (Previous.empty() && StdAlignValT)
18319 Previous.addDecl(getStdAlignValT());
18320 }
18321 }
18322
18323 // If we didn't find a previous declaration, and this is a reference
18324 // (or friend reference), move to the correct scope. In C++, we
18325 // also need to do a redeclaration lookup there, just in case
18326 // there's a shadow friend decl.
18327 if (Name && Previous.empty() &&
18328 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18329 IsTemplateParamOrArg)) {
18330 if (Invalid) goto CreateNewDecl;
18331 assert(SS.isEmpty());
18332
18333 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18334 // C++ [basic.scope.pdecl]p5:
18335 // -- for an elaborated-type-specifier of the form
18336 //
18337 // class-key identifier
18338 //
18339 // if the elaborated-type-specifier is used in the
18340 // decl-specifier-seq or parameter-declaration-clause of a
18341 // function defined in namespace scope, the identifier is
18342 // declared as a class-name in the namespace that contains
18343 // the declaration; otherwise, except as a friend
18344 // declaration, the identifier is declared in the smallest
18345 // non-class, non-function-prototype scope that contains the
18346 // declaration.
18347 //
18348 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18349 // C structs and unions.
18350 //
18351 // It is an error in C++ to declare (rather than define) an enum
18352 // type, including via an elaborated type specifier. We'll
18353 // diagnose that later; for now, declare the enum in the same
18354 // scope as we would have picked for any other tag type.
18355 //
18356 // GNU C also supports this behavior as part of its incomplete
18357 // enum types extension, while GNU C++ does not.
18358 //
18359 // Find the context where we'll be declaring the tag.
18360 // FIXME: We would like to maintain the current DeclContext as the
18361 // lexical context,
18362 SearchDC = getTagInjectionContext(SearchDC);
18363
18364 // Find the scope where we'll be declaring the tag.
18366 } else {
18367 assert(TUK == TagUseKind::Friend);
18368 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18369
18370 // C++ [namespace.memdef]p3:
18371 // If a friend declaration in a non-local class first declares a
18372 // class or function, the friend class or function is a member of
18373 // the innermost enclosing namespace.
18374 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18375 : SearchDC->getEnclosingNamespaceContext();
18376 }
18377
18378 // In C++, we need to do a redeclaration lookup to properly
18379 // diagnose some problems.
18380 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18381 // hidden declaration so that we don't get ambiguity errors when using a
18382 // type declared by an elaborated-type-specifier. In C that is not correct
18383 // and we should instead merge compatible types found by lookup.
18384 if (getLangOpts().CPlusPlus) {
18385 // FIXME: This can perform qualified lookups into function contexts,
18386 // which are meaningless.
18387 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18388 LookupQualifiedName(Previous, SearchDC);
18389 } else {
18390 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18391 LookupName(Previous, S);
18392 }
18393 }
18394
18395 // If we have a known previous declaration to use, then use it.
18396 if (Previous.empty() && SkipBody && SkipBody->Previous)
18397 Previous.addDecl(SkipBody->Previous);
18398
18399 if (!Previous.empty()) {
18400 NamedDecl *PrevDecl = Previous.getFoundDecl();
18401 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18402
18403 // It's okay to have a tag decl in the same scope as a typedef
18404 // which hides a tag decl in the same scope. Finding this
18405 // with a redeclaration lookup can only actually happen in C++.
18406 //
18407 // This is also okay for elaborated-type-specifiers, which is
18408 // technically forbidden by the current standard but which is
18409 // okay according to the likely resolution of an open issue;
18410 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18411 if (getLangOpts().CPlusPlus) {
18412 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18413 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18414 if (Tag->getDeclName() == Name &&
18415 Tag->getDeclContext()->getRedeclContext()
18416 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18417 PrevDecl = Tag;
18418 Previous.clear();
18419 Previous.addDecl(Tag);
18420 Previous.resolveKind();
18421 }
18422 }
18423 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18424 TUK == TagUseKind::Reference && RD &&
18425 RD->isInjectedClassName()) {
18426 // If lookup found the injected class name, the previous declaration is
18427 // the class being injected into.
18428 PrevDecl = cast<TagDecl>(RD->getDeclContext());
18429 Previous.clear();
18430 Previous.addDecl(PrevDecl);
18431 Previous.resolveKind();
18432 IsInjectedClassName = true;
18433 }
18434 }
18435
18436 // If this is a redeclaration of a using shadow declaration, it must
18437 // declare a tag in the same context. In MSVC mode, we allow a
18438 // redefinition if either context is within the other.
18439 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18440 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18441 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18442 TUK != TagUseKind::Friend &&
18443 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18444 !(OldTag && isAcceptableTagRedeclContext(
18445 *this, OldTag->getDeclContext(), SearchDC))) {
18446 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18447 Diag(Shadow->getTargetDecl()->getLocation(),
18448 diag::note_using_decl_target);
18449 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18450 << 0;
18451 // Recover by ignoring the old declaration.
18452 Previous.clear();
18453 goto CreateNewDecl;
18454 }
18455 }
18456
18457 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18458 // If this is a use of a previous tag, or if the tag is already declared
18459 // in the same scope (so that the definition/declaration completes or
18460 // rementions the tag), reuse the decl.
18461 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18462 isDeclInScope(DirectPrevDecl, SearchDC, S,
18463 SS.isNotEmpty() || isMemberSpecialization)) {
18464 // Make sure that this wasn't declared as an enum and now used as a
18465 // struct or something similar.
18466 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18467 TUK == TagUseKind::Definition, KWLoc,
18468 Name)) {
18469 bool SafeToContinue =
18470 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18471 Kind != TagTypeKind::Enum);
18472 if (SafeToContinue)
18473 Diag(KWLoc, diag::err_use_with_wrong_tag)
18474 << Name
18476 PrevTagDecl->getKindName());
18477 else
18478 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18479 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18480
18481 if (SafeToContinue)
18482 Kind = PrevTagDecl->getTagKind();
18483 else {
18484 // Recover by making this an anonymous redefinition.
18485 Name = nullptr;
18486 Previous.clear();
18487 Invalid = true;
18488 }
18489 }
18490
18491 if (Kind == TagTypeKind::Enum &&
18492 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18493 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18494 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18495 return PrevTagDecl;
18496
18497 QualType EnumUnderlyingTy;
18498 if (TypeSourceInfo *TI =
18499 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18500 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18501 else if (const Type *T =
18502 dyn_cast_if_present<const Type *>(EnumUnderlying))
18503 EnumUnderlyingTy = QualType(T, 0);
18504
18505 // All conflicts with previous declarations are recovered by
18506 // returning the previous declaration, unless this is a definition,
18507 // in which case we want the caller to bail out.
18508 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18509 ScopedEnum, EnumUnderlyingTy,
18510 IsFixed, PrevEnum))
18511 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18512 }
18513
18514 // C++11 [class.mem]p1:
18515 // A member shall not be declared twice in the member-specification,
18516 // except that a nested class or member class template can be declared
18517 // and then later defined.
18518 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18519 S->isDeclScope(PrevDecl)) {
18520 Diag(NameLoc, diag::ext_member_redeclared);
18521 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18522 }
18523
18524 if (!Invalid) {
18525 // If this is a use, just return the declaration we found, unless
18526 // we have attributes.
18527 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18528 if (!Attrs.empty()) {
18529 // FIXME: Diagnose these attributes. For now, we create a new
18530 // declaration to hold them.
18531 } else if (TUK == TagUseKind::Reference &&
18532 (PrevTagDecl->getFriendObjectKind() ==
18534 PrevDecl->getOwningModule() != getCurrentModule()) &&
18535 SS.isEmpty()) {
18536 // This declaration is a reference to an existing entity, but
18537 // has different visibility from that entity: it either makes
18538 // a friend visible or it makes a type visible in a new module.
18539 // In either case, create a new declaration. We only do this if
18540 // the declaration would have meant the same thing if no prior
18541 // declaration were found, that is, if it was found in the same
18542 // scope where we would have injected a declaration.
18543 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18544 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18545 return PrevTagDecl;
18546 // This is in the injected scope, create a new declaration in
18547 // that scope.
18549 } else {
18550 return PrevTagDecl;
18551 }
18552 }
18553
18554 // Diagnose attempts to redefine a tag.
18555 if (TUK == TagUseKind::Definition) {
18556 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18557 // If the type is currently being defined, complain
18558 // about a nested redefinition.
18559 if (Def->isBeingDefined()) {
18560 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18561 Diag(PrevTagDecl->getLocation(),
18562 diag::note_previous_definition);
18563 Name = nullptr;
18564 Previous.clear();
18565 Invalid = true;
18566 } else {
18567 // If we're defining a specialization and the previous
18568 // definition is from an implicit instantiation, don't emit an
18569 // error here; we'll catch this in the general case below.
18570 bool IsExplicitSpecializationAfterInstantiation = false;
18571 if (isMemberSpecialization) {
18572 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18573 IsExplicitSpecializationAfterInstantiation =
18574 RD->getTemplateSpecializationKind() !=
18576 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18577 IsExplicitSpecializationAfterInstantiation =
18578 ED->getTemplateSpecializationKind() !=
18580 }
18581
18582 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18583 // do not keep more that one definition around (merge them).
18584 // However, ensure the decl passes the structural compatibility
18585 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18586 NamedDecl *Hidden = nullptr;
18587 bool HiddenDefVisible = false;
18588 if (SkipBody &&
18589 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18590 getLangOpts().C23)) {
18591 // There is a definition of this tag, but it is not visible.
18592 // We explicitly make use of C++'s one definition rule here,
18593 // and assume that this definition is identical to the hidden
18594 // one we already have. Make the existing definition visible
18595 // and use it in place of this one.
18596 if (!getLangOpts().CPlusPlus) {
18597 // Postpone making the old definition visible until after we
18598 // complete parsing the new one and do the structural
18599 // comparison.
18600 SkipBody->CheckSameAsPrevious = true;
18601 SkipBody->New = createTagFromNewDecl();
18602 SkipBody->Previous = Def;
18603
18604 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18605 return Def;
18606 }
18607
18608 SkipBody->ShouldSkip = true;
18609 SkipBody->Previous = Def;
18610 if (!HiddenDefVisible && Hidden)
18612 // Carry on and handle it like a normal definition. We'll
18613 // skip starting the definition later.
18614
18615 } else if (!IsExplicitSpecializationAfterInstantiation) {
18616 // A redeclaration in function prototype scope in C isn't
18617 // visible elsewhere, so merely issue a warning.
18618 if (!getLangOpts().CPlusPlus &&
18620 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18621 << Name;
18622 else
18623 Diag(NameLoc, diag::err_redefinition) << Name;
18625 NameLoc.isValid() ? NameLoc : KWLoc);
18626 // If this is a redefinition, recover by making this
18627 // struct be anonymous, which will make any later
18628 // references get the previous definition.
18629 Name = nullptr;
18630 Previous.clear();
18631 Invalid = true;
18632 }
18633 }
18634 }
18635
18636 // Okay, this is definition of a previously declared or referenced
18637 // tag. We're going to create a new Decl for it.
18638 }
18639
18640 // Okay, we're going to make a redeclaration. If this is some kind
18641 // of reference, make sure we build the redeclaration in the same DC
18642 // as the original, and ignore the current access specifier.
18643 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18644 SearchDC = PrevTagDecl->getDeclContext();
18645 AS = AS_none;
18646 }
18647 }
18648 // If we get here we have (another) forward declaration or we
18649 // have a definition. Just create a new decl.
18650
18651 } else {
18652 // If we get here, this is a definition of a new tag type in a nested
18653 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18654 // new decl/type. We set PrevDecl to NULL so that the entities
18655 // have distinct types.
18656 Previous.clear();
18657 }
18658 // If we get here, we're going to create a new Decl. If PrevDecl
18659 // is non-NULL, it's a definition of the tag declared by
18660 // PrevDecl. If it's NULL, we have a new definition.
18661
18662 // Otherwise, PrevDecl is not a tag, but was found with tag
18663 // lookup. This is only actually possible in C++, where a few
18664 // things like templates still live in the tag namespace.
18665 } else {
18666 // Use a better diagnostic if an elaborated-type-specifier
18667 // found the wrong kind of type on the first
18668 // (non-redeclaration) lookup.
18669 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18670 !Previous.isForRedeclaration()) {
18671 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18672 Diag(NameLoc, diag::err_tag_reference_non_tag)
18673 << PrevDecl << NTK << Kind;
18674 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18675 Invalid = true;
18676
18677 // Otherwise, only diagnose if the declaration is in scope.
18678 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18679 SS.isNotEmpty() || isMemberSpecialization)) {
18680 // do nothing
18681
18682 // Diagnose implicit declarations introduced by elaborated types.
18683 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18684 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18685 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18686 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18687 Invalid = true;
18688
18689 // Otherwise it's a declaration. Call out a particularly common
18690 // case here.
18691 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18692 unsigned Kind = 0;
18693 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18694 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18695 << Name << Kind << TND->getUnderlyingType();
18696 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18697 Invalid = true;
18698
18699 // Otherwise, diagnose.
18700 } else {
18701 // The tag name clashes with something else in the target scope,
18702 // issue an error and recover by making this tag be anonymous.
18703 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18704 notePreviousDefinition(PrevDecl, NameLoc);
18705 Name = nullptr;
18706 Invalid = true;
18707 }
18708
18709 // The existing declaration isn't relevant to us; we're in a
18710 // new scope, so clear out the previous declaration.
18711 Previous.clear();
18712 }
18713 }
18714
18715CreateNewDecl:
18716
18717 TagDecl *PrevDecl = nullptr;
18718 if (Previous.isSingleResult())
18719 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18720
18721 // If there is an identifier, use the location of the identifier as the
18722 // location of the decl, otherwise use the location of the struct/union
18723 // keyword.
18724 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18725
18726 // Otherwise, create a new declaration. If there is a previous
18727 // declaration of the same entity, the two will be linked via
18728 // PrevDecl.
18729 TagDecl *New;
18730
18731 if (Kind == TagTypeKind::Enum) {
18732 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18733 // enum X { A, B, C } D; D should chain to X.
18734 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18735 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18736 ScopedEnumUsesClassTag, IsFixed);
18737
18740 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18741
18742 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18744
18745 // If this is an undefined enum, warn.
18746 if (TUK != TagUseKind::Definition && !Invalid) {
18747 TagDecl *Def;
18748 if (IsFixed && ED->isFixed()) {
18749 // C++0x: 7.2p2: opaque-enum-declaration.
18750 // Conflicts are diagnosed above. Do nothing.
18751 } else if (PrevDecl &&
18752 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18753 Diag(Loc, diag::ext_forward_ref_enum_def)
18754 << New;
18755 Diag(Def->getLocation(), diag::note_previous_definition);
18756 } else {
18757 unsigned DiagID = diag::ext_forward_ref_enum;
18758 if (getLangOpts().MSVCCompat)
18759 DiagID = diag::ext_ms_forward_ref_enum;
18760 else if (getLangOpts().CPlusPlus)
18761 DiagID = diag::err_forward_ref_enum;
18762 Diag(Loc, DiagID);
18763 }
18764 }
18765
18766 if (EnumUnderlying) {
18768 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18770 else
18771 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18772 QualType EnumTy = ED->getIntegerType();
18773 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18774 ? Context.getPromotedIntegerType(EnumTy)
18775 : EnumTy);
18776 assert(ED->isComplete() && "enum with type should be complete");
18777 }
18778 } else {
18779 // struct/union/class
18780
18781 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18782 // struct X { int A; } D; D should chain to X.
18783 if (getLangOpts().CPlusPlus) {
18784 // FIXME: Look for a way to use RecordDecl for simple structs.
18785 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18786 cast_or_null<CXXRecordDecl>(PrevDecl));
18787
18788 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18790 } else
18791 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18792 cast_or_null<RecordDecl>(PrevDecl));
18793 }
18794
18795 // Only C23 and later allow defining new types in 'offsetof()'.
18796 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18798 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18799 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18800
18801 // C++11 [dcl.type]p3:
18802 // A type-specifier-seq shall not define a class or enumeration [...].
18803 if (!Invalid && getLangOpts().CPlusPlus &&
18804 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18805 TUK == TagUseKind::Definition) {
18806 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18807 << Context.getCanonicalTagType(New);
18808 Invalid = true;
18809 }
18810
18812 DC->getDeclKind() == Decl::Enum) {
18813 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18814 << Context.getCanonicalTagType(New);
18815 Invalid = true;
18816 }
18817
18818 // Maybe add qualifier info.
18819 if (SS.isNotEmpty()) {
18820 if (SS.isSet()) {
18821 // If this is either a declaration or a definition, check the
18822 // nested-name-specifier against the current context.
18823 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18824 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18825 /*TemplateId=*/nullptr,
18826 isMemberSpecialization))
18827 Invalid = true;
18828
18829 New->setQualifierInfo(SS.getWithLocInContext(Context));
18830 if (TemplateParameterLists.size() > 0) {
18831 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18832 }
18833 }
18834 else
18835 Invalid = true;
18836 }
18837
18838 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18839 // Add alignment attributes if necessary; these attributes are checked when
18840 // the ASTContext lays out the structure.
18841 //
18842 // It is important for implementing the correct semantics that this
18843 // happen here (in ActOnTag). The #pragma pack stack is
18844 // maintained as a result of parser callbacks which can occur at
18845 // many points during the parsing of a struct declaration (because
18846 // the #pragma tokens are effectively skipped over during the
18847 // parsing of the struct).
18848 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18849 if (LangOpts.HLSL)
18850 RD->addAttr(PackedAttr::CreateImplicit(Context));
18853 }
18854 }
18855
18856 if (ModulePrivateLoc.isValid()) {
18857 if (isMemberSpecialization)
18858 Diag(New->getLocation(), diag::err_module_private_specialization)
18859 << 2
18860 << FixItHint::CreateRemoval(ModulePrivateLoc);
18861 // __module_private__ does not apply to local classes. However, we only
18862 // diagnose this as an error when the declaration specifiers are
18863 // freestanding. Here, we just ignore the __module_private__.
18864 else if (!SearchDC->isFunctionOrMethod())
18865 New->setModulePrivate();
18866 }
18867
18868 // If this is a specialization of a member class (of a class template),
18869 // check the specialization.
18870 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18871 Invalid = true;
18872
18873 // If we're declaring or defining a tag in function prototype scope in C,
18874 // note that this type can only be used within the function and add it to
18875 // the list of decls to inject into the function definition scope. However,
18876 // in C23 and later, while the type is only visible within the function, the
18877 // function can be called with a compatible type defined in the same TU, so
18878 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18879 if ((Name || Kind == TagTypeKind::Enum) &&
18880 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18881 if (getLangOpts().CPlusPlus) {
18882 // C++ [dcl.fct]p6:
18883 // Types shall not be defined in return or parameter types.
18884 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18885 Diag(Loc, diag::err_type_defined_in_param_type)
18886 << Name;
18887 Invalid = true;
18888 }
18889 if (TUK == TagUseKind::Declaration)
18890 Invalid = true;
18891 } else if (!PrevDecl) {
18892 // In C23 mode, if the declaration is complete, we do not want to
18893 // diagnose.
18894 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18895 Diag(Loc, diag::warn_decl_in_param_list)
18896 << Context.getCanonicalTagType(New);
18897 }
18898 }
18899
18900 if (Invalid)
18901 New->setInvalidDecl();
18902
18903 // Set the lexical context. If the tag has a C++ scope specifier, the
18904 // lexical context will be different from the semantic context.
18905 New->setLexicalDeclContext(CurContext);
18906
18907 // Mark this as a friend decl if applicable.
18908 // In Microsoft mode, a friend declaration also acts as a forward
18909 // declaration so we always pass true to setObjectOfFriendDecl to make
18910 // the tag name visible.
18911 if (TUK == TagUseKind::Friend)
18912 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18913
18914 // Set the access specifier.
18915 if (!Invalid && SearchDC->isRecord())
18916 SetMemberAccessSpecifier(New, PrevDecl, AS);
18917
18918 if (PrevDecl)
18920
18921 if (TUK == TagUseKind::Definition) {
18922 if (!SkipBody || !SkipBody->ShouldSkip) {
18923 New->startDefinition();
18924 } else {
18925 New->setCompleteDefinition();
18926 New->demoteThisDefinitionToDeclaration();
18927 }
18928 }
18929
18930 ProcessDeclAttributeList(S, New, Attrs);
18932
18933 // If this has an identifier, add it to the scope stack.
18934 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18935 // We might be replacing an existing declaration in the lookup tables;
18936 // if so, borrow its access specifier.
18937 if (PrevDecl)
18938 New->setAccess(PrevDecl->getAccess());
18939
18940 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18942 if (Name) // can be null along some error paths
18943 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18944 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18945 } else if (Name) {
18946 S = getNonFieldDeclScope(S);
18947 PushOnScopeChains(New, S, true);
18948 } else {
18949 CurContext->addDecl(New);
18950 }
18951
18952 // If this is the C FILE type, notify the AST context.
18953 if (IdentifierInfo *II = New->getIdentifier())
18954 if (!New->isInvalidDecl() &&
18955 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18956 II->isStr("FILE"))
18957 Context.setFILEDecl(New);
18958
18959 if (PrevDecl)
18960 mergeDeclAttributes(New, PrevDecl);
18961
18962 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18965 }
18966
18967 // If there's a #pragma GCC visibility in scope, set the visibility of this
18968 // record.
18970
18971 // If this is not a definition, process API notes for it now.
18972 if (TUK != TagUseKind::Definition)
18974
18975 if (isMemberSpecialization && !New->isInvalidDecl())
18977
18978 OwnedDecl = true;
18979 // In C++, don't return an invalid declaration. We can't recover well from
18980 // the cases where we make the type anonymous.
18981 if (Invalid && getLangOpts().CPlusPlus) {
18982 if (New->isBeingDefined())
18983 if (auto RD = dyn_cast<RecordDecl>(New))
18984 RD->completeDefinition();
18985 return true;
18986 } else if (SkipBody && SkipBody->ShouldSkip) {
18987 return SkipBody->Previous;
18988 } else {
18989 return New;
18990 }
18991}
18992
18995 TagDecl *Tag = cast<TagDecl>(TagD);
18996
18997 // Enter the tag context.
18998 PushDeclContext(S, Tag);
18999
19001
19002 // If there's a #pragma GCC visibility in scope, set the visibility of this
19003 // record.
19005}
19006
19008 SkipBodyInfo &SkipBody) {
19009 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
19010 return false;
19011
19012 // Make the previous decl visible.
19014 CleanupMergedEnum(S, SkipBody.New);
19015 return true;
19016}
19017
19019 SourceLocation FinalLoc,
19020 bool IsFinalSpelledSealed,
19021 bool IsAbstract,
19022 SourceLocation LBraceLoc) {
19025
19026 FieldCollector->StartClass();
19027
19028 if (!Record->getIdentifier())
19029 return;
19030
19031 if (IsAbstract)
19032 Record->markAbstract();
19033
19034 if (FinalLoc.isValid()) {
19035 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
19036 IsFinalSpelledSealed
19037 ? FinalAttr::Keyword_sealed
19038 : FinalAttr::Keyword_final));
19039 }
19040
19041 // C++ [class]p2:
19042 // [...] The class-name is also inserted into the scope of the
19043 // class itself; this is known as the injected-class-name. For
19044 // purposes of access checking, the injected-class-name is treated
19045 // as if it were a public member name.
19046 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19047 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
19048 Record->getLocation(), Record->getIdentifier());
19049 InjectedClassName->setImplicit();
19050 InjectedClassName->setAccess(AS_public);
19051 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19052 InjectedClassName->setDescribedClassTemplate(Template);
19053
19054 PushOnScopeChains(InjectedClassName, S);
19055 assert(InjectedClassName->isInjectedClassName() &&
19056 "Broken injected-class-name");
19057}
19058
19060 SourceRange BraceRange) {
19062 TagDecl *Tag = cast<TagDecl>(TagD);
19063 Tag->setBraceRange(BraceRange);
19064
19065 // Make sure we "complete" the definition even it is invalid.
19066 if (Tag->isBeingDefined()) {
19067 assert(Tag->isInvalidDecl() && "We should already have completed it");
19068 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19069 RD->completeDefinition();
19070 }
19071
19072 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
19073 FieldCollector->FinishClass();
19074 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19075 auto *Def = RD->getDefinition();
19076 assert(Def && "The record is expected to have a completed definition");
19077 unsigned NumInitMethods = 0;
19078 for (auto *Method : Def->methods()) {
19079 if (!Method->getIdentifier())
19080 continue;
19081 if (Method->getName() == "__init")
19082 NumInitMethods++;
19083 }
19084 if (NumInitMethods > 1 || !Def->hasInitMethod())
19085 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
19086 }
19087
19088 // If we're defining a dynamic class in a module interface unit, we always
19089 // need to produce the vtable for it, even if the vtable is not used in the
19090 // current TU.
19091 //
19092 // The case where the current class is not dynamic is handled in
19093 // MarkVTableUsed.
19094 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19095 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
19096 }
19097
19098 // Exit this scope of this tag's definition.
19100
19101 if (getCurLexicalContext()->isObjCContainer() &&
19102 Tag->getDeclContext()->isFileContext())
19103 Tag->setTopLevelDeclInObjCContainer();
19104
19105 // Notify the consumer that we've defined a tag.
19106 if (!Tag->isInvalidDecl())
19107 Consumer.HandleTagDeclDefinition(Tag);
19108
19109 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19110 // from XLs and instead matches the XL #pragma pack(1) behavior.
19111 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19112 AlignPackStack.hasValue()) {
19113 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19114 // Only diagnose #pragma align(packed).
19115 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19116 return;
19117 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
19118 if (!RD)
19119 return;
19120 // Only warn if there is at least 1 bitfield member.
19121 if (llvm::any_of(RD->fields(),
19122 [](const FieldDecl *FD) { return FD->isBitField(); }))
19123 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
19124 }
19125}
19126
19129 TagDecl *Tag = cast<TagDecl>(TagD);
19130 Tag->setInvalidDecl();
19131
19132 // Make sure we "complete" the definition even it is invalid.
19133 if (Tag->isBeingDefined()) {
19134 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19135 RD->completeDefinition();
19136 }
19137
19138 // We're undoing ActOnTagStartDefinition here, not
19139 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19140 // the FieldCollector.
19141
19143}
19144
19145// Note that FieldName may be null for anonymous bitfields.
19147 const IdentifierInfo *FieldName,
19148 QualType FieldTy, bool IsMsStruct,
19149 Expr *BitWidth) {
19150 assert(BitWidth);
19151 if (BitWidth->containsErrors())
19152 return ExprError();
19153
19154 // C99 6.7.2.1p4 - verify the field type.
19155 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19156 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19157 // Handle incomplete and sizeless types with a specific error.
19158 if (RequireCompleteSizedType(FieldLoc, FieldTy,
19159 diag::err_field_incomplete_or_sizeless))
19160 return ExprError();
19161 if (FieldName)
19162 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
19163 << FieldName << FieldTy << BitWidth->getSourceRange();
19164 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
19165 << FieldTy << BitWidth->getSourceRange();
19167 return ExprError();
19168
19169 // If the bit-width is type- or value-dependent, don't try to check
19170 // it now.
19171 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19172 return BitWidth;
19173
19174 llvm::APSInt Value;
19175 ExprResult ICE =
19177 if (ICE.isInvalid())
19178 return ICE;
19179 BitWidth = ICE.get();
19180
19181 // Zero-width bitfield is ok for anonymous field.
19182 if (Value == 0 && FieldName)
19183 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
19184 << FieldName << BitWidth->getSourceRange();
19185
19186 if (Value.isSigned() && Value.isNegative()) {
19187 if (FieldName)
19188 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
19189 << FieldName << toString(Value, 10);
19190 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
19191 << toString(Value, 10);
19192 }
19193
19194 // The size of the bit-field must not exceed our maximum permitted object
19195 // size.
19196 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19197 return Diag(FieldLoc, diag::err_bitfield_too_wide)
19198 << !FieldName << FieldName << toString(Value, 10);
19199 }
19200
19201 if (!FieldTy->isDependentType()) {
19202 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
19203 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
19204 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
19205
19206 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19207 // ABI.
19208 bool CStdConstraintViolation =
19209 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19210 bool MSBitfieldViolation = Value.ugt(TypeStorageSize) && IsMsStruct;
19211 if (CStdConstraintViolation || MSBitfieldViolation) {
19212 unsigned DiagWidth =
19213 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19214 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
19215 << (bool)FieldName << FieldName << toString(Value, 10)
19216 << !CStdConstraintViolation << DiagWidth;
19217 }
19218
19219 // Warn on types where the user might conceivably expect to get all
19220 // specified bits as value bits: that's all integral types other than
19221 // 'bool'.
19222 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19223 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
19224 << FieldName << Value << (unsigned)TypeWidth;
19225 }
19226 }
19227
19228 if (isa<ConstantExpr>(BitWidth))
19229 return BitWidth;
19230 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
19231}
19232
19234 Declarator &D, Expr *BitfieldWidth) {
19235 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
19236 D, BitfieldWidth,
19237 /*InitStyle=*/ICIS_NoInit, AS_public);
19238 return Res;
19239}
19240
19242 SourceLocation DeclStart,
19243 Declarator &D, Expr *BitWidth,
19244 InClassInitStyle InitStyle,
19245 AccessSpecifier AS) {
19246 if (D.isDecompositionDeclarator()) {
19248 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19249 << Decomp.getSourceRange();
19250 return nullptr;
19251 }
19252
19253 const IdentifierInfo *II = D.getIdentifier();
19254 SourceLocation Loc = DeclStart;
19255 if (II) Loc = D.getIdentifierLoc();
19256
19258 QualType T = TInfo->getType();
19259 if (getLangOpts().CPlusPlus) {
19261
19264 D.setInvalidType();
19265 T = Context.IntTy;
19266 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19267 }
19268 }
19269
19271
19273 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19274 << getLangOpts().CPlusPlus17;
19277 diag::err_invalid_thread)
19279
19280 // Check to see if this name was declared as a member previously
19281 NamedDecl *PrevDecl = nullptr;
19282 LookupResult Previous(*this, II, Loc, LookupMemberName,
19284 LookupName(Previous, S);
19285 switch (Previous.getResultKind()) {
19288 PrevDecl = Previous.getAsSingle<NamedDecl>();
19289 break;
19290
19292 PrevDecl = Previous.getRepresentativeDecl();
19293 break;
19294
19298 break;
19299 }
19300 Previous.suppressDiagnostics();
19301
19302 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19303 // Maybe we will complain about the shadowed template parameter.
19305 // Just pretend that we didn't see the previous declaration.
19306 PrevDecl = nullptr;
19307 }
19308
19309 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19310 PrevDecl = nullptr;
19311
19312 bool Mutable
19313 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19314 SourceLocation TSSL = D.getBeginLoc();
19315 FieldDecl *NewFD
19316 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19317 TSSL, AS, PrevDecl, &D);
19318
19319 if (NewFD->isInvalidDecl())
19320 Record->setInvalidDecl();
19321
19323 NewFD->setModulePrivate();
19324
19325 if (NewFD->isInvalidDecl() && PrevDecl) {
19326 // Don't introduce NewFD into scope; there's already something
19327 // with the same name in the same scope.
19328 } else if (II) {
19329 PushOnScopeChains(NewFD, S);
19330 } else
19331 Record->addDecl(NewFD);
19332
19333 return NewFD;
19334}
19335
19337 TypeSourceInfo *TInfo,
19339 bool Mutable, Expr *BitWidth,
19340 InClassInitStyle InitStyle,
19341 SourceLocation TSSL,
19342 AccessSpecifier AS, NamedDecl *PrevDecl,
19343 Declarator *D) {
19344 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19345 bool InvalidDecl = false;
19346 if (D) InvalidDecl = D->isInvalidType();
19347
19348 // If we receive a broken type, recover by assuming 'int' and
19349 // marking this declaration as invalid.
19350 if (T.isNull() || T->containsErrors()) {
19351 InvalidDecl = true;
19352 T = Context.IntTy;
19353 }
19354
19355 QualType EltTy = Context.getBaseElementType(T);
19356 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19357 bool isIncomplete =
19358 LangOpts.HLSL // HLSL allows sizeless builtin types
19359 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19360 : RequireCompleteSizedType(Loc, EltTy,
19361 diag::err_field_incomplete_or_sizeless);
19362 if (isIncomplete) {
19363 // Fields of incomplete type force their record to be invalid.
19364 Record->setInvalidDecl();
19365 InvalidDecl = true;
19366 } else {
19367 NamedDecl *Def;
19368 EltTy->isIncompleteType(&Def);
19369 if (Def && Def->isInvalidDecl()) {
19370 Record->setInvalidDecl();
19371 InvalidDecl = true;
19372 }
19373 }
19374 }
19375
19376 // TR 18037 does not allow fields to be declared with address space
19377 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19378 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19379 Diag(Loc, diag::err_field_with_address_space);
19380 Record->setInvalidDecl();
19381 InvalidDecl = true;
19382 }
19383
19384 if (LangOpts.OpenCL) {
19385 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19386 // used as structure or union field: image, sampler, event or block types.
19387 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19388 T->isBlockPointerType()) {
19389 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19390 Record->setInvalidDecl();
19391 InvalidDecl = true;
19392 }
19393 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19394 // is enabled.
19395 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19396 "__cl_clang_bitfields", LangOpts)) {
19397 Diag(Loc, diag::err_opencl_bitfields);
19398 InvalidDecl = true;
19399 }
19400 }
19401
19402 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19403 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19404 T.hasQualifiers()) {
19405 InvalidDecl = true;
19406 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19407 }
19408
19409 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19410 // than a variably modified type.
19411 if (!InvalidDecl && T->isVariablyModifiedType()) {
19413 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19414 InvalidDecl = true;
19415 }
19416
19417 // Fields can not have abstract class types
19418 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19419 diag::err_abstract_type_in_decl,
19421 InvalidDecl = true;
19422
19423 if (InvalidDecl)
19424 BitWidth = nullptr;
19425 // If this is declared as a bit-field, check the bit-field.
19426 if (BitWidth) {
19427 BitWidth =
19428 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19429 if (!BitWidth) {
19430 InvalidDecl = true;
19431 BitWidth = nullptr;
19432 }
19433 }
19434
19435 // Check that 'mutable' is consistent with the type of the declaration.
19436 if (!InvalidDecl && Mutable) {
19437 unsigned DiagID = 0;
19438 if (T->isReferenceType())
19439 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19440 : diag::err_mutable_reference;
19441 else if (T.isConstQualified())
19442 DiagID = diag::err_mutable_const;
19443
19444 if (DiagID) {
19445 SourceLocation ErrLoc = Loc;
19446 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19447 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19448 Diag(ErrLoc, DiagID);
19449 if (DiagID != diag::ext_mutable_reference) {
19450 Mutable = false;
19451 InvalidDecl = true;
19452 }
19453 }
19454 }
19455
19456 // C++11 [class.union]p8 (DR1460):
19457 // At most one variant member of a union may have a
19458 // brace-or-equal-initializer.
19459 if (InitStyle != ICIS_NoInit)
19461
19462 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19463 BitWidth, Mutable, InitStyle);
19464 if (InvalidDecl)
19465 NewFD->setInvalidDecl();
19466
19467 if (!InvalidDecl)
19469
19470 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19471 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19472 Diag(Loc, diag::err_duplicate_member) << II;
19473 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19474 NewFD->setInvalidDecl();
19475 }
19476
19477 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19478 if (Record->isUnion()) {
19479 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19480 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19481
19482 // C++ [class.union]p1: An object of a class with a non-trivial
19483 // constructor, a non-trivial copy constructor, a non-trivial
19484 // destructor, or a non-trivial copy assignment operator
19485 // cannot be a member of a union, nor can an array of such
19486 // objects.
19487 if (CheckNontrivialField(NewFD))
19488 NewFD->setInvalidDecl();
19489 }
19490
19491 // C++ [class.union]p1: If a union contains a member of reference type,
19492 // the program is ill-formed, except when compiling with MSVC extensions
19493 // enabled.
19494 if (EltTy->isReferenceType()) {
19495 const bool HaveMSExt =
19496 getLangOpts().MicrosoftExt &&
19498
19499 Diag(NewFD->getLocation(),
19500 HaveMSExt ? diag::ext_union_member_of_reference_type
19501 : diag::err_union_member_of_reference_type)
19502 << NewFD->getDeclName() << EltTy;
19503 if (!HaveMSExt)
19504 NewFD->setInvalidDecl();
19505 }
19506 }
19507 }
19508
19509 // FIXME: We need to pass in the attributes given an AST
19510 // representation, not a parser representation.
19511 if (D) {
19512 // FIXME: The current scope is almost... but not entirely... correct here.
19513 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19514
19515 if (NewFD->hasAttrs())
19517 }
19518
19519 // In auto-retain/release, infer strong retension for fields of
19520 // retainable type.
19521 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19522 NewFD->setInvalidDecl();
19523
19524 if (T.isObjCGCWeak())
19525 Diag(Loc, diag::warn_attribute_weak_on_field);
19526
19527 // PPC MMA non-pointer types are not allowed as field types.
19528 if (Context.getTargetInfo().getTriple().isPPC64() &&
19529 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19530 NewFD->setInvalidDecl();
19531
19532 NewFD->setAccess(AS);
19533 return NewFD;
19534}
19535
19537 assert(FD);
19538 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19539
19540 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19541 return false;
19542
19543 QualType EltTy = Context.getBaseElementType(FD->getType());
19544 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19545 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19546 // We check for copy constructors before constructors
19547 // because otherwise we'll never get complaints about
19548 // copy constructors.
19549
19551 // We're required to check for any non-trivial constructors. Since the
19552 // implicit default constructor is suppressed if there are any
19553 // user-declared constructors, we just need to check that there is a
19554 // trivial default constructor and a trivial copy constructor. (We don't
19555 // worry about move constructors here, since this is a C++98 check.)
19556 if (RDecl->hasNonTrivialCopyConstructor())
19558 else if (!RDecl->hasTrivialDefaultConstructor())
19560 else if (RDecl->hasNonTrivialCopyAssignment())
19562 else if (RDecl->hasNonTrivialDestructor())
19564
19565 if (member != CXXSpecialMemberKind::Invalid) {
19566 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19567 RDecl->hasObjectMember()) {
19568 // Objective-C++ ARC: it is an error to have a non-trivial field of
19569 // a union. However, system headers in Objective-C programs
19570 // occasionally have Objective-C lifetime objects within unions,
19571 // and rather than cause the program to fail, we make those
19572 // members unavailable.
19573 SourceLocation Loc = FD->getLocation();
19574 if (getSourceManager().isInSystemHeader(Loc)) {
19575 if (!FD->hasAttr<UnavailableAttr>())
19576 FD->addAttr(UnavailableAttr::CreateImplicit(
19577 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19578 return false;
19579 }
19580 }
19581
19582 Diag(FD->getLocation(),
19584 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19585 : diag::err_illegal_union_or_anon_struct_member)
19586 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19587 DiagnoseNontrivial(RDecl, member);
19588 return !getLangOpts().CPlusPlus11;
19589 }
19590 }
19591
19592 return false;
19593}
19594
19596 SmallVectorImpl<Decl *> &AllIvarDecls) {
19597 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19598 return;
19599
19600 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19601 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19602
19603 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19604 return;
19605 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19606 if (!ID) {
19607 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19608 if (!CD->IsClassExtension())
19609 return;
19610 }
19611 // No need to add this to end of @implementation.
19612 else
19613 return;
19614 }
19615 // All conditions are met. Add a new bitfield to the tail end of ivars.
19616 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19617 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19618 Expr *BitWidth =
19619 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19620
19621 Ivar = ObjCIvarDecl::Create(
19622 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19623 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19624 ObjCIvarDecl::Private, BitWidth, true);
19625 AllIvarDecls.push_back(Ivar);
19626}
19627
19628/// [class.dtor]p4:
19629/// At the end of the definition of a class, overload resolution is
19630/// performed among the prospective destructors declared in that class with
19631/// an empty argument list to select the destructor for the class, also
19632/// known as the selected destructor.
19633///
19634/// We do the overload resolution here, then mark the selected constructor in the AST.
19635/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19637 if (!Record->hasUserDeclaredDestructor()) {
19638 return;
19639 }
19640
19641 SourceLocation Loc = Record->getLocation();
19643
19644 for (auto *Decl : Record->decls()) {
19645 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19646 if (DD->isInvalidDecl())
19647 continue;
19648 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19649 OCS);
19650 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19651 }
19652 }
19653
19654 if (OCS.empty()) {
19655 return;
19656 }
19658 unsigned Msg = 0;
19659 OverloadCandidateDisplayKind DisplayKind;
19660
19661 switch (OCS.BestViableFunction(S, Loc, Best)) {
19662 case OR_Success:
19663 case OR_Deleted:
19664 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19665 break;
19666
19667 case OR_Ambiguous:
19668 Msg = diag::err_ambiguous_destructor;
19669 DisplayKind = OCD_AmbiguousCandidates;
19670 break;
19671
19673 Msg = diag::err_no_viable_destructor;
19674 DisplayKind = OCD_AllCandidates;
19675 break;
19676 }
19677
19678 if (Msg) {
19679 // OpenCL have got their own thing going with destructors. It's slightly broken,
19680 // but we allow it.
19681 if (!S.LangOpts.OpenCL) {
19682 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19683 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19684 Record->setInvalidDecl();
19685 }
19686 // It's a bit hacky: At this point we've raised an error but we want the
19687 // rest of the compiler to continue somehow working. However almost
19688 // everything we'll try to do with the class will depend on there being a
19689 // destructor. So let's pretend the first one is selected and hope for the
19690 // best.
19691 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19692 }
19693}
19694
19695/// [class.mem.special]p5
19696/// Two special member functions are of the same kind if:
19697/// - they are both default constructors,
19698/// - they are both copy or move constructors with the same first parameter
19699/// type, or
19700/// - they are both copy or move assignment operators with the same first
19701/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19703 CXXMethodDecl *M1,
19704 CXXMethodDecl *M2,
19706 // We don't want to compare templates to non-templates: See
19707 // https://github.com/llvm/llvm-project/issues/59206
19709 return bool(M1->getDescribedFunctionTemplate()) ==
19711 // FIXME: better resolve CWG
19712 // https://cplusplus.github.io/CWG/issues/2787.html
19713 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19714 M2->getNonObjectParameter(0)->getType()))
19715 return false;
19716 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
19718 return false;
19719
19720 return true;
19721}
19722
19723/// [class.mem.special]p6:
19724/// An eligible special member function is a special member function for which:
19725/// - the function is not deleted,
19726/// - the associated constraints, if any, are satisfied, and
19727/// - no special member function of the same kind whose associated constraints
19728/// [CWG2595], if any, are satisfied is more constrained.
19732 SmallVector<bool, 4> SatisfactionStatus;
19733
19734 for (CXXMethodDecl *Method : Methods) {
19735 if (!Method->getTrailingRequiresClause())
19736 SatisfactionStatus.push_back(true);
19737 else {
19738 ConstraintSatisfaction Satisfaction;
19739 if (S.CheckFunctionConstraints(Method, Satisfaction))
19740 SatisfactionStatus.push_back(false);
19741 else
19742 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19743 }
19744 }
19745
19746 for (size_t i = 0; i < Methods.size(); i++) {
19747 if (!SatisfactionStatus[i])
19748 continue;
19749 CXXMethodDecl *Method = Methods[i];
19750 CXXMethodDecl *OrigMethod = Method;
19751 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19752 OrigMethod = cast<CXXMethodDecl>(MF);
19753
19755 bool AnotherMethodIsMoreConstrained = false;
19756 for (size_t j = 0; j < Methods.size(); j++) {
19757 if (i == j || !SatisfactionStatus[j])
19758 continue;
19759 CXXMethodDecl *OtherMethod = Methods[j];
19760 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19761 OtherMethod = cast<CXXMethodDecl>(MF);
19762
19763 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19764 CSM))
19765 continue;
19766
19768 if (!Other)
19769 continue;
19770 if (!Orig) {
19771 AnotherMethodIsMoreConstrained = true;
19772 break;
19773 }
19774 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19775 AnotherMethodIsMoreConstrained)) {
19776 // There was an error with the constraints comparison. Exit the loop
19777 // and don't consider this function eligible.
19778 AnotherMethodIsMoreConstrained = true;
19779 }
19780 if (AnotherMethodIsMoreConstrained)
19781 break;
19782 }
19783 // FIXME: Do not consider deleted methods as eligible after implementing
19784 // DR1734 and DR1496.
19785 if (!AnotherMethodIsMoreConstrained) {
19786 Method->setIneligibleOrNotSelected(false);
19787 Record->addedEligibleSpecialMemberFunction(Method,
19788 1 << llvm::to_underlying(CSM));
19789 }
19790 }
19791}
19792
19795 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19796 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19797 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19798 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19799 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19800
19801 for (auto *Decl : Record->decls()) {
19802 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19803 if (!MD) {
19804 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19805 if (FTD)
19806 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19807 }
19808 if (!MD)
19809 continue;
19810 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19811 if (CD->isInvalidDecl())
19812 continue;
19813 if (CD->isDefaultConstructor())
19814 DefaultConstructors.push_back(MD);
19815 else if (CD->isCopyConstructor())
19816 CopyConstructors.push_back(MD);
19817 else if (CD->isMoveConstructor())
19818 MoveConstructors.push_back(MD);
19819 } else if (MD->isCopyAssignmentOperator()) {
19820 CopyAssignmentOperators.push_back(MD);
19821 } else if (MD->isMoveAssignmentOperator()) {
19822 MoveAssignmentOperators.push_back(MD);
19823 }
19824 }
19825
19826 SetEligibleMethods(S, Record, DefaultConstructors,
19828 SetEligibleMethods(S, Record, CopyConstructors,
19830 SetEligibleMethods(S, Record, MoveConstructors,
19832 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19834 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19836}
19837
19838bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19839 // Check to see if a FieldDecl is a pointer to a function.
19840 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19841 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19842 if (!FD) {
19843 // Check whether this is a forward declaration that was inserted by
19844 // Clang. This happens when a non-forward declared / defined type is
19845 // used, e.g.:
19846 //
19847 // struct foo {
19848 // struct bar *(*f)();
19849 // struct bar *(*g)();
19850 // };
19851 //
19852 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19853 // incomplete definition.
19854 if (const auto *TD = dyn_cast<TagDecl>(D))
19855 return !TD->isCompleteDefinition();
19856 return false;
19857 }
19858 QualType FieldType = FD->getType().getDesugaredType(Context);
19859 if (isa<PointerType>(FieldType)) {
19860 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19861 return PointeeType.getDesugaredType(Context)->isFunctionType();
19862 }
19863 // If a member is a struct entirely of function pointers, that counts too.
19864 if (const auto *Record = FieldType->getAsRecordDecl();
19865 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19866 return true;
19867 return false;
19868 };
19869
19870 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19871}
19872
19873void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19874 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19875 SourceLocation RBrac,
19876 const ParsedAttributesView &Attrs) {
19877 assert(EnclosingDecl && "missing record or interface decl");
19878
19879 // If this is an Objective-C @implementation or category and we have
19880 // new fields here we should reset the layout of the interface since
19881 // it will now change.
19882 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19883 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19884 switch (DC->getKind()) {
19885 default: break;
19886 case Decl::ObjCCategory:
19887 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19888 break;
19889 case Decl::ObjCImplementation:
19890 Context.
19891 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19892 break;
19893 }
19894 }
19895
19896 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19897 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19898
19899 // Start counting up the number of named members; make sure to include
19900 // members of anonymous structs and unions in the total.
19901 unsigned NumNamedMembers = 0;
19902 if (Record) {
19903 for (const auto *I : Record->decls()) {
19904 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19905 if (IFD->getDeclName())
19906 ++NumNamedMembers;
19907 }
19908 }
19909
19910 // Verify that all the fields are okay.
19912 const FieldDecl *PreviousField = nullptr;
19913 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19914 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
19915 FieldDecl *FD = cast<FieldDecl>(*i);
19916
19917 // Get the type for the field.
19918 const Type *FDTy = FD->getType().getTypePtr();
19919
19920 if (!FD->isAnonymousStructOrUnion()) {
19921 // Remember all fields written by the user.
19922 RecFields.push_back(FD);
19923 }
19924
19925 // If the field is already invalid for some reason, don't emit more
19926 // diagnostics about it.
19927 if (FD->isInvalidDecl()) {
19928 EnclosingDecl->setInvalidDecl();
19929 continue;
19930 }
19931
19932 // C99 6.7.2.1p2:
19933 // A structure or union shall not contain a member with
19934 // incomplete or function type (hence, a structure shall not
19935 // contain an instance of itself, but may contain a pointer to
19936 // an instance of itself), except that the last member of a
19937 // structure with more than one named member may have incomplete
19938 // array type; such a structure (and any union containing,
19939 // possibly recursively, a member that is such a structure)
19940 // shall not be a member of a structure or an element of an
19941 // array.
19942 bool IsLastField = (i + 1 == Fields.end());
19943 if (FDTy->isFunctionType()) {
19944 // Field declared as a function.
19945 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19946 << FD->getDeclName();
19947 FD->setInvalidDecl();
19948 EnclosingDecl->setInvalidDecl();
19949 continue;
19950 } else if (FDTy->isIncompleteArrayType() &&
19951 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19952 if (Record) {
19953 // Flexible array member.
19954 // Microsoft and g++ is more permissive regarding flexible array.
19955 // It will accept flexible array in union and also
19956 // as the sole element of a struct/class.
19957 unsigned DiagID = 0;
19958 if (!Record->isUnion() && !IsLastField) {
19959 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19960 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19961 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19962 FD->setInvalidDecl();
19963 EnclosingDecl->setInvalidDecl();
19964 continue;
19965 } else if (Record->isUnion())
19966 DiagID = getLangOpts().MicrosoftExt
19967 ? diag::ext_flexible_array_union_ms
19968 : diag::ext_flexible_array_union_gnu;
19969 else if (NumNamedMembers < 1)
19970 DiagID = getLangOpts().MicrosoftExt
19971 ? diag::ext_flexible_array_empty_aggregate_ms
19972 : diag::ext_flexible_array_empty_aggregate_gnu;
19973
19974 if (DiagID)
19975 Diag(FD->getLocation(), DiagID)
19976 << FD->getDeclName() << Record->getTagKind();
19977 // While the layout of types that contain virtual bases is not specified
19978 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19979 // virtual bases after the derived members. This would make a flexible
19980 // array member declared at the end of an object not adjacent to the end
19981 // of the type.
19982 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19983 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19984 << FD->getDeclName() << Record->getTagKind();
19985 if (!getLangOpts().C99)
19986 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19987 << FD->getDeclName() << Record->getTagKind();
19988
19989 // If the element type has a non-trivial destructor, we would not
19990 // implicitly destroy the elements, so disallow it for now.
19991 //
19992 // FIXME: GCC allows this. We should probably either implicitly delete
19993 // the destructor of the containing class, or just allow this.
19994 QualType BaseElem = Context.getBaseElementType(FD->getType());
19995 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19996 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19997 << FD->getDeclName() << FD->getType();
19998 FD->setInvalidDecl();
19999 EnclosingDecl->setInvalidDecl();
20000 continue;
20001 }
20002 // Okay, we have a legal flexible array member at the end of the struct.
20003 Record->setHasFlexibleArrayMember(true);
20004 } else {
20005 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20006 // unless they are followed by another ivar. That check is done
20007 // elsewhere, after synthesized ivars are known.
20008 }
20009 } else if (!FDTy->isDependentType() &&
20010 (LangOpts.HLSL // HLSL allows sizeless builtin types
20012 diag::err_incomplete_type)
20014 FD->getLocation(), FD->getType(),
20015 diag::err_field_incomplete_or_sizeless))) {
20016 // Incomplete type
20017 FD->setInvalidDecl();
20018 EnclosingDecl->setInvalidDecl();
20019 continue;
20020 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20021 if (Record && RD->hasFlexibleArrayMember()) {
20022 // A type which contains a flexible array member is considered to be a
20023 // flexible array member.
20024 Record->setHasFlexibleArrayMember(true);
20025 if (!Record->isUnion()) {
20026 // If this is a struct/class and this is not the last element, reject
20027 // it. Note that GCC supports variable sized arrays in the middle of
20028 // structures.
20029 if (!IsLastField)
20030 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
20031 << FD->getDeclName() << FD->getType();
20032 else {
20033 // We support flexible arrays at the end of structs in
20034 // other structs as an extension.
20035 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
20036 << FD->getDeclName();
20037 }
20038 }
20039 }
20040 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
20042 diag::err_abstract_type_in_decl,
20044 // Ivars can not have abstract class types
20045 FD->setInvalidDecl();
20046 }
20047 if (Record && RD->hasObjectMember())
20048 Record->setHasObjectMember(true);
20049 if (Record && RD->hasVolatileMember())
20050 Record->setHasVolatileMember(true);
20051 } else if (FDTy->isObjCObjectType()) {
20052 /// A field cannot be an Objective-c object
20053 Diag(FD->getLocation(), diag::err_statically_allocated_object)
20055 QualType T = Context.getObjCObjectPointerType(FD->getType());
20056 FD->setType(T);
20057 } else if (Record && Record->isUnion() &&
20059 getSourceManager().isInSystemHeader(FD->getLocation()) &&
20060 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20062 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
20063 // For backward compatibility, fields of C unions declared in system
20064 // headers that have non-trivial ObjC ownership qualifications are marked
20065 // as unavailable unless the qualifier is explicit and __strong. This can
20066 // break ABI compatibility between programs compiled with ARC and MRR, but
20067 // is a better option than rejecting programs using those unions under
20068 // ARC.
20069 FD->addAttr(UnavailableAttr::CreateImplicit(
20070 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
20071 FD->getLocation()));
20072 } else if (getLangOpts().ObjC &&
20073 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20074 !Record->hasObjectMember()) {
20075 if (FD->getType()->isObjCObjectPointerType() ||
20076 FD->getType().isObjCGCStrong())
20077 Record->setHasObjectMember(true);
20078 else if (Context.getAsArrayType(FD->getType())) {
20079 QualType BaseType = Context.getBaseElementType(FD->getType());
20080 if (const auto *RD = BaseType->getAsRecordDecl();
20081 RD && RD->hasObjectMember())
20082 Record->setHasObjectMember(true);
20083 else if (BaseType->isObjCObjectPointerType() ||
20084 BaseType.isObjCGCStrong())
20085 Record->setHasObjectMember(true);
20086 }
20087 }
20088
20089 if (Record && !getLangOpts().CPlusPlus &&
20090 !shouldIgnoreForRecordTriviality(FD)) {
20091 QualType FT = FD->getType();
20093 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20095 Record->isUnion())
20096 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20097 }
20100 Record->setNonTrivialToPrimitiveCopy(true);
20101 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20102 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20103 }
20104 if (FD->hasAttr<ExplicitInitAttr>())
20105 Record->setHasUninitializedExplicitInitFields(true);
20106 if (FT.isDestructedType()) {
20107 Record->setNonTrivialToPrimitiveDestroy(true);
20108 Record->setParamDestroyedInCallee(true);
20109 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20110 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20111 }
20112
20113 if (const auto *RD = FT->getAsRecordDecl()) {
20114 if (RD->getArgPassingRestrictions() ==
20116 Record->setArgPassingRestrictions(
20118 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20119 Record->setArgPassingRestrictions(
20121 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20122 Q && Q.isAddressDiscriminated()) {
20123 Record->setArgPassingRestrictions(
20125 Record->setNonTrivialToPrimitiveCopy(true);
20126 }
20127 }
20128
20129 if (Record && FD->getType().isVolatileQualified())
20130 Record->setHasVolatileMember(true);
20131 bool ReportMSBitfieldStoragePacking =
20132 Record && PreviousField &&
20133 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
20134 Record->getLocation());
20135 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20136 return FD->isBitField() && !FD->getType()->isDependentType();
20137 };
20138
20139 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20140 IsNonDependentBitField(PreviousField)) {
20141 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
20142 CharUnits PreviousFieldStorageSize =
20143 Context.getTypeSizeInChars(PreviousField->getType());
20144 if (FDStorageSize != PreviousFieldStorageSize) {
20145 Diag(FD->getLocation(),
20146 diag::warn_ms_bitfield_mismatched_storage_packing)
20147 << FD << FD->getType() << FDStorageSize.getQuantity()
20148 << PreviousFieldStorageSize.getQuantity();
20149 Diag(PreviousField->getLocation(),
20150 diag::note_ms_bitfield_mismatched_storage_size_previous)
20151 << PreviousField << PreviousField->getType();
20152 }
20153 }
20154 // Keep track of the number of named members.
20155 if (FD->getIdentifier())
20156 ++NumNamedMembers;
20157 }
20158
20159 // Okay, we successfully defined 'Record'.
20160 if (Record) {
20161 bool Completed = false;
20162 if (S) {
20163 Scope *Parent = S->getParent();
20164 if (Parent && Parent->isTypeAliasScope() &&
20165 Parent->isTemplateParamScope())
20166 Record->setInvalidDecl();
20167 }
20168
20169 if (CXXRecord) {
20170 if (!CXXRecord->isInvalidDecl()) {
20171 // Set access bits correctly on the directly-declared conversions.
20173 I = CXXRecord->conversion_begin(),
20174 E = CXXRecord->conversion_end(); I != E; ++I)
20175 I.setAccess((*I)->getAccess());
20176 }
20177
20178 // Add any implicitly-declared members to this class.
20180
20181 if (!CXXRecord->isDependentType()) {
20182 if (!CXXRecord->isInvalidDecl()) {
20183 // If we have virtual base classes, we may end up finding multiple
20184 // final overriders for a given virtual function. Check for this
20185 // problem now.
20186 if (CXXRecord->getNumVBases()) {
20187 CXXFinalOverriderMap FinalOverriders;
20188 CXXRecord->getFinalOverriders(FinalOverriders);
20189
20190 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20191 MEnd = FinalOverriders.end();
20192 M != MEnd; ++M) {
20193 for (OverridingMethods::iterator SO = M->second.begin(),
20194 SOEnd = M->second.end();
20195 SO != SOEnd; ++SO) {
20196 assert(SO->second.size() > 0 &&
20197 "Virtual function without overriding functions?");
20198 if (SO->second.size() == 1)
20199 continue;
20200
20201 // C++ [class.virtual]p2:
20202 // In a derived class, if a virtual member function of a base
20203 // class subobject has more than one final overrider the
20204 // program is ill-formed.
20205 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
20206 << (const NamedDecl *)M->first << Record;
20207 Diag(M->first->getLocation(),
20208 diag::note_overridden_virtual_function);
20210 OM = SO->second.begin(),
20211 OMEnd = SO->second.end();
20212 OM != OMEnd; ++OM)
20213 Diag(OM->Method->getLocation(), diag::note_final_overrider)
20214 << (const NamedDecl *)M->first << OM->Method->getParent();
20215
20216 Record->setInvalidDecl();
20217 }
20218 }
20219 CXXRecord->completeDefinition(&FinalOverriders);
20220 Completed = true;
20221 }
20222 }
20223 ComputeSelectedDestructor(*this, CXXRecord);
20225 }
20226 }
20227
20228 if (!Completed)
20229 Record->completeDefinition();
20230
20231 // Handle attributes before checking the layout.
20233
20234 // Maybe randomize the record's decls. We automatically randomize a record
20235 // of function pointers, unless it has the "no_randomize_layout" attribute.
20236 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20237 !Record->isRandomized() && !Record->isUnion() &&
20238 (Record->hasAttr<RandomizeLayoutAttr>() ||
20239 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20240 EntirelyFunctionPointers(Record)))) {
20241 SmallVector<Decl *, 32> NewDeclOrdering;
20243 NewDeclOrdering))
20244 Record->reorderDecls(NewDeclOrdering);
20245 }
20246
20247 // We may have deferred checking for a deleted destructor. Check now.
20248 if (CXXRecord) {
20249 auto *Dtor = CXXRecord->getDestructor();
20250 if (Dtor && Dtor->isImplicit() &&
20252 CXXRecord->setImplicitDestructorIsDeleted();
20253 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20254 }
20255 }
20256
20257 if (Record->hasAttrs()) {
20259
20260 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20262 IA->getRange(), IA->getBestCase(),
20263 IA->getInheritanceModel());
20264 }
20265
20266 // Check if the structure/union declaration is a type that can have zero
20267 // size in C. For C this is a language extension, for C++ it may cause
20268 // compatibility problems.
20269 bool CheckForZeroSize;
20270 if (!getLangOpts().CPlusPlus) {
20271 CheckForZeroSize = true;
20272 } else {
20273 // For C++ filter out types that cannot be referenced in C code.
20275 CheckForZeroSize =
20276 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20277 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20278 CXXRecord->isCLike();
20279 }
20280 if (CheckForZeroSize) {
20281 bool ZeroSize = true;
20282 bool IsEmpty = true;
20283 unsigned NonBitFields = 0;
20284 for (RecordDecl::field_iterator I = Record->field_begin(),
20285 E = Record->field_end();
20286 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20287 IsEmpty = false;
20288 if (I->isUnnamedBitField()) {
20289 if (!I->isZeroLengthBitField())
20290 ZeroSize = false;
20291 } else {
20292 ++NonBitFields;
20293 QualType FieldType = I->getType();
20294 if (FieldType->isIncompleteType() ||
20295 !Context.getTypeSizeInChars(FieldType).isZero())
20296 ZeroSize = false;
20297 }
20298 }
20299
20300 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20301 // allowed in C++, but warn if its declaration is inside
20302 // extern "C" block.
20303 if (ZeroSize) {
20304 Diag(RecLoc, getLangOpts().CPlusPlus ?
20305 diag::warn_zero_size_struct_union_in_extern_c :
20306 diag::warn_zero_size_struct_union_compat)
20307 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20308 }
20309
20310 // Structs without named members are extension in C (C99 6.7.2.1p7),
20311 // but are accepted by GCC. In C2y, this became implementation-defined
20312 // (C2y 6.7.3.2p10).
20313 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20314 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20315 : diag::ext_no_named_members_in_struct_union)
20316 << Record->isUnion();
20317 }
20318 }
20319 } else {
20320 ObjCIvarDecl **ClsFields =
20321 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20322 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20323 ID->setEndOfDefinitionLoc(RBrac);
20324 // Add ivar's to class's DeclContext.
20325 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20326 ClsFields[i]->setLexicalDeclContext(ID);
20327 ID->addDecl(ClsFields[i]);
20328 }
20329 // Must enforce the rule that ivars in the base classes may not be
20330 // duplicates.
20331 if (ID->getSuperClass())
20332 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20333 } else if (ObjCImplementationDecl *IMPDecl =
20334 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20335 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20336 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20337 // Ivar declared in @implementation never belongs to the implementation.
20338 // Only it is in implementation's lexical context.
20339 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20340 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20341 RBrac);
20342 IMPDecl->setIvarLBraceLoc(LBrac);
20343 IMPDecl->setIvarRBraceLoc(RBrac);
20344 } else if (ObjCCategoryDecl *CDecl =
20345 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20346 // case of ivars in class extension; all other cases have been
20347 // reported as errors elsewhere.
20348 // FIXME. Class extension does not have a LocEnd field.
20349 // CDecl->setLocEnd(RBrac);
20350 // Add ivar's to class extension's DeclContext.
20351 // Diagnose redeclaration of private ivars.
20352 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20353 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20354 if (IDecl) {
20355 if (const ObjCIvarDecl *ClsIvar =
20356 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20357 Diag(ClsFields[i]->getLocation(),
20358 diag::err_duplicate_ivar_declaration);
20359 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20360 continue;
20361 }
20362 for (const auto *Ext : IDecl->known_extensions()) {
20363 if (const ObjCIvarDecl *ClsExtIvar
20364 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20365 Diag(ClsFields[i]->getLocation(),
20366 diag::err_duplicate_ivar_declaration);
20367 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20368 continue;
20369 }
20370 }
20371 }
20372 ClsFields[i]->setLexicalDeclContext(CDecl);
20373 CDecl->addDecl(ClsFields[i]);
20374 }
20375 CDecl->setIvarLBraceLoc(LBrac);
20376 CDecl->setIvarRBraceLoc(RBrac);
20377 }
20378 }
20381}
20382
20383// Given an integral type, return the next larger integral type
20384// (or a NULL type of no such type exists).
20386 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20387 // enum checking below.
20388 assert((T->isIntegralType(Context) ||
20389 T->isEnumeralType()) && "Integral type required!");
20390 const unsigned NumTypes = 4;
20391 QualType SignedIntegralTypes[NumTypes] = {
20392 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20393 };
20394 QualType UnsignedIntegralTypes[NumTypes] = {
20395 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20396 Context.UnsignedLongLongTy
20397 };
20398
20399 unsigned BitWidth = Context.getTypeSize(T);
20400 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20401 : UnsignedIntegralTypes;
20402 for (unsigned I = 0; I != NumTypes; ++I)
20403 if (Context.getTypeSize(Types[I]) > BitWidth)
20404 return Types[I];
20405
20406 return QualType();
20407}
20408
20410 EnumConstantDecl *LastEnumConst,
20411 SourceLocation IdLoc,
20412 IdentifierInfo *Id,
20413 Expr *Val) {
20414 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20415 llvm::APSInt EnumVal(IntWidth);
20416 QualType EltTy;
20417
20419 Val = nullptr;
20420
20421 if (Val)
20422 Val = DefaultLvalueConversion(Val).get();
20423
20424 if (Val) {
20425 if (Enum->isDependentType() || Val->isTypeDependent() ||
20426 Val->containsErrors())
20427 EltTy = Context.DependentTy;
20428 else {
20429 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20430 // underlying type, but do allow it in all other contexts.
20431 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20432 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20433 // constant-expression in the enumerator-definition shall be a converted
20434 // constant expression of the underlying type.
20435 EltTy = Enum->getIntegerType();
20437 Val, EltTy, EnumVal, CCEKind::Enumerator);
20438 if (Converted.isInvalid())
20439 Val = nullptr;
20440 else
20441 Val = Converted.get();
20442 } else if (!Val->isValueDependent() &&
20443 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20445 .get())) {
20446 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20447 } else {
20448 if (Enum->isComplete()) {
20449 EltTy = Enum->getIntegerType();
20450
20451 // In Obj-C and Microsoft mode, require the enumeration value to be
20452 // representable in the underlying type of the enumeration. In C++11,
20453 // we perform a non-narrowing conversion as part of converted constant
20454 // expression checking.
20455 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20456 if (Context.getTargetInfo()
20457 .getTriple()
20458 .isWindowsMSVCEnvironment()) {
20459 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20460 } else {
20461 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20462 }
20463 }
20464
20465 // Cast to the underlying type.
20466 Val = ImpCastExprToType(Val, EltTy,
20467 EltTy->isBooleanType() ? CK_IntegralToBoolean
20468 : CK_IntegralCast)
20469 .get();
20470 } else if (getLangOpts().CPlusPlus) {
20471 // C++11 [dcl.enum]p5:
20472 // If the underlying type is not fixed, the type of each enumerator
20473 // is the type of its initializing value:
20474 // - If an initializer is specified for an enumerator, the
20475 // initializing value has the same type as the expression.
20476 EltTy = Val->getType();
20477 } else {
20478 // C99 6.7.2.2p2:
20479 // The expression that defines the value of an enumeration constant
20480 // shall be an integer constant expression that has a value
20481 // representable as an int.
20482
20483 // Complain if the value is not representable in an int.
20484 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20485 Diag(IdLoc, getLangOpts().C23
20486 ? diag::warn_c17_compat_enum_value_not_int
20487 : diag::ext_c23_enum_value_not_int)
20488 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20489 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20490 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20491 // Force the type of the expression to 'int'.
20492 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20493 }
20494 EltTy = Val->getType();
20495 }
20496 }
20497 }
20498 }
20499
20500 if (!Val) {
20501 if (Enum->isDependentType())
20502 EltTy = Context.DependentTy;
20503 else if (!LastEnumConst) {
20504 // C++0x [dcl.enum]p5:
20505 // If the underlying type is not fixed, the type of each enumerator
20506 // is the type of its initializing value:
20507 // - If no initializer is specified for the first enumerator, the
20508 // initializing value has an unspecified integral type.
20509 //
20510 // GCC uses 'int' for its unspecified integral type, as does
20511 // C99 6.7.2.2p3.
20512 if (Enum->isFixed()) {
20513 EltTy = Enum->getIntegerType();
20514 }
20515 else {
20516 EltTy = Context.IntTy;
20517 }
20518 } else {
20519 // Assign the last value + 1.
20520 EnumVal = LastEnumConst->getInitVal();
20521 ++EnumVal;
20522 EltTy = LastEnumConst->getType();
20523
20524 // Check for overflow on increment.
20525 if (EnumVal < LastEnumConst->getInitVal()) {
20526 // C++0x [dcl.enum]p5:
20527 // If the underlying type is not fixed, the type of each enumerator
20528 // is the type of its initializing value:
20529 //
20530 // - Otherwise the type of the initializing value is the same as
20531 // the type of the initializing value of the preceding enumerator
20532 // unless the incremented value is not representable in that type,
20533 // in which case the type is an unspecified integral type
20534 // sufficient to contain the incremented value. If no such type
20535 // exists, the program is ill-formed.
20537 if (T.isNull() || Enum->isFixed()) {
20538 // There is no integral type larger enough to represent this
20539 // value. Complain, then allow the value to wrap around.
20540 EnumVal = LastEnumConst->getInitVal();
20541 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20542 ++EnumVal;
20543 if (Enum->isFixed())
20544 // When the underlying type is fixed, this is ill-formed.
20545 Diag(IdLoc, diag::err_enumerator_wrapped)
20546 << toString(EnumVal, 10)
20547 << EltTy;
20548 else
20549 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20550 << toString(EnumVal, 10);
20551 } else {
20552 EltTy = T;
20553 }
20554
20555 // Retrieve the last enumerator's value, extent that type to the
20556 // type that is supposed to be large enough to represent the incremented
20557 // value, then increment.
20558 EnumVal = LastEnumConst->getInitVal();
20559 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20560 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20561 ++EnumVal;
20562
20563 // If we're not in C++, diagnose the overflow of enumerator values,
20564 // which in C99 means that the enumerator value is not representable in
20565 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20566 // are representable in some larger integral type and we allow it in
20567 // older language modes as an extension.
20568 // Exclude fixed enumerators since they are diagnosed with an error for
20569 // this case.
20570 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20571 Diag(IdLoc, getLangOpts().C23
20572 ? diag::warn_c17_compat_enum_value_not_int
20573 : diag::ext_c23_enum_value_not_int)
20574 << 1 << toString(EnumVal, 10) << 1;
20575 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20576 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20577 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20578 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20579 : diag::ext_c23_enum_value_not_int)
20580 << 1 << toString(EnumVal, 10) << 1;
20581 }
20582 }
20583 }
20584
20585 if (!EltTy->isDependentType()) {
20586 // Make the enumerator value match the signedness and size of the
20587 // enumerator's type.
20588 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20589 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20590 }
20591
20592 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20593 Val, EnumVal);
20594}
20595
20597 SourceLocation IILoc) {
20598 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20600 return SkipBodyInfo();
20601
20602 // We have an anonymous enum definition. Look up the first enumerator to
20603 // determine if we should merge the definition with an existing one and
20604 // skip the body.
20605 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20607 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20608 if (!PrevECD)
20609 return SkipBodyInfo();
20610
20611 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20612 NamedDecl *Hidden;
20613 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20615 Skip.Previous = Hidden;
20616 return Skip;
20617 }
20618
20619 return SkipBodyInfo();
20620}
20621
20622Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20623 SourceLocation IdLoc, IdentifierInfo *Id,
20624 const ParsedAttributesView &Attrs,
20625 SourceLocation EqualLoc, Expr *Val,
20626 SkipBodyInfo *SkipBody) {
20627 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20628 EnumConstantDecl *LastEnumConst =
20629 cast_or_null<EnumConstantDecl>(lastEnumConst);
20630
20631 // The scope passed in may not be a decl scope. Zip up the scope tree until
20632 // we find one that is.
20633 S = getNonFieldDeclScope(S);
20634
20635 // Verify that there isn't already something declared with this name in this
20636 // scope.
20637 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20639 LookupName(R, S);
20640 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20641
20642 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20643 // Maybe we will complain about the shadowed template parameter.
20644 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20645 // Just pretend that we didn't see the previous declaration.
20646 PrevDecl = nullptr;
20647 }
20648
20649 // C++ [class.mem]p15:
20650 // If T is the name of a class, then each of the following shall have a name
20651 // different from T:
20652 // - every enumerator of every member of class T that is an unscoped
20653 // enumerated type
20654 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20656 DeclarationNameInfo(Id, IdLoc)))
20657 return nullptr;
20658
20660 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20661 if (!New)
20662 return nullptr;
20663
20664 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20665 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20666 // Check for other kinds of shadowing not already handled.
20667 CheckShadow(New, PrevDecl, R);
20668 }
20669
20670 // When in C++, we may get a TagDecl with the same name; in this case the
20671 // enum constant will 'hide' the tag.
20672 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20673 "Received TagDecl when not in C++!");
20674 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20675 if (isa<EnumConstantDecl>(PrevDecl))
20676 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20677 else
20678 Diag(IdLoc, diag::err_redefinition) << Id;
20679 notePreviousDefinition(PrevDecl, IdLoc);
20680 return nullptr;
20681 }
20682 }
20683
20684 // Process attributes.
20685 ProcessDeclAttributeList(S, New, Attrs);
20688
20689 // Register this decl in the current scope stack.
20690 New->setAccess(TheEnumDecl->getAccess());
20692
20694
20695 return New;
20696}
20697
20698// Returns true when the enum initial expression does not trigger the
20699// duplicate enum warning. A few common cases are exempted as follows:
20700// Element2 = Element1
20701// Element2 = Element1 + 1
20702// Element2 = Element1 - 1
20703// Where Element2 and Element1 are from the same enum.
20705 Expr *InitExpr = ECD->getInitExpr();
20706 if (!InitExpr)
20707 return true;
20708 InitExpr = InitExpr->IgnoreImpCasts();
20709
20710 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20711 if (!BO->isAdditiveOp())
20712 return true;
20713 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20714 if (!IL)
20715 return true;
20716 if (IL->getValue() != 1)
20717 return true;
20718
20719 InitExpr = BO->getLHS();
20720 }
20721
20722 // This checks if the elements are from the same enum.
20723 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20724 if (!DRE)
20725 return true;
20726
20727 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20728 if (!EnumConstant)
20729 return true;
20730
20732 Enum)
20733 return true;
20734
20735 return false;
20736}
20737
20738// Emits a warning when an element is implicitly set a value that
20739// a previous element has already been set to.
20741 EnumDecl *Enum, QualType EnumType) {
20742 // Avoid anonymous enums
20743 if (!Enum->getIdentifier())
20744 return;
20745
20746 // Only check for small enums.
20747 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20748 return;
20749
20750 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20751 return;
20752
20753 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20754 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20755
20756 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20757
20758 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20759 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20760
20761 // Use int64_t as a key to avoid needing special handling for map keys.
20762 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20763 llvm::APSInt Val = D->getInitVal();
20764 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20765 };
20766
20767 DuplicatesVector DupVector;
20768 ValueToVectorMap EnumMap;
20769
20770 // Populate the EnumMap with all values represented by enum constants without
20771 // an initializer.
20772 for (auto *Element : Elements) {
20773 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20774
20775 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20776 // this constant. Skip this enum since it may be ill-formed.
20777 if (!ECD) {
20778 return;
20779 }
20780
20781 // Constants with initializers are handled in the next loop.
20782 if (ECD->getInitExpr())
20783 continue;
20784
20785 // Duplicate values are handled in the next loop.
20786 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20787 }
20788
20789 if (EnumMap.size() == 0)
20790 return;
20791
20792 // Create vectors for any values that has duplicates.
20793 for (auto *Element : Elements) {
20794 // The last loop returned if any constant was null.
20796 if (!ValidDuplicateEnum(ECD, Enum))
20797 continue;
20798
20799 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20800 if (Iter == EnumMap.end())
20801 continue;
20802
20803 DeclOrVector& Entry = Iter->second;
20804 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20805 // Ensure constants are different.
20806 if (D == ECD)
20807 continue;
20808
20809 // Create new vector and push values onto it.
20810 auto Vec = std::make_unique<ECDVector>();
20811 Vec->push_back(D);
20812 Vec->push_back(ECD);
20813
20814 // Update entry to point to the duplicates vector.
20815 Entry = Vec.get();
20816
20817 // Store the vector somewhere we can consult later for quick emission of
20818 // diagnostics.
20819 DupVector.emplace_back(std::move(Vec));
20820 continue;
20821 }
20822
20823 ECDVector *Vec = cast<ECDVector *>(Entry);
20824 // Make sure constants are not added more than once.
20825 if (*Vec->begin() == ECD)
20826 continue;
20827
20828 Vec->push_back(ECD);
20829 }
20830
20831 // Emit diagnostics.
20832 for (const auto &Vec : DupVector) {
20833 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20834
20835 // Emit warning for one enum constant.
20836 auto *FirstECD = Vec->front();
20837 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20838 << FirstECD << toString(FirstECD->getInitVal(), 10)
20839 << FirstECD->getSourceRange();
20840
20841 // Emit one note for each of the remaining enum constants with
20842 // the same value.
20843 for (auto *ECD : llvm::drop_begin(*Vec))
20844 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20845 << ECD << toString(ECD->getInitVal(), 10)
20846 << ECD->getSourceRange();
20847 }
20848}
20849
20850bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20851 bool AllowMask) const {
20852 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20853 assert(ED->isCompleteDefinition() && "expected enum definition");
20854
20855 auto R = FlagBitsCache.try_emplace(ED);
20856 llvm::APInt &FlagBits = R.first->second;
20857
20858 if (R.second) {
20859 for (auto *E : ED->enumerators()) {
20860 const auto &EVal = E->getInitVal();
20861 // Only single-bit enumerators introduce new flag values.
20862 if (EVal.isPowerOf2())
20863 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20864 }
20865 }
20866
20867 // A value is in a flag enum if either its bits are a subset of the enum's
20868 // flag bits (the first condition) or we are allowing masks and the same is
20869 // true of its complement (the second condition). When masks are allowed, we
20870 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20871 //
20872 // While it's true that any value could be used as a mask, the assumption is
20873 // that a mask will have all of the insignificant bits set. Anything else is
20874 // likely a logic error.
20875 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20876 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20877}
20878
20879// Emits a warning when a suspicious comparison operator is used along side
20880// binary operators in enum initializers.
20882 const EnumDecl *Enum) {
20883 bool HasBitwiseOp = false;
20884 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20885
20886 // Iterate over all the enum values, gather suspisious comparison ops and
20887 // whether any enum initialisers contain a binary operator.
20888 for (const auto *ECD : Enum->enumerators()) {
20889 const Expr *InitExpr = ECD->getInitExpr();
20890 if (!InitExpr)
20891 continue;
20892
20893 const Expr *E = InitExpr->IgnoreParenImpCasts();
20894
20895 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
20896 BinaryOperatorKind Op = BinOp->getOpcode();
20897
20898 // Check for bitwise ops (<<, >>, &, |)
20899 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20900 HasBitwiseOp = true;
20901 } else if (Op == BO_LT || Op == BO_GT) {
20902 // Check for the typo pattern (Comparison < or >)
20903 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20904 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
20905 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20906 if (IntLiteral->getValue() == 1)
20907 SuspiciousCompares.push_back(BinOp);
20908 }
20909 }
20910 }
20911 }
20912
20913 // If we found a bitwise op and some sus compares, iterate over the compares
20914 // and warn.
20915 if (HasBitwiseOp) {
20916 for (const auto *BinOp : SuspiciousCompares) {
20917 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20920 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20921
20922 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
20923 << BinOp->getOpcodeStr() << SuggestedOp;
20924
20925 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
20926 << SuggestedOp
20927 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
20928 }
20929 }
20930}
20931
20933 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20934 const ParsedAttributesView &Attrs) {
20935 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20936 CanQualType EnumType = Context.getCanonicalTagType(Enum);
20937
20938 ProcessDeclAttributeList(S, Enum, Attrs);
20940
20941 if (Enum->isDependentType()) {
20942 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20943 EnumConstantDecl *ECD =
20944 cast_or_null<EnumConstantDecl>(Elements[i]);
20945 if (!ECD) continue;
20946
20947 ECD->setType(EnumType);
20948 }
20949
20950 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20951 return;
20952 }
20953
20954 // Verify that all the values are okay, compute the size of the values, and
20955 // reverse the list.
20956 unsigned NumNegativeBits = 0;
20957 unsigned NumPositiveBits = 0;
20958 bool MembersRepresentableByInt =
20959 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
20960
20961 // Figure out the type that should be used for this enum.
20962 QualType BestType;
20963 unsigned BestWidth;
20964
20965 // C++0x N3000 [conv.prom]p3:
20966 // An rvalue of an unscoped enumeration type whose underlying
20967 // type is not fixed can be converted to an rvalue of the first
20968 // of the following types that can represent all the values of
20969 // the enumeration: int, unsigned int, long int, unsigned long
20970 // int, long long int, or unsigned long long int.
20971 // C99 6.4.4.3p2:
20972 // An identifier declared as an enumeration constant has type int.
20973 // The C99 rule is modified by C23.
20974 QualType BestPromotionType;
20975
20976 bool Packed = Enum->hasAttr<PackedAttr>();
20977 // -fshort-enums is the equivalent to specifying the packed attribute on all
20978 // enum definitions.
20979 if (LangOpts.ShortEnums)
20980 Packed = true;
20981
20982 // If the enum already has a type because it is fixed or dictated by the
20983 // target, promote that type instead of analyzing the enumerators.
20984 if (Enum->isComplete()) {
20985 BestType = Enum->getIntegerType();
20986 if (Context.isPromotableIntegerType(BestType))
20987 BestPromotionType = Context.getPromotedIntegerType(BestType);
20988 else
20989 BestPromotionType = BestType;
20990
20991 BestWidth = Context.getIntWidth(BestType);
20992 } else {
20993 bool EnumTooLarge = Context.computeBestEnumTypes(
20994 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20995 BestWidth = Context.getIntWidth(BestType);
20996 if (EnumTooLarge)
20997 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20998 }
20999
21000 // Loop over all of the enumerator constants, changing their types to match
21001 // the type of the enum if needed.
21002 for (auto *D : Elements) {
21003 auto *ECD = cast_or_null<EnumConstantDecl>(D);
21004 if (!ECD) continue; // Already issued a diagnostic.
21005
21006 // C99 says the enumerators have int type, but we allow, as an
21007 // extension, the enumerators to be larger than int size. If each
21008 // enumerator value fits in an int, type it as an int, otherwise type it the
21009 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21010 // that X has type 'int', not 'unsigned'.
21011
21012 // Determine whether the value fits into an int.
21013 llvm::APSInt InitVal = ECD->getInitVal();
21014
21015 // If it fits into an integer type, force it. Otherwise force it to match
21016 // the enum decl type.
21017 QualType NewTy;
21018 unsigned NewWidth;
21019 bool NewSign;
21020 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21021 MembersRepresentableByInt) {
21022 // C23 6.7.3.3.3p15:
21023 // The enumeration member type for an enumerated type without fixed
21024 // underlying type upon completion is:
21025 // - int if all the values of the enumeration are representable as an
21026 // int; or,
21027 // - the enumerated type
21028 NewTy = Context.IntTy;
21029 NewWidth = Context.getTargetInfo().getIntWidth();
21030 NewSign = true;
21031 } else if (ECD->getType() == BestType) {
21032 // Already the right type!
21033 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21034 // C++ [dcl.enum]p4: Following the closing brace of an
21035 // enum-specifier, each enumerator has the type of its
21036 // enumeration.
21037 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21038 // with fixed underlying type is the enumerated type.
21039 ECD->setType(EnumType);
21040 continue;
21041 } else {
21042 NewTy = BestType;
21043 NewWidth = BestWidth;
21044 NewSign = BestType->isSignedIntegerOrEnumerationType();
21045 }
21046
21047 // Adjust the APSInt value.
21048 InitVal = InitVal.extOrTrunc(NewWidth);
21049 InitVal.setIsSigned(NewSign);
21050 ECD->setInitVal(Context, InitVal);
21051
21052 // Adjust the Expr initializer and type.
21053 if (ECD->getInitExpr() &&
21054 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
21055 ECD->setInitExpr(ImplicitCastExpr::Create(
21056 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
21057 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
21058 if (getLangOpts().CPlusPlus ||
21059 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21060 // C++ [dcl.enum]p4: Following the closing brace of an
21061 // enum-specifier, each enumerator has the type of its
21062 // enumeration.
21063 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21064 // with fixed underlying type is the enumerated type.
21065 ECD->setType(EnumType);
21066 else
21067 ECD->setType(NewTy);
21068 }
21069
21070 Enum->completeDefinition(BestType, BestPromotionType,
21071 NumPositiveBits, NumNegativeBits);
21072
21073 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
21075
21076 if (Enum->isClosedFlag()) {
21077 for (Decl *D : Elements) {
21078 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
21079 if (!ECD) continue; // Already issued a diagnostic.
21080
21081 llvm::APSInt InitVal = ECD->getInitVal();
21082 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21083 !IsValueInFlagEnum(Enum, InitVal, true))
21084 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
21085 << ECD << Enum;
21086 }
21087 }
21088
21089 // Now that the enum type is defined, ensure it's not been underaligned.
21090 if (Enum->hasAttrs())
21092}
21093
21095 SourceLocation EndLoc) {
21096
21098 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
21099 CurContext->addDecl(New);
21100 return New;
21101}
21102
21104 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
21105 CurContext->addDecl(New);
21106 PushDeclContext(S, New);
21108 PushCompoundScope(false);
21109 return New;
21110}
21111
21113 if (Statement)
21114 D->setStmt(Statement);
21118}
21119
21121 IdentifierInfo* AliasName,
21122 SourceLocation PragmaLoc,
21123 SourceLocation NameLoc,
21124 SourceLocation AliasNameLoc) {
21125 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
21127 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21129 AsmLabelAttr *Attr =
21130 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
21131
21132 // If a declaration that:
21133 // 1) declares a function or a variable
21134 // 2) has external linkage
21135 // already exists, add a label attribute to it.
21136 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21137 if (isDeclExternC(PrevDecl))
21138 PrevDecl->addAttr(Attr);
21139 else
21140 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
21141 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
21142 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21143 } else
21144 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
21145}
21146
21148 SourceLocation PragmaLoc,
21149 SourceLocation NameLoc) {
21150 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
21151
21152 if (PrevDecl) {
21153 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
21154 } else {
21155 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
21156 }
21157}
21158
21160 IdentifierInfo* AliasName,
21161 SourceLocation PragmaLoc,
21162 SourceLocation NameLoc,
21163 SourceLocation AliasNameLoc) {
21164 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
21166 WeakInfo W = WeakInfo(Name, NameLoc);
21167
21168 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21169 if (!PrevDecl->hasAttr<AliasAttr>())
21170 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
21172 } else {
21173 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
21174 }
21175}
21176
21178 bool Final) {
21179 assert(FD && "Expected non-null FunctionDecl");
21180
21181 // Templates are emitted when they're instantiated.
21182 if (FD->isDependentContext())
21184
21185 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21186 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21187 FD->hasAttr<SYCLExternalAttr>()))
21189
21190 // Check whether this function is an externally visible definition.
21191 auto IsEmittedForExternalSymbol = [this, FD]() {
21192 // We have to check the GVA linkage of the function's *definition* -- if we
21193 // only have a declaration, we don't know whether or not the function will
21194 // be emitted, because (say) the definition could include "inline".
21195 const FunctionDecl *Def = FD->getDefinition();
21196
21197 // We can't compute linkage when we skip function bodies.
21198 return Def && !Def->hasSkippedBody() &&
21200 getASTContext().GetGVALinkageForFunction(Def));
21201 };
21202
21203 if (LangOpts.OpenMPIsTargetDevice) {
21204 // In OpenMP device mode we will not emit host only functions, or functions
21205 // we don't need due to their linkage.
21206 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21207 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21208 // DevTy may be changed later by
21209 // #pragma omp declare target to(*) device_type(*).
21210 // Therefore DevTy having no value does not imply host. The emission status
21211 // will be checked again at the end of compilation unit with Final = true.
21212 if (DevTy)
21213 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21215 // If we have an explicit value for the device type, or we are in a target
21216 // declare context, we need to emit all extern and used symbols.
21217 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21218 if (IsEmittedForExternalSymbol())
21220 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21221 // we'll omit it.
21222 if (Final)
21224 } else if (LangOpts.OpenMP > 45) {
21225 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21226 // function. In 5.0, no_host was introduced which might cause a function to
21227 // be omitted.
21228 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21229 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21230 if (DevTy)
21231 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21233 }
21234
21235 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21237
21238 if (LangOpts.CUDA) {
21239 // When compiling for device, host functions are never emitted. Similarly,
21240 // when compiling for host, device and global functions are never emitted.
21241 // (Technically, we do emit a host-side stub for global functions, but this
21242 // doesn't count for our purposes here.)
21244 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21246 if (!LangOpts.CUDAIsDevice &&
21249
21250 if (IsEmittedForExternalSymbol())
21252
21253 // If FD is a virtual destructor of an explicit instantiation
21254 // of a template class, return Emitted.
21255 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(FD)) {
21256 if (Destructor->isVirtual()) {
21257 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
21258 Destructor->getParent())) {
21260 Spec->getTemplateSpecializationKind();
21264 }
21265 }
21266 }
21267 }
21268
21269 // Otherwise, the function is known-emitted if it's in our set of
21270 // known-emitted functions.
21272}
21273
21275 // Host-side references to a __global__ function refer to the stub, so the
21276 // function itself is never emitted and therefore should not be marked.
21277 // If we have host fn calls kernel fn calls host+device, the HD function
21278 // does not get instantiated on the host. We model this by omitting at the
21279 // call to the kernel from the callgraph. This ensures that, when compiling
21280 // for host, only HD functions actually called from the host get marked as
21281 // known-emitted.
21282 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21284}
21285
21287 bool &Visible) {
21288 Visible = hasVisibleDefinition(D, Suggested);
21289 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21290 // for declaratins which is attached to named modules.
21291 // We only did this if the current module is named module as we have better
21292 // diagnostics for declarations in global module and named modules.
21293 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21294 D->isInNamedModule())
21295 return false;
21296 // The redefinition of D in the **current** TU is allowed if D is invisible or
21297 // D is defined in the global module of other module units.
21298 return D->isInAnotherModuleUnit() || !Visible;
21299}
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:80
#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:227
SourceManager & getSourceManager()
Definition ASTContext.h:866
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:805
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
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:924
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:3551
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:3784
QualType getElementType() const
Definition TypeBase.h:3796
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:4510
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4498
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
Expr * getLHS() const
Definition Expr.h:4091
StringRef getOpcodeStr() const
Definition Expr.h:4107
Expr * getRHS() const
Definition Expr.h:4093
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4182
A binding in a decomposition declaration.
Definition DeclCXX.h:4190
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4690
bool doesNotEscape() const
Definition Decl.h:4841
This class is used for builtin types like 'int'.
Definition TypeBase.h:3226
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:2620
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:3060
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:3020
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2952
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:3275
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:2385
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
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:3150
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:2132
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:2721
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition DeclCXX.cpp:2807
bool isVirtual() const
Definition DeclCXX.h:2187
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:2506
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2872
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2271
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2753
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2306
bool isConst() const
Definition DeclCXX.h:2184
bool isStatic() const
Definition DeclCXX.cpp:2419
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2732
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2241
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:132
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:1372
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1560
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:1097
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1148
bool hasDefinition() const
Definition DeclCXX.h:561
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2052
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2156
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1059
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1119
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2056
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:3150
bool isCallToStdMove() const
Definition Expr.cpp:3649
Expr * getCallee()
Definition Expr.h:3093
arg_range arguments()
Definition Expr.h:3198
CastKind getCastKind() const
Definition Expr.h:3723
Expr * getSubExpr()
Definition Expr.h:3729
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:3822
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:3878
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:355
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:1405
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
bool isFileContext() const
Definition DeclBase.h:2193
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2590
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:2155
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2138
bool isNamespace() const
Definition DeclBase.h:2211
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:2198
bool isRecord() const
Definition DeclBase.h:2202
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:2386
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
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:2115
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:1273
ValueDecl * getDecl()
Definition Expr.h:1341
SourceLocation getBeginLoc() const
Definition Expr.h:1352
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:655
bool isModulePrivateSpecified() const
Definition DeclSpec.h:836
static const TST TST_typeof_unqualType
Definition DeclSpec.h:282
bool hasAutoTypeSpec() const
Definition DeclSpec.h:580
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:500
bool isNoreturnSpecified() const
Definition DeclSpec.h:668
TST getTypeSpecType() const
Definition DeclSpec.h:522
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:495
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:846
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:716
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:602
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:715
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:669
bool isExternInLinkageSpec() const
Definition DeclSpec.h:490
static const TST TST_union
Definition DeclSpec.h:275
SCS
storage-class-specifier
Definition DeclSpec.h:224
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:661
static const TST TST_int
Definition DeclSpec.h:258
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:837
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:532
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:795
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:487
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:631
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:603
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:662
Expr * getRepAsExpr() const
Definition DeclSpec.h:540
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:453
bool isInlineSpecified() const
Definition DeclSpec.h:644
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:604
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:848
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:496
Decl * getRepAsDecl() const
Definition DeclSpec.h:536
static const TST TST_unspecified
Definition DeclSpec.h:251
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:606
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:656
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:843
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:567
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:799
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:651
bool isTypeSpecOwned() const
Definition DeclSpec.h:526
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:647
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:607
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:605
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:828
bool hasExplicitSpecifier() const
Definition DeclSpec.h:658
bool hasConstexprSpecifier() const
Definition DeclSpec.h:844
static const TST TST_typeofType
Definition DeclSpec.h:280
static const TST TST_auto
Definition DeclSpec.h:291
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:839
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:1074
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1089
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:341
bool isInStdNamespace() const
Definition DeclBase.cpp:450
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:1239
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:547
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:779
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:1164
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:906
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1232
@ FOK_None
Not a friend object.
Definition DeclBase.h:1230
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1231
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:601
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:850
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:1193
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2806
bool isInvalidDecl() const
Definition DeclBase.h:596
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1182
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:576
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:382
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:931
bool hasAttr() const
Definition DeclBase.h:585
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1248
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
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:1948
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2504
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2446
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2095
Expr * getAsmLabel() const
Definition DeclSpec.h:2750
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2789
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2731
void setRedeclaration(bool Val)
Definition DeclSpec.h:2812
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2384
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2387
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2132
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2681
void takeAttributesAppending(ParsedAttributes &attrs)
takeAttributesAppending - Takes attributes from the given ParsedAttributes set and add them to this d...
Definition DeclSpec.h:2724
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2761
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2711
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2442
bool isRedeclaration() const
Definition DeclSpec.h:2813
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2734
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2116
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2131
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:410
bool isFunctionDefinition() const
Definition DeclSpec.h:2785
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2114
bool hasInitializer() const
Definition DeclSpec.h:2794
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2781
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2110
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2401
bool isInvalidType() const
Definition DeclSpec.h:2762
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2130
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2374
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2797
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:2102
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2535
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2378
A decomposition declaration.
Definition DeclCXX.h:4254
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3734
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1836
SourceRange getSourceRange() const
Definition DeclSpec.h:1884
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1882
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:233
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:960
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3441
llvm::APSInt getInitVal() const
Definition Decl.h:3461
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5711
const Expr * getInitExpr() const
Definition Decl.h:3459
Represents an enum.
Definition Decl.h:4029
enumerator_range enumerators() const
Definition Decl.h:4175
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4247
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4211
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4214
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4261
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5069
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5108
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4256
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5083
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4197
void setEnumKeyRange(SourceRange Range)
Definition Decl.h:4109
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4202
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1931
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:3097
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:3093
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:3354
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:3077
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:282
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:3178
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3281
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4710
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3414
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:4695
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4756
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5844
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
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:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
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:104
Represents a function declaration or definition.
Definition Decl.h:2018
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2707
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:2207
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2494
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4200
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3728
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4193
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4188
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3293
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2332
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2719
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2698
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4019
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3757
param_iterator param_end()
Definition Decl.h:2805
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2939
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2713
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3701
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2407
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2395
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3609
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4308
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2466
void setWillHaveBody(bool V=true)
Definition Decl.h:2704
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition Decl.h:2612
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2461
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4318
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3742
param_iterator param_begin()
Definition Decl.h:2804
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2841
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2344
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2558
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3152
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3370
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4252
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2906
bool isStatic() const
Definition Decl.h:2947
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4521
void setTrivial(bool IT)
Definition Decl.h:2396
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4139
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:2488
bool isDeletedAsWritten() const
Definition Decl.h:2562
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2371
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3613
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2375
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:2446
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2367
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2697
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2300
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3363
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2934
bool param_empty() const
Definition Decl.h:2803
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3218
void setRangeEnd(SourceLocation E)
Definition Decl.h:2236
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3697
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2403
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2439
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4544
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2951
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4133
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2491
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4412
void setDefaulted(bool D=true)
Definition Decl.h:2404
bool isConsteval() const
Definition Decl.h:2500
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:2880
void setBody(Stmt *B)
Definition Decl.cpp:3286
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3627
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3164
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2477
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4160
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3821
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2229
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3194
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2453
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:3241
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:2917
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3683
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2703
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5305
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5337
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5868
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5169
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5369
unsigned getNumParams() const
Definition TypeBase.h:5647
QualType getParamType(unsigned i) const
Definition TypeBase.h:5649
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5866
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5682
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5773
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5658
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5654
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:4676
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4788
CallingConv getCC() const
Definition TypeBase.h:4735
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4754
unsigned getRegParm() const
Definition TypeBase.h:4728
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4724
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4747
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4768
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4782
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4565
ExtInfo getExtInfo() const
Definition TypeBase.h:4921
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3700
unsigned getRegParmType() const
Definition TypeBase.h:4908
CallingConv getCallConv() const
Definition TypeBase.h:4920
QualType getReturnType() const
Definition TypeBase.h:4905
bool getCmseNSCallAttr() const
Definition TypeBase.h:4919
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:2078
Represents a C array with an unspecified size.
Definition TypeBase.h:3971
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3485
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5738
void setInherited(bool I)
Definition Attr.h:161
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2591
child_range children()
Definition Expr.h:5498
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:980
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:1432
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3020
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3305
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:3450
Expr * getBase() const
Definition Expr.h:3444
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3715
Describes a module or submodule.
Definition Module.h:301
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:307
Module * Parent
The parent of this module.
Definition Module.h:350
bool isPrivateModule() const
Definition Module.h:409
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:827
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:843
bool isModulePartition() const
Is this a module partition.
Definition Module.h:832
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:239
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:384
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:901
@ 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:714
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:277
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:3364
Represents a parameter to a function.
Definition Decl.h:1808
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1868
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1872
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1841
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1900
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:2952
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2975
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:8263
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:3390
QualType getPointeeType() const
Definition TypeBase.h:3400
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:8529
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8523
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:3019
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:3085
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8445
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8571
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:8485
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getCanonicalType() const
Definition TypeBase.h:8497
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8539
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:3069
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:8518
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8566
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:8502
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:2788
@ 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:8385
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8392
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4788
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:4343
field_range fields() const
Definition Decl.h:4546
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5227
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4543
field_iterator field_begin() const
Definition Decl.cpp:5270
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7503
void setMemberSpecialization()
Note that this member template is a specialization.
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:5348
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3635
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:409
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:428
unsigned getDepth() const
Returns the depth of this scope. The translation-unit has scope depth 0.
Definition Scope.h:339
unsigned getNextFunctionPrototypeIndex()
Return the number of parameters declared in this function prototype, increasing it by one for the nex...
Definition Scope.h:349
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:291
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
bool isTypeAliasScope() const
Determine whether this scope is a type alias scope.
Definition Scope.h:628
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:398
void RemoveDecl(Decl *D)
Definition Scope.h:370
void setLookupEntity(DeclContext *E)
Definition Scope.h:414
unsigned getMSLastManglingNumber() const
Definition Scope.h:386
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
unsigned getMSCurManglingNumber() const
Definition Scope.h:392
bool decl_empty() const
Definition Scope.h:360
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:481
unsigned getFunctionPrototypeDepth() const
Returns the number of function prototype scopes in this scope chain.
Definition Scope.h:343
Scope * getDeclParent()
Definition Scope.h:335
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition Scope.h:619
decl_range decls() const
Definition Scope.h:356
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:287
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:487
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred within this scope.
Definition Scope.h:420
void applyNRVO()
Definition Scope.cpp:166
Scope * getTemplateParamParent()
Definition Scope.h:332
@ 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:1440
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:90
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:754
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:842
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:907
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:973
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:737
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:703
void deduceAddressSpace(VarDecl *Decl)
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:806
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:773
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:717
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:713
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:670
void CheckSYCLExternalFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:280
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:297
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:427
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:1919
Mode getAlignMode() const
Definition Sema.h:1921
A RAII object to temporarily push a declaration context.
Definition Sema.h:3526
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1386
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1398
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3747
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3757
static NameClassification Unknown()
Definition Sema.h:3727
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3731
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3775
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3763
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3737
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3769
static NameClassification UndeclaredNonType()
Definition Sema.h:3743
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3751
static NameClassification Error()
Definition Sema.h:3723
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12553
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12587
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
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:1448
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:3625
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13150
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2628
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1141
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:8330
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6389
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9413
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9417
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9436
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9452
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9449
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9425
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9420
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:1533
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:4797
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3607
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1845
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:6581
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:1473
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:938
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2076
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2070
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:4200
@ Delete
deleted-function-body
Definition Sema.h:4206
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 ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
SemaSYCL & SYCL()
Definition Sema.h:1558
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:1725
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)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ASTContext & Context
Definition Sema.h:1308
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:226
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2358
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void * SkippedDefinitionContext
Definition Sema.h:4424
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1518
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1373
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:2073
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:3615
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:939
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:2069
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:762
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:1212
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:1730
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:12251
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8448
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:2419
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:4635
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:934
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:2437
void PopCompoundScope()
Definition Sema.cpp:2570
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:14528
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14531
@ UPPC_Initializer
An initializer.
Definition Sema.h:14543
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14537
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14516
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14555
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14540
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14519
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14522
const LangOptions & getLangOpts() const
Definition Sema.h:932
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:2531
SourceLocation CurInitSegLoc
Definition Sema.h:2112
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:3632
SemaOpenACC & OpenACC()
Definition Sema.h:1523
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:1307
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
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:2209
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:1306
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:2646
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15624
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1483
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:1846
SemaRISCV & RISCV()
Definition Sema.h:1548
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:15801
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:215
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:1563
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:2058
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:7048
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2068
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1145
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:4812
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1341
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2565
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:7045
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...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:644
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:15618
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3603
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2111
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9943
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:1446
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1528
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:1705
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl)
CheckLiteralOperatorDeclaration - Check whether the declaration of this literal operator function is ...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
void applyFunctionAttributesBeforeParsingBody(Decl *FD)
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
void CleanupMergedEnum(Scope *S, Decl *New)
CleanupMergedEnum - We have just merged the decl 'New' by making another definition visible.
DeclContext * OriginalLexicalContext
Generally null except when we temporarily switch decl contexts, like in.
Definition Sema.h:3629
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT)
Determines if we can perform a correct type check for D as a redeclaration of PrevDecl.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14056
SourceManager & getSourceManager() const
Definition Sema.h:937
NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists)
llvm::DenseMap< const EnumDecl *, llvm::APInt > FlagBitsCache
A cache of the flags available in enumerations with the flag_bits attribute.
Definition Sema.h:3577
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
void diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, SourceLocation NewLoc, SourceLocation OldLoc)
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
PragmaClangSection PragmaClangTextSection
Definition Sema.h:1847
@ NTCUK_Destruct
Definition Sema.h:4139
@ NTCUK_Init
Definition Sema.h:4138
@ NTCUK_Copy
Definition Sema.h:4140
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1844
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLoc