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"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/Type.h"
37#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
38#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
39#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
40#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
42#include "clang/Sema/DeclSpec.h"
45#include "clang/Sema/Lookup.h"
47#include "clang/Sema/Scope.h"
49#include "clang/Sema/SemaARM.h"
50#include "clang/Sema/SemaCUDA.h"
51#include "clang/Sema/SemaHLSL.h"
53#include "clang/Sema/SemaObjC.h"
56#include "clang/Sema/SemaPPC.h"
58#include "clang/Sema/SemaSYCL.h"
60#include "clang/Sema/SemaWasm.h"
61#include "clang/Sema/Template.h"
62#include "llvm/ADT/ArrayRef.h"
63#include "llvm/ADT/STLForwardCompat.h"
64#include "llvm/ADT/ScopeExit.h"
65#include "llvm/ADT/SmallPtrSet.h"
66#include "llvm/ADT/SmallString.h"
67#include "llvm/ADT/StringExtras.h"
68#include "llvm/ADT/StringRef.h"
69#include "llvm/Support/SaveAndRestore.h"
70#include "llvm/TargetParser/Triple.h"
71#include <algorithm>
72#include <cstring>
73#include <optional>
74#include <unordered_map>
75
76using namespace clang;
77using namespace sema;
78
80 if (OwnedType) {
81 Decl *Group[2] = { OwnedType, Ptr };
83 }
84
86}
87
88namespace {
89
90class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
91 public:
92 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
93 bool AllowTemplates = false,
94 bool AllowNonTemplates = true)
95 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
96 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
97 WantExpressionKeywords = false;
98 WantCXXNamedCasts = false;
99 WantRemainingKeywords = false;
100 }
101
102 bool ValidateCandidate(const TypoCorrection &candidate) override {
103 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
104 if (!AllowInvalidDecl && ND->isInvalidDecl())
105 return false;
106
107 if (getAsTypeTemplateDecl(ND))
108 return AllowTemplates;
109
110 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
111 if (!IsType)
112 return false;
113
114 if (AllowNonTemplates)
115 return true;
116
117 // An injected-class-name of a class template (specialization) is valid
118 // as a template or as a non-template.
119 if (AllowTemplates) {
120 auto *RD = dyn_cast<CXXRecordDecl>(ND);
121 if (!RD || !RD->isInjectedClassName())
122 return false;
123 RD = cast<CXXRecordDecl>(RD->getDeclContext());
124 return RD->getDescribedClassTemplate() ||
126 }
127
128 return false;
129 }
130
131 return !WantClassName && candidate.isKeyword();
132 }
133
134 std::unique_ptr<CorrectionCandidateCallback> clone() override {
135 return std::make_unique<TypeNameValidatorCCC>(*this);
136 }
137
138 private:
139 bool AllowInvalidDecl;
140 bool WantClassName;
141 bool AllowTemplates;
142 bool AllowNonTemplates;
143};
144
145} // end anonymous namespace
146
148 TypeDecl *TD, SourceLocation NameLoc) {
149 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
150 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
151 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
152 FoundRD->isInjectedClassName() &&
153 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
154 Diag(NameLoc,
156 ? diag::ext_out_of_line_qualified_id_type_names_constructor
157 : diag::err_out_of_line_qualified_id_type_names_constructor)
158 << TD->getIdentifier() << /*Type=*/1
159 << 0 /*if any keyword was present, it was 'typename'*/;
160 }
161
162 DiagnoseUseOfDecl(TD, NameLoc);
163 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
164}
165
166namespace {
167enum class UnqualifiedTypeNameLookupResult {
168 NotFound,
169 FoundNonType,
170 FoundType
171};
172} // end anonymous namespace
173
174/// Tries to perform unqualified lookup of the type decls in bases for
175/// dependent class.
176/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
177/// type decl, \a FoundType if only type decls are found.
178static UnqualifiedTypeNameLookupResult
180 SourceLocation NameLoc,
181 const CXXRecordDecl *RD) {
182 if (!RD->hasDefinition())
183 return UnqualifiedTypeNameLookupResult::NotFound;
184 // Look for type decls in base classes.
185 UnqualifiedTypeNameLookupResult FoundTypeDecl =
186 UnqualifiedTypeNameLookupResult::NotFound;
187 for (const auto &Base : RD->bases()) {
188 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
189 if (BaseRD) {
190 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
191 Base.getType().getCanonicalType())) {
192 // Look for type decls in dependent base classes that have known primary
193 // templates.
194 if (!TST->isDependentType())
195 continue;
196 auto *TD = TST->getTemplateName().getAsTemplateDecl();
197 if (!TD)
198 continue;
199 if (auto *BasePrimaryTemplate =
200 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
201 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
202 BaseRD = BasePrimaryTemplate;
203 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
205 CTD->findPartialSpecialization(Base.getType()))
206 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
207 BaseRD = PS;
208 }
209 }
210 }
211 if (BaseRD) {
212 for (NamedDecl *ND : BaseRD->lookup(&II)) {
213 if (!isa<TypeDecl>(ND))
214 return UnqualifiedTypeNameLookupResult::FoundNonType;
215 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
216 }
217 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
218 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
219 case UnqualifiedTypeNameLookupResult::FoundNonType:
220 return UnqualifiedTypeNameLookupResult::FoundNonType;
221 case UnqualifiedTypeNameLookupResult::FoundType:
222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
223 break;
224 case UnqualifiedTypeNameLookupResult::NotFound:
225 break;
226 }
227 }
228 }
229 }
230
231 return FoundTypeDecl;
232}
233
235 const IdentifierInfo &II,
236 SourceLocation NameLoc) {
237 // Lookup in the parent class template context, if any.
238 const CXXRecordDecl *RD = nullptr;
239 UnqualifiedTypeNameLookupResult FoundTypeDecl =
240 UnqualifiedTypeNameLookupResult::NotFound;
241 for (DeclContext *DC = S.CurContext;
242 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
243 DC = DC->getParent()) {
244 // Look for type decls in dependent base classes that have known primary
245 // templates.
246 RD = dyn_cast<CXXRecordDecl>(DC);
247 if (RD && RD->getDescribedClassTemplate())
248 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
249 }
250 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
251 return nullptr;
252
253 // We found some types in dependent base classes. Recover as if the user
254 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
255 // allowed. We'll fully resolve the lookup during template instantiation.
256 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
257
258 ASTContext &Context = S.Context;
259 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
260 QualType T =
261 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
262
263 CXXScopeSpec SS;
264 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
265
266 TypeLocBuilder Builder;
267 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
268 DepTL.setNameLoc(NameLoc);
270 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
271 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
272}
273
275 Scope *S, CXXScopeSpec *SS, bool isClassName,
276 bool HasTrailingDot, ParsedType ObjectTypePtr,
277 bool IsCtorOrDtorName,
278 bool WantNontrivialTypeSourceInfo,
279 bool IsClassTemplateDeductionContext,
280 ImplicitTypenameContext AllowImplicitTypename,
281 IdentifierInfo **CorrectedII) {
282 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
283 // FIXME: Consider allowing this outside C++1z mode as an extension.
284 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
285 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
286 !HasTrailingDot;
287
288 // Determine where we will perform name lookup.
289 DeclContext *LookupCtx = nullptr;
290 if (ObjectTypePtr) {
291 QualType ObjectType = ObjectTypePtr.get();
292 if (ObjectType->isRecordType())
293 LookupCtx = computeDeclContext(ObjectType);
294 } else if (SS && SS->isNotEmpty()) {
295 LookupCtx = computeDeclContext(*SS, false);
296
297 if (!LookupCtx) {
298 if (isDependentScopeSpecifier(*SS)) {
299 // C++ [temp.res]p3:
300 // A qualified-id that refers to a type and in which the
301 // nested-name-specifier depends on a template-parameter (14.6.2)
302 // shall be prefixed by the keyword typename to indicate that the
303 // qualified-id denotes a type, forming an
304 // elaborated-type-specifier (7.1.5.3).
305 //
306 // We therefore do not perform any name lookup if the result would
307 // refer to a member of an unknown specialization.
308 // In C++2a, in several contexts a 'typename' is not required. Also
309 // allow this as an extension.
310 if (IsImplicitTypename) {
311 if (AllowImplicitTypename == ImplicitTypenameContext::No)
312 return nullptr;
313 SourceLocation QualifiedLoc = SS->getRange().getBegin();
314 // FIXME: Defer the diagnostic after we build the type and use it.
315 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
316 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
317 SS->getScopeRep(), &II);
319 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
320 }
321
322 // We know from the grammar that this name refers to a type,
323 // so build a dependent node to describe the type.
324 if (WantNontrivialTypeSourceInfo)
325 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
326 (ImplicitTypenameContext)IsImplicitTypename)
327 .get();
328
331 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
333 SourceLocation(), QualifierLoc, II, NameLoc);
334 return ParsedType::make(T);
335 }
336
337 return nullptr;
338 }
339
340 if (!LookupCtx->isDependentContext() &&
341 RequireCompleteDeclContext(*SS, LookupCtx))
342 return nullptr;
343 }
344
345 // In the case where we know that the identifier is a class name, we know that
346 // it is a type declaration (struct, class, union or enum) so we can use tag
347 // name lookup.
348 //
349 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
350 // the component name of the type-name or simple-template-id is type-only.
351 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
352 LookupResult Result(*this, &II, NameLoc, Kind);
353 if (LookupCtx) {
354 // Perform "qualified" name lookup into the declaration context we
355 // computed, which is either the type of the base of a member access
356 // expression or the declaration context associated with a prior
357 // nested-name-specifier.
358 LookupQualifiedName(Result, LookupCtx);
359
360 if (ObjectTypePtr && Result.empty()) {
361 // C++ [basic.lookup.classref]p3:
362 // If the unqualified-id is ~type-name, the type-name is looked up
363 // in the context of the entire postfix-expression. If the type T of
364 // the object expression is of a class type C, the type-name is also
365 // looked up in the scope of class C. At least one of the lookups shall
366 // find a name that refers to (possibly cv-qualified) T.
367 LookupName(Result, S);
368 }
369 } else {
370 // Perform unqualified name lookup.
371 LookupName(Result, S);
372
373 // For unqualified lookup in a class template in MSVC mode, look into
374 // dependent base classes where the primary class template is known.
375 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
376 if (ParsedType TypeInBase =
377 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
378 return TypeInBase;
379 }
380 }
381
382 NamedDecl *IIDecl = nullptr;
383 UsingShadowDecl *FoundUsingShadow = nullptr;
384 switch (Result.getResultKind()) {
386 if (CorrectedII) {
387 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
388 AllowDeducedTemplate);
389 TypoCorrection Correction =
390 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
392 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
394 bool MemberOfUnknownSpecialization;
396 TemplateName.setIdentifier(NewII, NameLoc);
398 CXXScopeSpec NewSS, *NewSSPtr = SS;
399 if (SS && NNS) {
400 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
401 NewSSPtr = &NewSS;
402 }
403 if (Correction && (NNS || NewII != &II) &&
404 // Ignore a correction to a template type as the to-be-corrected
405 // identifier is not a template (typo correction for template names
406 // is handled elsewhere).
407 !(getLangOpts().CPlusPlus && NewSSPtr &&
408 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
409 Template, MemberOfUnknownSpecialization))) {
410 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
411 isClassName, HasTrailingDot, ObjectTypePtr,
412 IsCtorOrDtorName,
413 WantNontrivialTypeSourceInfo,
414 IsClassTemplateDeductionContext);
415 if (Ty) {
416 diagnoseTypo(Correction,
417 PDiag(diag::err_unknown_type_or_class_name_suggest)
418 << Result.getLookupName() << isClassName);
419 if (SS && NNS)
420 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
421 *CorrectedII = NewII;
422 return Ty;
423 }
424 }
425 }
426 Result.suppressDiagnostics();
427 return nullptr;
429 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
430 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
431 SS->getScopeRep(), &II);
432 TypeLocBuilder TLB;
436 TL.setNameLoc(NameLoc);
437 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
438 }
439 [[fallthrough]];
442 Result.suppressDiagnostics();
443 return nullptr;
444
446 // Recover from type-hiding ambiguities by hiding the type. We'll
447 // do the lookup again when looking for an object, and we can
448 // diagnose the error then. If we don't do this, then the error
449 // about hiding the type will be immediately followed by an error
450 // that only makes sense if the identifier was treated like a type.
451 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
452 Result.suppressDiagnostics();
453 return nullptr;
454 }
455
456 // Look to see if we have a type anywhere in the list of results.
457 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
458 Res != ResEnd; ++Res) {
459 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
461 RealRes) ||
462 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
463 if (!IIDecl ||
464 // Make the selection of the recovery decl deterministic.
465 RealRes->getLocation() < IIDecl->getLocation()) {
466 IIDecl = RealRes;
467 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
468 }
469 }
470 }
471
472 if (!IIDecl) {
473 // None of the entities we found is a type, so there is no way
474 // to even assume that the result is a type. In this case, don't
475 // complain about the ambiguity. The parser will either try to
476 // perform this lookup again (e.g., as an object name), which
477 // will produce the ambiguity, or will complain that it expected
478 // a type name.
479 Result.suppressDiagnostics();
480 return nullptr;
481 }
482
483 // We found a type within the ambiguous lookup; diagnose the
484 // ambiguity and then return that type. This might be the right
485 // answer, or it might not be, but it suppresses any attempt to
486 // perform the name lookup again.
487 break;
488
490 IIDecl = Result.getFoundDecl();
491 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
492 break;
493 }
494
495 assert(IIDecl && "Didn't find decl");
496
497 TypeLocBuilder TLB;
498 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
499 checkTypeDeclType(LookupCtx,
500 IsImplicitTypename ? DiagCtorKind::Implicit
502 TD, NameLoc);
503 QualType T;
504 if (FoundUsingShadow) {
505 T = Context.getUsingType(ElaboratedTypeKeyword::None,
506 SS ? SS->getScopeRep() : std::nullopt,
507 FoundUsingShadow);
508 if (!WantNontrivialTypeSourceInfo)
509 return ParsedType::make(T);
510 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
513 NameLoc);
514 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
516 SS ? SS->getScopeRep() : std::nullopt, Tag,
517 /*OwnsTag=*/false);
518 if (!WantNontrivialTypeSourceInfo)
519 return ParsedType::make(T);
520 auto TL = TLB.push<TagTypeLoc>(T);
522 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
524 TL.setNameLoc(NameLoc);
525 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
526 TN && !isa<ObjCTypeParamDecl>(TN)) {
527 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
528 SS ? SS->getScopeRep() : std::nullopt, TN);
529 if (!WantNontrivialTypeSourceInfo)
530 return ParsedType::make(T);
531 TLB.push<TypedefTypeLoc>(T).set(
532 /*ElaboratedKeywordLoc=*/SourceLocation(),
534 NameLoc);
535 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
536 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
537 SS ? SS->getScopeRep() : std::nullopt,
538 UD);
539 if (!WantNontrivialTypeSourceInfo)
540 return ParsedType::make(T);
541 TLB.push<UnresolvedUsingTypeLoc>(T).set(
542 /*ElaboratedKeywordLoc=*/SourceLocation(),
544 NameLoc);
545 } else {
546 T = Context.getTypeDeclType(TD);
547 if (!WantNontrivialTypeSourceInfo)
548 return ParsedType::make(T);
550 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
551 else
552 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
553 }
554 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
555 }
556
557 if (getLangOpts().HLSL) {
558 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
559 getAsTemplateNameDecl(IIDecl, /*AllowFunctionTemplates=*/false,
560 /*AllowDependent=*/false))) {
561 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(TD, NameLoc);
562 if (!ShorthandTy.isNull())
563 return ParsedType::make(ShorthandTy);
564 }
565 }
566
567 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
568 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
569 if (!HasTrailingDot) {
570 // FIXME: Support UsingType for this case.
571 QualType T = Context.getObjCInterfaceType(IDecl);
572 if (!WantNontrivialTypeSourceInfo)
573 return ParsedType::make(T);
574 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
575 TL.setNameLoc(NameLoc);
576 // FIXME: Pass in this source location.
577 TL.setNameEndLoc(NameLoc);
578 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
579 }
580 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
581 (void)DiagnoseUseOfDecl(UD, NameLoc);
582 // Recover with 'int'
583 return ParsedType::make(Context.IntTy);
584 } else if (AllowDeducedTemplate) {
585 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
586 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
587 // FIXME: Support UsingType here.
588 TemplateName Template = Context.getQualifiedTemplateName(
589 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
590 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
591 QualType T = Context.getDeducedTemplateSpecializationType(
595 TL.setNameLoc(NameLoc);
596 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
598 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
599 }
600 }
601
602 // As it's not plausibly a type, suppress diagnostics.
603 Result.suppressDiagnostics();
604 return nullptr;
605}
606
607// Builds a fake NNS for the given decl context.
610 for (;; DC = DC->getLookupParent()) {
611 DC = DC->getPrimaryContext();
612 auto *ND = dyn_cast<NamespaceDecl>(DC);
613 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
614 return NestedNameSpecifier(Context, ND, std::nullopt);
615 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
616 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
619 }
620 llvm_unreachable("something isn't in TU scope?");
621}
622
623/// Find the parent class with dependent bases of the innermost enclosing method
624/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
625/// up allowing unqualified dependent type names at class-level, which MSVC
626/// correctly rejects.
627static const CXXRecordDecl *
629 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
630 DC = DC->getPrimaryContext();
631 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
632 if (MD->getParent()->hasAnyDependentBases())
633 return MD->getParent();
634 }
635 return nullptr;
636}
637
639 SourceLocation NameLoc,
640 bool IsTemplateTypeArg) {
641 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
642
643 NestedNameSpecifier NNS = std::nullopt;
644 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
645 // If we weren't able to parse a default template argument, delay lookup
646 // until instantiation time by making a non-dependent DependentTypeName. We
647 // pretend we saw a NestedNameSpecifier referring to the current scope, and
648 // lookup is retried.
649 // FIXME: This hurts our diagnostic quality, since we get errors like "no
650 // type named 'Foo' in 'current_namespace'" when the user didn't write any
651 // name specifiers.
653 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
654 } else if (const CXXRecordDecl *RD =
656 // Build a DependentNameType that will perform lookup into RD at
657 // instantiation time.
658 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
659
660 // Diagnose that this identifier was undeclared, and retry the lookup during
661 // template instantiation.
662 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
663 << RD;
664 } else {
665 // This is not a situation that we should recover from.
666 return ParsedType();
667 }
668
669 QualType T =
670 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
671
672 // Build type location information. We synthesized the qualifier, so we have
673 // to build a fake NestedNameSpecifierLoc.
674 NestedNameSpecifierLocBuilder NNSLocBuilder;
675 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
676 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
677
678 TypeLocBuilder Builder;
679 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
680 DepTL.setNameLoc(NameLoc);
682 DepTL.setQualifierLoc(QualifierLoc);
683 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
684}
685
687 // Do a tag name lookup in this scope.
688 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
689 LookupName(R, S, false);
690 R.suppressDiagnostics();
691 if (R.getResultKind() == LookupResultKind::Found)
692 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
693 switch (TD->getTagKind()) {
699 return DeclSpec::TST_union;
701 return DeclSpec::TST_class;
703 return DeclSpec::TST_enum;
704 }
705 }
706
708}
709
711 if (!CurContext->isRecord())
712 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
713
714 switch (SS->getScopeRep().getKind()) {
716 return true;
718 QualType T(SS->getScopeRep().getAsType(), 0);
719 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
720 if (Context.hasSameUnqualifiedType(T, Base.getType()))
721 return true;
722 [[fallthrough]];
723 }
724 default:
725 return S->isFunctionPrototypeScope();
726 }
727}
728
730 SourceLocation IILoc,
731 Scope *S,
732 CXXScopeSpec *SS,
733 ParsedType &SuggestedType,
734 bool IsTemplateName) {
735 // Don't report typename errors for editor placeholders.
736 if (II->isEditorPlaceholder())
737 return;
738 // We don't have anything to suggest (yet).
739 SuggestedType = nullptr;
740
741 // There may have been a typo in the name of the type. Look up typo
742 // results, in case we have something that we can suggest.
743 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
744 /*AllowTemplates=*/IsTemplateName,
745 /*AllowNonTemplates=*/!IsTemplateName);
746 if (TypoCorrection Corrected =
749 // FIXME: Support error recovery for the template-name case.
750 bool CanRecover = !IsTemplateName;
751 if (Corrected.isKeyword()) {
752 // We corrected to a keyword.
753 diagnoseTypo(Corrected,
754 PDiag(IsTemplateName ? diag::err_no_template_suggest
755 : diag::err_unknown_typename_suggest)
756 << II);
757 II = Corrected.getCorrectionAsIdentifierInfo();
758 } else {
759 // We found a similarly-named type or interface; suggest that.
760 if (!SS || !SS->isSet()) {
761 diagnoseTypo(Corrected,
762 PDiag(IsTemplateName ? diag::err_no_template_suggest
763 : diag::err_unknown_typename_suggest)
764 << II, CanRecover);
765 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
766 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
767 bool DroppedSpecifier =
768 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
769 diagnoseTypo(Corrected,
770 PDiag(IsTemplateName
771 ? diag::err_no_member_template_suggest
772 : diag::err_unknown_nested_typename_suggest)
773 << II << DC << DroppedSpecifier << SS->getRange(),
774 CanRecover);
775 } else {
776 llvm_unreachable("could not have corrected a typo here");
777 }
778
779 if (!CanRecover)
780 return;
781
782 CXXScopeSpec tmpSS;
783 if (Corrected.getCorrectionSpecifier())
784 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
785 SourceRange(IILoc));
786 // FIXME: Support class template argument deduction here.
787 SuggestedType =
788 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
789 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
790 /*IsCtorOrDtorName=*/false,
791 /*WantNontrivialTypeSourceInfo=*/true);
792 }
793 return;
794 }
795
796 if (getLangOpts().CPlusPlus && !IsTemplateName) {
797 // See if II is a class template that the user forgot to pass arguments to.
798 UnqualifiedId Name;
799 Name.setIdentifier(II, IILoc);
800 CXXScopeSpec EmptySS;
801 TemplateTy TemplateResult;
802 bool MemberOfUnknownSpecialization;
803 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
804 Name, nullptr, true, TemplateResult,
805 MemberOfUnknownSpecialization) == TNK_Type_template) {
806 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
807 return;
808 }
809 }
810
811 // FIXME: Should we move the logic that tries to recover from a missing tag
812 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
813
814 if (!SS || (!SS->isSet() && !SS->isInvalid()))
815 Diag(IILoc, IsTemplateName ? diag::err_no_template
816 : diag::err_unknown_typename)
817 << II;
818 else if (DeclContext *DC = computeDeclContext(*SS, false))
819 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
820 : diag::err_typename_nested_not_found)
821 << II << DC << SS->getRange();
822 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
823 SuggestedType =
824 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
825 } else if (isDependentScopeSpecifier(*SS)) {
826 unsigned DiagID = diag::err_typename_missing;
827 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
828 DiagID = diag::ext_typename_missing;
829
830 SuggestedType =
831 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
832
833 Diag(SS->getRange().getBegin(), DiagID)
834 << GetTypeFromParser(SuggestedType)
835 << SourceRange(SS->getRange().getBegin(), IILoc)
836 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
837 } else {
838 assert(SS && SS->isInvalid() &&
839 "Invalid scope specifier has already been diagnosed");
840 }
841}
842
843/// Determine whether the given result set contains either a type name
844/// or
845static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
846 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
847 NextToken.is(tok::less);
848
849 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
851 return true;
852
853 if (CheckTemplate && isa<TemplateDecl>(*I))
854 return true;
855 }
856
857 return false;
858}
859
860static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
861 Scope *S, CXXScopeSpec &SS,
862 IdentifierInfo *&Name,
863 SourceLocation NameLoc) {
864 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
865 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
866 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
867 StringRef FixItTagName;
868 switch (Tag->getTagKind()) {
870 FixItTagName = "class ";
871 break;
872
874 FixItTagName = "enum ";
875 break;
876
878 FixItTagName = "struct ";
879 break;
880
882 FixItTagName = "__interface ";
883 break;
884
886 FixItTagName = "union ";
887 break;
888 }
889
890 StringRef TagName = FixItTagName.drop_back();
891 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
892 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
893 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
894
895 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
896 I != IEnd; ++I)
897 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
898 << Name << TagName;
899
900 // Replace lookup results with just the tag decl.
901 Result.clear(Sema::LookupTagName);
902 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
903 return true;
904 }
905
906 return false;
907}
908
910 IdentifierInfo *&Name,
911 SourceLocation NameLoc,
912 const Token &NextToken,
914 DeclarationNameInfo NameInfo(Name, NameLoc);
915 ObjCMethodDecl *CurMethod = getCurMethodDecl();
916
917 assert(NextToken.isNot(tok::coloncolon) &&
918 "parse nested name specifiers before calling ClassifyName");
919 if (getLangOpts().CPlusPlus && SS.isSet() &&
920 isCurrentClassName(*Name, S, &SS)) {
921 // Per [class.qual]p2, this names the constructors of SS, not the
922 // injected-class-name. We don't have a classification for that.
923 // There's not much point caching this result, since the parser
924 // will reject it later.
926 }
927
928 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
929 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
930 /*AllowBuiltinCreation=*/!CurMethod);
931
932 if (SS.isInvalid())
934
935 // For unqualified lookup in a class template in MSVC mode, look into
936 // dependent base classes where the primary class template is known.
937 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
938 if (ParsedType TypeInBase =
939 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
940 return TypeInBase;
941 }
942
943 // Perform lookup for Objective-C instance variables (including automatically
944 // synthesized instance variables), if we're in an Objective-C method.
945 // FIXME: This lookup really, really needs to be folded in to the normal
946 // unqualified lookup mechanism.
947 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
948 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
949 if (Ivar.isInvalid())
951 if (Ivar.isUsable())
953
954 // We defer builtin creation until after ivar lookup inside ObjC methods.
955 if (Result.empty())
957 }
958
959 bool SecondTry = false;
960 bool IsFilteredTemplateName = false;
961
962Corrected:
963 switch (Result.getResultKind()) {
965 // If an unqualified-id is followed by a '(', then we have a function
966 // call.
967 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
968 // In C++, this is an ADL-only call.
969 // FIXME: Reference?
972
973 // C90 6.3.2.2:
974 // If the expression that precedes the parenthesized argument list in a
975 // function call consists solely of an identifier, and if no
976 // declaration is visible for this identifier, the identifier is
977 // implicitly declared exactly as if, in the innermost block containing
978 // the function call, the declaration
979 //
980 // extern int identifier ();
981 //
982 // appeared.
983 //
984 // We also allow this in C99 as an extension. However, this is not
985 // allowed in all language modes as functions without prototypes may not
986 // be supported.
987 if (getLangOpts().implicitFunctionsAllowed()) {
988 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
990 }
991 }
992
993 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
994 // In C++20 onwards, this could be an ADL-only call to a function
995 // template, and we're required to assume that this is a template name.
996 //
997 // FIXME: Find a way to still do typo correction in this case.
999 Context.getAssumedTemplateName(NameInfo.getName());
1001 }
1002
1003 // In C, we first see whether there is a tag type by the same name, in
1004 // which case it's likely that the user just forgot to write "enum",
1005 // "struct", or "union".
1006 if (!getLangOpts().CPlusPlus && !SecondTry &&
1007 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1008 break;
1009 }
1010
1011 // Perform typo correction to determine if there is another name that is
1012 // close to this name.
1013 if (!SecondTry && CCC) {
1014 SecondTry = true;
1015 if (TypoCorrection Corrected =
1016 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1017 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1018 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1019 unsigned QualifiedDiag = diag::err_no_member_suggest;
1020
1021 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1022 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1023 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1024 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1025 UnqualifiedDiag = diag::err_no_template_suggest;
1026 QualifiedDiag = diag::err_no_member_template_suggest;
1027 } else if (UnderlyingFirstDecl &&
1028 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1029 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1030 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1031 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1032 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1033 }
1034
1035 if (SS.isEmpty()) {
1036 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1037 } else {// FIXME: is this even reachable? Test it.
1038 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1039 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1040 Name->getName() == CorrectedStr;
1041 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1042 << Name << computeDeclContext(SS, false)
1043 << DroppedSpecifier << SS.getRange());
1044 }
1045
1046 // Update the name, so that the caller has the new name.
1047 Name = Corrected.getCorrectionAsIdentifierInfo();
1048
1049 // Typo correction corrected to a keyword.
1050 if (Corrected.isKeyword())
1051 return Name;
1052
1053 // Also update the LookupResult...
1054 // FIXME: This should probably go away at some point
1055 Result.clear();
1056 Result.setLookupName(Corrected.getCorrection());
1057 if (FirstDecl)
1058 Result.addDecl(FirstDecl);
1059
1060 // If we found an Objective-C instance variable, let
1061 // LookupInObjCMethod build the appropriate expression to
1062 // reference the ivar.
1063 // FIXME: This is a gross hack.
1064 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1065 DeclResult R =
1066 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1067 if (R.isInvalid())
1069 if (R.isUsable())
1070 return NameClassification::NonType(Ivar);
1071 }
1072
1073 goto Corrected;
1074 }
1075 }
1076
1077 // We failed to correct; just fall through and let the parser deal with it.
1078 Result.suppressDiagnostics();
1080
1082 // We performed name lookup into the current instantiation, and there were
1083 // dependent bases, so we treat this result the same way as any other
1084 // dependent nested-name-specifier.
1085
1086 // C++ [temp.res]p2:
1087 // A name used in a template declaration or definition and that is
1088 // dependent on a template-parameter is assumed not to name a type
1089 // unless the applicable name lookup finds a type name or the name is
1090 // qualified by the keyword typename.
1091 //
1092 // FIXME: If the next token is '<', we might want to ask the parser to
1093 // perform some heroics to see if we actually have a
1094 // template-argument-list, which would indicate a missing 'template'
1095 // keyword here.
1097 }
1098
1102 break;
1103
1105 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1106 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1107 /*AllowDependent=*/false)) {
1108 // C++ [temp.local]p3:
1109 // A lookup that finds an injected-class-name (10.2) can result in an
1110 // ambiguity in certain cases (for example, if it is found in more than
1111 // one base class). If all of the injected-class-names that are found
1112 // refer to specializations of the same class template, and if the name
1113 // is followed by a template-argument-list, the reference refers to the
1114 // class template itself and not a specialization thereof, and is not
1115 // ambiguous.
1116 //
1117 // This filtering can make an ambiguous result into an unambiguous one,
1118 // so try again after filtering out template names.
1120 if (!Result.isAmbiguous()) {
1121 IsFilteredTemplateName = true;
1122 break;
1123 }
1124 }
1125
1126 // Diagnose the ambiguity and return an error.
1128 }
1129
1130 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1131 (IsFilteredTemplateName ||
1133 Result, /*AllowFunctionTemplates=*/true,
1134 /*AllowDependent=*/false,
1135 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1137 // C++ [temp.names]p3:
1138 // After name lookup (3.4) finds that a name is a template-name or that
1139 // an operator-function-id or a literal- operator-id refers to a set of
1140 // overloaded functions any member of which is a function template if
1141 // this is followed by a <, the < is always taken as the delimiter of a
1142 // template-argument-list and never as the less-than operator.
1143 // C++2a [temp.names]p2:
1144 // A name is also considered to refer to a template if it is an
1145 // unqualified-id followed by a < and name lookup finds either one
1146 // or more functions or finds nothing.
1147 if (!IsFilteredTemplateName)
1149
1150 bool IsFunctionTemplate;
1151 bool IsVarTemplate;
1153 if (Result.end() - Result.begin() > 1) {
1154 IsFunctionTemplate = true;
1155 Template = Context.getOverloadedTemplateName(Result.begin(),
1156 Result.end());
1157 } else if (!Result.empty()) {
1159 *Result.begin(), /*AllowFunctionTemplates=*/true,
1160 /*AllowDependent=*/false));
1161 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1162 IsVarTemplate = isa<VarTemplateDecl>(TD);
1163
1164 UsingShadowDecl *FoundUsingShadow =
1165 dyn_cast<UsingShadowDecl>(*Result.begin());
1166 assert(!FoundUsingShadow ||
1167 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1168 Template = Context.getQualifiedTemplateName(
1169 SS.getScopeRep(),
1170 /*TemplateKeyword=*/false,
1171 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1172 } else {
1173 // All results were non-template functions. This is a function template
1174 // name.
1175 IsFunctionTemplate = true;
1176 Template = Context.getAssumedTemplateName(NameInfo.getName());
1177 }
1178
1179 if (IsFunctionTemplate) {
1180 // Function templates always go through overload resolution, at which
1181 // point we'll perform the various checks (e.g., accessibility) we need
1182 // to based on which function we selected.
1183 Result.suppressDiagnostics();
1184
1186 }
1187
1188 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1190 }
1191
1192 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1193 QualType T;
1194 TypeLocBuilder TLB;
1195 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1196 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1197 USD);
1198 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1199 SS.getWithLocInContext(Context), NameLoc);
1200 } else {
1201 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1202 Type);
1203 if (isa<TagType>(T)) {
1204 auto TTL = TLB.push<TagTypeLoc>(T);
1206 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1207 TTL.setNameLoc(NameLoc);
1208 } else if (isa<TypedefType>(T)) {
1209 TLB.push<TypedefTypeLoc>(T).set(
1210 /*ElaboratedKeywordLoc=*/SourceLocation(),
1211 SS.getWithLocInContext(Context), NameLoc);
1212 } else if (isa<UnresolvedUsingType>(T)) {
1213 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1214 /*ElaboratedKeywordLoc=*/SourceLocation(),
1215 SS.getWithLocInContext(Context), NameLoc);
1216 } else {
1217 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1218 }
1219 }
1220 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
1221 };
1222
1223 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1224 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1225 DiagnoseUseOfDecl(Type, NameLoc);
1226 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1227 return BuildTypeFor(Type, *Result.begin());
1228 }
1229
1230 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1231 if (!Class) {
1232 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1233 if (ObjCCompatibleAliasDecl *Alias =
1234 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1235 Class = Alias->getClassInterface();
1236 }
1237
1238 if (Class) {
1239 DiagnoseUseOfDecl(Class, NameLoc);
1240
1241 if (NextToken.is(tok::period)) {
1242 // Interface. <something> is parsed as a property reference expression.
1243 // Just return "unknown" as a fall-through for now.
1244 Result.suppressDiagnostics();
1246 }
1247
1248 QualType T = Context.getObjCInterfaceType(Class);
1249 return ParsedType::make(T);
1250 }
1251
1253 // We want to preserve the UsingShadowDecl for concepts.
1254 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1258 }
1259
1260 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1261 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1263 }
1264
1265 // We can have a type template here if we're classifying a template argument.
1270
1271 // Check for a tag type hidden by a non-type decl in a few cases where it
1272 // seems likely a type is wanted instead of the non-type that was found.
1273 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1274 if ((NextToken.is(tok::identifier) ||
1275 (NextIsOp &&
1276 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1277 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1278 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1279 DiagnoseUseOfDecl(Type, NameLoc);
1280 return BuildTypeFor(Type, *Result.begin());
1281 }
1282
1283 // If we already know which single declaration is referenced, just annotate
1284 // that declaration directly. Defer resolving even non-overloaded class
1285 // member accesses, as we need to defer certain access checks until we know
1286 // the context.
1287 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1288 if (Result.isSingleResult() && !ADL &&
1289 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1290 return NameClassification::NonType(Result.getRepresentativeDecl());
1291
1292 // Otherwise, this is an overload set that we will need to resolve later.
1293 Result.suppressDiagnostics();
1295 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1296 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1297 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1298}
1299
1302 SourceLocation NameLoc) {
1303 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1304 CXXScopeSpec SS;
1305 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1306 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1307}
1308
1311 IdentifierInfo *Name,
1312 SourceLocation NameLoc,
1313 bool IsAddressOfOperand) {
1314 DeclarationNameInfo NameInfo(Name, NameLoc);
1315 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1316 NameInfo, IsAddressOfOperand,
1317 /*TemplateArgs=*/nullptr);
1318}
1319
1322 SourceLocation NameLoc,
1323 const Token &NextToken) {
1324 if (getCurMethodDecl() && SS.isEmpty())
1325 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1326 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1327
1328 // Reconstruct the lookup result.
1329 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1330 Result.addDecl(Found);
1331 Result.resolveKind();
1332
1333 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1334 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1335}
1336
1338 // For an implicit class member access, transform the result into a member
1339 // access expression if necessary.
1340 auto *ULE = cast<UnresolvedLookupExpr>(E);
1341 if ((*ULE->decls_begin())->isCXXClassMember()) {
1342 CXXScopeSpec SS;
1343 SS.Adopt(ULE->getQualifierLoc());
1344
1345 // Reconstruct the lookup result.
1346 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1348 Result.setNamingClass(ULE->getNamingClass());
1349 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1350 Result.addDecl(*I, I.getAccess());
1351 Result.resolveKind();
1353 nullptr, S);
1354 }
1355
1356 // Otherwise, this is already in the form we needed, and no further checks
1357 // are necessary.
1358 return ULE;
1359}
1360
1380
1382 assert(DC->getLexicalParent() == CurContext &&
1383 "The next DeclContext should be lexically contained in the current one.");
1384 CurContext = DC;
1385 S->setEntity(DC);
1386}
1387
1389 assert(CurContext && "DeclContext imbalance!");
1390
1391 CurContext = CurContext->getLexicalParent();
1392 assert(CurContext && "Popped translation unit!");
1393}
1394
1396 Decl *D) {
1397 // Unlike PushDeclContext, the context to which we return is not necessarily
1398 // the containing DC of TD, because the new context will be some pre-existing
1399 // TagDecl definition instead of a fresh one.
1400 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1401 CurContext = cast<TagDecl>(D)->getDefinition();
1402 assert(CurContext && "skipping definition of undefined tag");
1403 // Start lookups from the parent of the current context; we don't want to look
1404 // into the pre-existing complete definition.
1405 S->setEntity(CurContext->getLookupParent());
1406 return Result;
1407}
1408
1412
1414 // C++0x [basic.lookup.unqual]p13:
1415 // A name used in the definition of a static data member of class
1416 // X (after the qualified-id of the static member) is looked up as
1417 // if the name was used in a member function of X.
1418 // C++0x [basic.lookup.unqual]p14:
1419 // If a variable member of a namespace is defined outside of the
1420 // scope of its namespace then any name used in the definition of
1421 // the variable member (after the declarator-id) is looked up as
1422 // if the definition of the variable member occurred in its
1423 // namespace.
1424 // Both of these imply that we should push a scope whose context
1425 // is the semantic context of the declaration. We can't use
1426 // PushDeclContext here because that context is not necessarily
1427 // lexically contained in the current context. Fortunately,
1428 // the containing scope should have the appropriate information.
1429
1430 assert(!S->getEntity() && "scope already has entity");
1431
1432#ifndef NDEBUG
1433 Scope *Ancestor = S->getParent();
1434 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1435 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1436#endif
1437
1438 CurContext = DC;
1439 S->setEntity(DC);
1440
1441 if (S->getParent()->isTemplateParamScope()) {
1442 // Also set the corresponding entities for all immediately-enclosing
1443 // template parameter scopes.
1445 }
1446}
1447
1449 assert(S->getEntity() == CurContext && "Context imbalance!");
1450
1451 // Switch back to the lexical context. The safety of this is
1452 // enforced by an assert in EnterDeclaratorContext.
1453 Scope *Ancestor = S->getParent();
1454 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1455 CurContext = Ancestor->getEntity();
1456
1457 // We don't need to do anything with the scope, which is going to
1458 // disappear.
1459}
1460
1462 assert(S->isTemplateParamScope() &&
1463 "expected to be initializing a template parameter scope");
1464
1465 // C++20 [temp.local]p7:
1466 // In the definition of a member of a class template that appears outside
1467 // of the class template definition, the name of a member of the class
1468 // template hides the name of a template-parameter of any enclosing class
1469 // templates (but not a template-parameter of the member if the member is a
1470 // class or function template).
1471 // C++20 [temp.local]p9:
1472 // In the definition of a class template or in the definition of a member
1473 // of such a template that appears outside of the template definition, for
1474 // each non-dependent base class (13.8.2.1), if the name of the base class
1475 // or the name of a member of the base class is the same as the name of a
1476 // template-parameter, the base class name or member name hides the
1477 // template-parameter name (6.4.10).
1478 //
1479 // This means that a template parameter scope should be searched immediately
1480 // after searching the DeclContext for which it is a template parameter
1481 // scope. For example, for
1482 // template<typename T> template<typename U> template<typename V>
1483 // void N::A<T>::B<U>::f(...)
1484 // we search V then B<U> (and base classes) then U then A<T> (and base
1485 // classes) then T then N then ::.
1486 unsigned ScopeDepth = getTemplateDepth(S);
1487 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1488 DeclContext *SearchDCAfterScope = DC;
1489 for (; DC; DC = DC->getLookupParent()) {
1490 if (const TemplateParameterList *TPL =
1491 cast<Decl>(DC)->getDescribedTemplateParams()) {
1492 unsigned DCDepth = TPL->getDepth() + 1;
1493 if (DCDepth > ScopeDepth)
1494 continue;
1495 if (ScopeDepth == DCDepth)
1496 SearchDCAfterScope = DC = DC->getLookupParent();
1497 break;
1498 }
1499 }
1500 S->setLookupEntity(SearchDCAfterScope);
1501 }
1502}
1503
1505 // We assume that the caller has already called
1506 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1507 FunctionDecl *FD = D->getAsFunction();
1508 if (!FD)
1509 return;
1510
1511 // Same implementation as PushDeclContext, but enters the context
1512 // from the lexical parent, rather than the top-level class.
1513 assert(CurContext == FD->getLexicalParent() &&
1514 "The next DeclContext should be lexically contained in the current one.");
1515 CurContext = FD;
1517
1518 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1519 ParmVarDecl *Param = FD->getParamDecl(P);
1520 // If the parameter has an identifier, then add it to the scope
1521 if (Param->getIdentifier()) {
1522 S->AddDecl(Param);
1523 IdResolver.AddDecl(Param);
1524 }
1525 }
1526}
1527
1529 // Same implementation as PopDeclContext, but returns to the lexical parent,
1530 // rather than the top-level class.
1531 assert(CurContext && "DeclContext imbalance!");
1532 CurContext = CurContext->getLexicalParent();
1533 assert(CurContext && "Popped translation unit!");
1534}
1535
1536/// Determine whether overloading is allowed for a new function
1537/// declaration considering prior declarations of the same name.
1538///
1539/// This routine determines whether overloading is possible, not
1540/// whether a new declaration actually overloads a previous one.
1541/// It will return true in C++ (where overloads are always permitted)
1542/// or, as a C extension, when either the new declaration or a
1543/// previous one is declared with the 'overloadable' attribute.
1545 ASTContext &Context,
1546 const FunctionDecl *New) {
1547 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1548 return true;
1549
1550 // Multiversion function declarations are not overloads in the
1551 // usual sense of that term, but lookup will report that an
1552 // overload set was found if more than one multiversion function
1553 // declaration is present for the same name. It is therefore
1554 // inadequate to assume that some prior declaration(s) had
1555 // the overloadable attribute; checking is required. Since one
1556 // declaration is permitted to omit the attribute, it is necessary
1557 // to check at least two; hence the 'any_of' check below. Note that
1558 // the overloadable attribute is implicitly added to declarations
1559 // that were required to have it but did not.
1560 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1561 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1562 return ND->hasAttr<OverloadableAttr>();
1563 });
1564 } else if (Previous.getResultKind() == LookupResultKind::Found)
1565 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1566
1567 return false;
1568}
1569
1570void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1571 // Move up the scope chain until we find the nearest enclosing
1572 // non-transparent context. The declaration will be introduced into this
1573 // scope.
1574 while (S->getEntity() && S->getEntity()->isTransparentContext())
1575 S = S->getParent();
1576
1577 // Add scoped declarations into their context, so that they can be
1578 // found later. Declarations without a context won't be inserted
1579 // into any context.
1580 if (AddToContext)
1581 CurContext->addDecl(D);
1582
1583 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1584 // are function-local declarations.
1585 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1586 return;
1587
1588 // Template instantiations should also not be pushed into scope.
1589 if (isa<FunctionDecl>(D) &&
1590 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1591 return;
1592
1593 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1594 S->AddDecl(D);
1595 return;
1596 }
1597 // If this replaces anything in the current scope,
1599 IEnd = IdResolver.end();
1600 for (; I != IEnd; ++I) {
1601 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1602 S->RemoveDecl(*I);
1603 IdResolver.RemoveDecl(*I);
1604
1605 // Should only need to replace one decl.
1606 break;
1607 }
1608 }
1609
1610 S->AddDecl(D);
1611
1612 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1613 // Implicitly-generated labels may end up getting generated in an order that
1614 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1615 // the label at the appropriate place in the identifier chain.
1616 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1617 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1618 if (IDC == CurContext) {
1619 if (!S->isDeclScope(*I))
1620 continue;
1621 } else if (IDC->Encloses(CurContext))
1622 break;
1623 }
1624
1625 IdResolver.InsertDeclAfter(I, D);
1626 } else {
1627 IdResolver.AddDecl(D);
1628 }
1630}
1631
1633 bool AllowInlineNamespace) const {
1634 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1635}
1636
1638 DeclContext *TargetDC = DC->getPrimaryContext();
1639 do {
1640 if (DeclContext *ScopeDC = S->getEntity())
1641 if (ScopeDC->getPrimaryContext() == TargetDC)
1642 return S;
1643 } while ((S = S->getParent()));
1644
1645 return nullptr;
1646}
1647
1649 DeclContext*,
1650 ASTContext&);
1651
1653 bool ConsiderLinkage,
1654 bool AllowInlineNamespace) {
1655 LookupResult::Filter F = R.makeFilter();
1656 while (F.hasNext()) {
1657 NamedDecl *D = F.next();
1658
1659 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1660 continue;
1661
1662 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1663 continue;
1664
1665 F.erase();
1666 }
1667
1668 F.done();
1669}
1670
1672 if (auto *VD = dyn_cast<VarDecl>(D))
1673 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1674 if (auto *FD = dyn_cast<FunctionDecl>(D))
1675 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1676 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1677 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1678
1679 return false;
1680}
1681
1683 // [module.interface]p7:
1684 // A declaration is attached to a module as follows:
1685 // - If the declaration is a non-dependent friend declaration that nominates a
1686 // function with a declarator-id that is a qualified-id or template-id or that
1687 // nominates a class other than with an elaborated-type-specifier with neither
1688 // a nested-name-specifier nor a simple-template-id, it is attached to the
1689 // module to which the friend is attached ([basic.link]).
1690 if (New->getFriendObjectKind() &&
1691 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1692 New->setLocalOwningModule(Old->getOwningModule());
1694 return false;
1695 }
1696
1697 // Although we have questions for the module ownership of implicit
1698 // instantiations, it should be sure that we shouldn't diagnose the
1699 // redeclaration of incorrect module ownership for different implicit
1700 // instantiations in different modules. We will diagnose the redeclaration of
1701 // incorrect module ownership for the template itself.
1703 return false;
1704
1705 Module *NewM = New->getOwningModule();
1706 Module *OldM = Old->getOwningModule();
1707
1708 if (NewM && NewM->isPrivateModule())
1709 NewM = NewM->Parent;
1710 if (OldM && OldM->isPrivateModule())
1711 OldM = OldM->Parent;
1712
1713 if (NewM == OldM)
1714 return false;
1715
1716 if (NewM && OldM) {
1717 // A module implementation unit has visibility of the decls in its
1718 // implicitly imported interface.
1719 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1720 return false;
1721
1722 // Partitions are part of the module, but a partition could import another
1723 // module, so verify that the PMIs agree.
1724 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1725 getASTContext().isInSameModule(NewM, OldM))
1726 return false;
1727 }
1728
1729 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1730 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1731 if (NewIsModuleInterface || OldIsModuleInterface) {
1732 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1733 // if a declaration of D [...] appears in the purview of a module, all
1734 // other such declarations shall appear in the purview of the same module
1735 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1736 << New
1737 << NewIsModuleInterface
1738 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1739 << OldIsModuleInterface
1740 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1741 Diag(Old->getLocation(), diag::note_previous_declaration);
1742 New->setInvalidDecl();
1743 return true;
1744 }
1745
1746 return false;
1747}
1748
1750 // [module.interface]p1:
1751 // An export-declaration shall inhabit a namespace scope.
1752 //
1753 // So it is meaningless to talk about redeclaration which is not at namespace
1754 // scope.
1755 if (!New->getLexicalDeclContext()
1756 ->getNonTransparentContext()
1757 ->isFileContext() ||
1758 !Old->getLexicalDeclContext()
1760 ->isFileContext())
1761 return false;
1762
1763 bool IsNewExported = New->isInExportDeclContext();
1764 bool IsOldExported = Old->isInExportDeclContext();
1765
1766 // It should be irrevelant if both of them are not exported.
1767 if (!IsNewExported && !IsOldExported)
1768 return false;
1769
1770 if (IsOldExported)
1771 return false;
1772
1773 // If the Old declaration are not attached to named modules
1774 // and the New declaration are attached to global module.
1775 // It should be fine to allow the export since it doesn't change
1776 // the linkage of declarations. See
1777 // https://github.com/llvm/llvm-project/issues/98583 for details.
1778 if (!Old->isInNamedModule() && New->getOwningModule() &&
1779 New->getOwningModule()->isImplicitGlobalModule())
1780 return false;
1781
1782 assert(IsNewExported);
1783
1784 auto Lk = Old->getFormalLinkage();
1785 int S = 0;
1786 if (Lk == Linkage::Internal)
1787 S = 1;
1788 else if (Lk == Linkage::Module)
1789 S = 2;
1790 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1791 Diag(Old->getLocation(), diag::note_previous_declaration);
1792 return true;
1793}
1794
1797 return true;
1798
1800 return true;
1801
1802 return false;
1803}
1804
1806 const NamedDecl *Old) const {
1807 assert(getASTContext().isSameEntity(New, Old) &&
1808 "New and Old are not the same definition, we should diagnostic it "
1809 "immediately instead of checking it.");
1810 assert(const_cast<Sema *>(this)->isReachable(New) &&
1811 const_cast<Sema *>(this)->isReachable(Old) &&
1812 "We shouldn't see unreachable definitions here.");
1813
1814 Module *NewM = New->getOwningModule();
1815 Module *OldM = Old->getOwningModule();
1816
1817 // We only checks for named modules here. The header like modules is skipped.
1818 // FIXME: This is not right if we import the header like modules in the module
1819 // purview.
1820 //
1821 // For example, assuming "header.h" provides definition for `D`.
1822 // ```C++
1823 // //--- M.cppm
1824 // export module M;
1825 // import "header.h"; // or #include "header.h" but import it by clang modules
1826 // actually.
1827 //
1828 // //--- Use.cpp
1829 // import M;
1830 // import "header.h"; // or uses clang modules.
1831 // ```
1832 //
1833 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1834 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1835 // reject it. But the current implementation couldn't detect the case since we
1836 // don't record the information about the importee modules.
1837 //
1838 // But this might not be painful in practice. Since the design of C++20 Named
1839 // Modules suggests us to use headers in global module fragment instead of
1840 // module purview.
1841 if (NewM && NewM->isHeaderLikeModule())
1842 NewM = nullptr;
1843 if (OldM && OldM->isHeaderLikeModule())
1844 OldM = nullptr;
1845
1846 if (!NewM && !OldM)
1847 return true;
1848
1849 // [basic.def.odr]p14.3
1850 // Each such definition shall not be attached to a named module
1851 // ([module.unit]).
1852 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1853 return true;
1854
1855 // Then New and Old lives in the same TU if their share one same module unit.
1856 if (NewM)
1857 NewM = NewM->getTopLevelModule();
1858 if (OldM)
1859 OldM = OldM->getTopLevelModule();
1860 return OldM == NewM;
1861}
1862
1864 if (D->getDeclContext()->isFileContext())
1865 return false;
1866
1867 return isa<UsingShadowDecl>(D) ||
1870}
1871
1872/// Removes using shadow declarations not at class scope from the lookup
1873/// results.
1875 LookupResult::Filter F = R.makeFilter();
1876 while (F.hasNext())
1878 F.erase();
1879
1880 F.done();
1881}
1882
1883/// Check for this common pattern:
1884/// @code
1885/// class S {
1886/// S(const S&); // DO NOT IMPLEMENT
1887/// void operator=(const S&); // DO NOT IMPLEMENT
1888/// };
1889/// @endcode
1891 // FIXME: Should check for private access too but access is set after we get
1892 // the decl here.
1894 return false;
1895
1896 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1897 return CD->isCopyConstructor();
1898 return D->isCopyAssignmentOperator();
1899}
1900
1901bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1902 const DeclContext *DC = D->getDeclContext();
1903 while (!DC->isTranslationUnit()) {
1904 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1905 if (!RD->hasNameForLinkage())
1906 return true;
1907 }
1908 DC = DC->getParent();
1909 }
1910
1911 return !D->isExternallyVisible();
1912}
1913
1914// FIXME: This needs to be refactored; some other isInMainFile users want
1915// these semantics.
1916static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1918 return false;
1919 return S.SourceMgr.isInMainFile(Loc);
1920}
1921
1923 assert(D);
1924
1925 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1926 return false;
1927
1928 // Ignore all entities declared within templates, and out-of-line definitions
1929 // of members of class templates.
1930 if (D->getDeclContext()->isDependentContext() ||
1932 return false;
1933
1934 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1935 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1936 return false;
1937 // A non-out-of-line declaration of a member specialization was implicitly
1938 // instantiated; it's the out-of-line declaration that we're interested in.
1939 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1940 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1941 return false;
1942
1943 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1944 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1945 return false;
1946 } else {
1947 // 'static inline' functions are defined in headers; don't warn.
1948 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1949 return false;
1950 }
1951
1952 if (FD->doesThisDeclarationHaveABody() &&
1953 Context.DeclMustBeEmitted(FD))
1954 return false;
1955 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1956 // Constants and utility variables are defined in headers with internal
1957 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1958 // like "inline".)
1959 if (!isMainFileLoc(*this, VD->getLocation()))
1960 return false;
1961
1962 if (Context.DeclMustBeEmitted(VD))
1963 return false;
1964
1965 if (VD->isStaticDataMember() &&
1966 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1967 return false;
1968 if (VD->isStaticDataMember() &&
1969 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1970 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1971 return false;
1972
1973 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1974 return false;
1975 } else {
1976 return false;
1977 }
1978
1979 // Only warn for unused decls internal to the translation unit.
1980 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1981 // for inline functions defined in the main source file, for instance.
1982 return mightHaveNonExternalLinkage(D);
1983}
1984
1986 if (!D)
1987 return;
1988
1989 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1990 const FunctionDecl *First = FD->getFirstDecl();
1992 return; // First should already be in the vector.
1993 }
1994
1995 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1996 const VarDecl *First = VD->getFirstDecl();
1998 return; // First should already be in the vector.
1999 }
2000
2002 UnusedFileScopedDecls.push_back(D);
2003}
2004
2005static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2006 const NamedDecl *D) {
2007 if (D->isInvalidDecl())
2008 return false;
2009
2010 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2011 // For a decomposition declaration, warn if none of the bindings are
2012 // referenced, instead of if the variable itself is referenced (which
2013 // it is, by the bindings' expressions).
2014 bool IsAllIgnored = true;
2015 for (const auto *BD : DD->bindings()) {
2016 if (BD->isReferenced())
2017 return false;
2018 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2019 BD->hasAttr<UnusedAttr>());
2020 }
2021 if (IsAllIgnored)
2022 return false;
2023 } else if (!D->getDeclName()) {
2024 return false;
2025 } else if (D->isReferenced() || D->isUsed()) {
2026 return false;
2027 }
2028
2029 if (D->isPlaceholderVar(LangOpts))
2030 return false;
2031
2032 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2033 D->hasAttr<CleanupAttr>())
2034 return false;
2035
2036 if (isa<LabelDecl>(D))
2037 return true;
2038
2039 // Except for labels, we only care about unused decls that are local to
2040 // functions.
2041 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2042 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2043 // For dependent types, the diagnostic is deferred.
2044 WithinFunction =
2045 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2046 if (!WithinFunction)
2047 return false;
2048
2049 if (isa<TypedefNameDecl>(D))
2050 return true;
2051
2052 // White-list anything that isn't a local variable.
2054 return false;
2055
2056 // Types of valid local variables should be complete, so this should succeed.
2057 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2058
2059 const Expr *Init = VD->getInit();
2060 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2061 Init = Cleanups->getSubExpr();
2062
2063 const auto *Ty = VD->getType().getTypePtr();
2064
2065 // Only look at the outermost level of typedef.
2066 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2067 // Allow anything marked with __attribute__((unused)).
2068 if (TT->getDecl()->hasAttr<UnusedAttr>())
2069 return false;
2070 }
2071
2072 // Warn for reference variables whose initializtion performs lifetime
2073 // extension.
2074 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2075 MTE && MTE->getExtendingDecl()) {
2076 Ty = VD->getType().getNonReferenceType().getTypePtr();
2077 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2078 }
2079
2080 // If we failed to complete the type for some reason, or if the type is
2081 // dependent, don't diagnose the variable.
2082 if (Ty->isIncompleteType() || Ty->isDependentType())
2083 return false;
2084
2085 // Look at the element type to ensure that the warning behaviour is
2086 // consistent for both scalars and arrays.
2087 Ty = Ty->getBaseElementTypeUnsafe();
2088
2089 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2090 if (Tag->hasAttr<UnusedAttr>())
2091 return false;
2092
2093 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2094 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2095 return false;
2096
2097 if (Init) {
2098 const auto *Construct =
2099 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2100 if (Construct && !Construct->isElidable()) {
2101 const CXXConstructorDecl *CD = Construct->getConstructor();
2102 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2103 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2104 return false;
2105 }
2106
2107 // Suppress the warning if we don't know how this is constructed, and
2108 // it could possibly be non-trivial constructor.
2109 if (Init->isTypeDependent()) {
2110 for (const CXXConstructorDecl *Ctor : RD->ctors())
2111 if (!Ctor->isTrivial())
2112 return false;
2113 }
2114
2115 // Suppress the warning if the constructor is unresolved because
2116 // its arguments are dependent.
2118 return false;
2119 }
2120 }
2121 }
2122
2123 // TODO: __attribute__((unused)) templates?
2124 }
2125
2126 return true;
2127}
2128
2130 FixItHint &Hint) {
2131 if (isa<LabelDecl>(D)) {
2133 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2134 /*SkipTrailingWhitespaceAndNewline=*/false);
2135 if (AfterColon.isInvalid())
2136 return;
2138 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2139 }
2140}
2141
2144 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2145}
2146
2148 DiagReceiverTy DiagReceiver) {
2149 if (D->isDependentType())
2150 return;
2151
2152 for (auto *TmpD : D->decls()) {
2153 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2154 DiagnoseUnusedDecl(T, DiagReceiver);
2155 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2156 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2157 }
2158}
2159
2162 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2163}
2164
2167 return;
2168
2169 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2170 // typedefs can be referenced later on, so the diagnostics are emitted
2171 // at end-of-translation-unit.
2173 return;
2174 }
2175
2176 FixItHint Hint;
2178
2179 unsigned DiagID;
2180 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2181 DiagID = diag::warn_unused_exception_param;
2182 else if (isa<LabelDecl>(D))
2183 DiagID = diag::warn_unused_label;
2184 else
2185 DiagID = diag::warn_unused_variable;
2186
2187 SourceLocation DiagLoc = D->getLocation();
2188 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2189}
2190
2192 DiagReceiverTy DiagReceiver) {
2193 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2194 // it's not really unused.
2195 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2196 return;
2197
2198 // In C++, `_` variables behave as if they were maybe_unused
2199 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2200 return;
2201
2202 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2203
2204 if (Ty->isReferenceType() || Ty->isDependentType())
2205 return;
2206
2207 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2208 if (Tag->hasAttr<UnusedAttr>())
2209 return;
2210 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2211 // mimic gcc's behavior.
2212 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2213 RD && !RD->hasAttr<WarnUnusedAttr>())
2214 return;
2215 }
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);
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 = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2251 : diag::warn_unused_but_set_variable;
2252 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2253}
2254
2256 Sema::DiagReceiverTy DiagReceiver) {
2257 // Verify that we have no forward references left. If so, there was a goto
2258 // or address of a label taken, but no definition of it. Label fwd
2259 // definitions are indicated with a null substmt which is also not a resolved
2260 // MS inline assembly label name.
2261 bool Diagnose = false;
2262 if (L->isMSAsmLabel())
2263 Diagnose = !L->isResolvedMSAsmLabel();
2264 else
2265 Diagnose = L->getStmt() == nullptr;
2266 if (Diagnose)
2267 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2268 << L);
2269}
2270
2272 S->applyNRVO();
2273
2274 if (S->decl_empty()) return;
2276 "Scope shouldn't contain decls!");
2277
2278 /// We visit the decls in non-deterministic order, but we want diagnostics
2279 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2280 /// and sort the diagnostics before emitting them, after we visited all decls.
2281 struct LocAndDiag {
2282 SourceLocation Loc;
2283 std::optional<SourceLocation> PreviousDeclLoc;
2285 };
2287 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2288 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2289 };
2290 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2291 SourceLocation PreviousDeclLoc,
2292 PartialDiagnostic PD) {
2293 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2294 };
2295
2296 for (auto *TmpD : S->decls()) {
2297 assert(TmpD && "This decl didn't get pushed??");
2298
2299 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2300 NamedDecl *D = cast<NamedDecl>(TmpD);
2301
2302 // Diagnose unused variables in this scope.
2304 DiagnoseUnusedDecl(D, addDiag);
2305 if (const auto *RD = dyn_cast<RecordDecl>(D))
2306 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2307 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2308 DiagnoseUnusedButSetDecl(VD, addDiag);
2309 RefsMinusAssignments.erase(VD);
2310 }
2311 }
2312
2313 if (!D->getDeclName()) continue;
2314
2315 // If this was a forward reference to a label, verify it was defined.
2316 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2317 CheckPoppedLabel(LD, *this, addDiag);
2318
2319 // Partial translation units that are created in incremental processing must
2320 // not clean up the IdResolver because PTUs should take into account the
2321 // declarations that came from previous PTUs.
2322 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2324 IdResolver.RemoveDecl(D);
2325
2326 // Warn on it if we are shadowing a declaration.
2327 auto ShadowI = ShadowingDecls.find(D);
2328 if (ShadowI != ShadowingDecls.end()) {
2329 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2330 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2331 PDiag(diag::warn_ctor_parm_shadows_field)
2332 << D << FD << FD->getParent());
2333 }
2334 ShadowingDecls.erase(ShadowI);
2335 }
2336 }
2337
2338 llvm::sort(DeclDiags,
2339 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2340 // The particular order for diagnostics is not important, as long
2341 // as the order is deterministic. Using the raw location is going
2342 // to generally be in source order unless there are macro
2343 // expansions involved.
2344 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2345 });
2346 for (const LocAndDiag &D : DeclDiags) {
2347 Diag(D.Loc, D.PD);
2348 if (D.PreviousDeclLoc)
2349 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2350 }
2351}
2352
2354 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2355 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2356 (S->isClassScope() && !getLangOpts().CPlusPlus))
2357 S = S->getParent();
2358 return S;
2359}
2360
2361static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2363 switch (Error) {
2365 return "";
2367 return BuiltinInfo.getHeaderName(ID);
2369 return "stdio.h";
2371 return "setjmp.h";
2373 return "ucontext.h";
2374 }
2375 llvm_unreachable("unhandled error kind");
2376}
2377
2379 unsigned ID, SourceLocation Loc) {
2380 DeclContext *Parent = Context.getTranslationUnitDecl();
2381
2382 if (getLangOpts().CPlusPlus) {
2384 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2385 CLinkageDecl->setImplicit();
2386 Parent->addDecl(CLinkageDecl);
2387 Parent = CLinkageDecl;
2388 }
2389
2391 if (Context.BuiltinInfo.isImmediate(ID)) {
2392 assert(getLangOpts().CPlusPlus20 &&
2393 "consteval builtins should only be available in C++20 mode");
2394 ConstexprKind = ConstexprSpecKind::Consteval;
2395 }
2396
2398 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2399 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2400 Type->isFunctionProtoType(), ConstexprKind);
2401 New->setImplicit();
2402 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2403
2404 // Create Decl objects for each parameter, adding them to the
2405 // FunctionDecl.
2406 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2408 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2410 Context, New, SourceLocation(), SourceLocation(), nullptr,
2411 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2412 parm->setScopeInfo(0, i);
2413 Params.push_back(parm);
2414 }
2415 New->setParams(Params);
2416 }
2417
2419 return New;
2420}
2421
2423 Scope *S, bool ForRedeclaration,
2424 SourceLocation Loc) {
2426
2428 QualType R = Context.GetBuiltinType(ID, Error);
2429 if (Error) {
2430 if (!ForRedeclaration)
2431 return nullptr;
2432
2433 // If we have a builtin without an associated type we should not emit a
2434 // warning when we were not able to find a type for it.
2436 Context.BuiltinInfo.allowTypeMismatch(ID))
2437 return nullptr;
2438
2439 // If we could not find a type for setjmp it is because the jmp_buf type was
2440 // not defined prior to the setjmp declaration.
2442 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2443 << Context.BuiltinInfo.getName(ID);
2444 return nullptr;
2445 }
2446
2447 // Generally, we emit a warning that the declaration requires the
2448 // appropriate header.
2449 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2450 << getHeaderName(Context.BuiltinInfo, ID, Error)
2451 << Context.BuiltinInfo.getName(ID);
2452 return nullptr;
2453 }
2454
2455 if (!ForRedeclaration &&
2456 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2457 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2458 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2459 : diag::ext_implicit_lib_function_decl)
2460 << Context.BuiltinInfo.getName(ID) << R;
2461 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2462 Diag(Loc, diag::note_include_header_or_declare)
2463 << Header << Context.BuiltinInfo.getName(ID);
2464 }
2465
2466 if (R.isNull())
2467 return nullptr;
2468
2469 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2471
2472 // TUScope is the translation-unit scope to insert this function into.
2473 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2474 // relate Scopes to DeclContexts, and probably eliminate CurContext
2475 // entirely, but we're not there yet.
2476 DeclContext *SavedContext = CurContext;
2477 CurContext = New->getDeclContext();
2479 CurContext = SavedContext;
2480 return New;
2481}
2482
2483/// Typedef declarations don't have linkage, but they still denote the same
2484/// entity if their types are the same.
2485/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2486/// isSameEntity.
2487static void
2490 // This is only interesting when modules are enabled.
2491 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2492 return;
2493
2494 // Empty sets are uninteresting.
2495 if (Previous.empty())
2496 return;
2497
2498 LookupResult::Filter Filter = Previous.makeFilter();
2499 while (Filter.hasNext()) {
2500 NamedDecl *Old = Filter.next();
2501
2502 // Non-hidden declarations are never ignored.
2503 if (S.isVisible(Old))
2504 continue;
2505
2506 // Declarations of the same entity are not ignored, even if they have
2507 // different linkages.
2508 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2509 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2510 Decl->getUnderlyingType()))
2511 continue;
2512
2513 // If both declarations give a tag declaration a typedef name for linkage
2514 // purposes, then they declare the same entity.
2515 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2516 Decl->getAnonDeclWithTypedefName())
2517 continue;
2518 }
2519
2520 Filter.erase();
2521 }
2522
2523 Filter.done();
2524}
2525
2527 QualType OldType;
2528 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2529 OldType = OldTypedef->getUnderlyingType();
2530 else
2531 OldType = Context.getTypeDeclType(Old);
2532 QualType NewType = New->getUnderlyingType();
2533
2534 if (NewType->isVariablyModifiedType()) {
2535 // Must not redefine a typedef with a variably-modified type.
2536 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2537 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2538 << Kind << NewType;
2539 if (Old->getLocation().isValid())
2540 notePreviousDefinition(Old, New->getLocation());
2541 New->setInvalidDecl();
2542 return true;
2543 }
2544
2545 if (OldType != NewType &&
2546 !OldType->isDependentType() &&
2547 !NewType->isDependentType() &&
2548 !Context.hasSameType(OldType, NewType)) {
2549 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2550 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2551 << Kind << NewType << OldType;
2552 if (Old->getLocation().isValid())
2553 notePreviousDefinition(Old, New->getLocation());
2554 New->setInvalidDecl();
2555 return true;
2556 }
2557 return false;
2558}
2559
2561 LookupResult &OldDecls) {
2562 // If the new decl is known invalid already, don't bother doing any
2563 // merging checks.
2564 if (New->isInvalidDecl()) return;
2565
2566 // Allow multiple definitions for ObjC built-in typedefs.
2567 // FIXME: Verify the underlying types are equivalent!
2568 if (getLangOpts().ObjC) {
2569 const IdentifierInfo *TypeID = New->getIdentifier();
2570 switch (TypeID->getLength()) {
2571 default: break;
2572 case 2:
2573 {
2574 if (!TypeID->isStr("id"))
2575 break;
2576 QualType T = New->getUnderlyingType();
2577 if (!T->isPointerType())
2578 break;
2579 if (!T->isVoidPointerType()) {
2581 if (!PT->isStructureType())
2582 break;
2583 }
2584 Context.setObjCIdRedefinitionType(T);
2585 // Install the built-in type for 'id', ignoring the current definition.
2586 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2587 Context.getObjCIdType());
2588 return;
2589 }
2590 case 5:
2591 if (!TypeID->isStr("Class"))
2592 break;
2593 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2594 // Install the built-in type for 'Class', ignoring the current definition.
2595 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2596 Context.getObjCClassType());
2597 return;
2598 case 3:
2599 if (!TypeID->isStr("SEL"))
2600 break;
2601 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2602 // Install the built-in type for 'SEL', ignoring the current definition.
2603 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2604 Context.getObjCSelType());
2605 return;
2606 }
2607 // Fall through - the typedef name was not a builtin type.
2608 }
2609
2610 // Verify the old decl was also a type.
2611 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2612 if (!Old) {
2613 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2614 << New->getDeclName();
2615
2616 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2617 if (OldD->getLocation().isValid())
2618 notePreviousDefinition(OldD, New->getLocation());
2619
2620 return New->setInvalidDecl();
2621 }
2622
2623 // If the old declaration is invalid, just give up here.
2624 if (Old->isInvalidDecl())
2625 return New->setInvalidDecl();
2626
2627 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2628 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2629 auto *NewTag = New->getAnonDeclWithTypedefName();
2630 NamedDecl *Hidden = nullptr;
2631 if (OldTag && NewTag &&
2632 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2633 !hasVisibleDefinition(OldTag, &Hidden)) {
2634 // There is a definition of this tag, but it is not visible. Use it
2635 // instead of our tag.
2636 if (OldTD->isModed())
2637 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2638 OldTD->getUnderlyingType());
2639 else
2640 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2641
2642 // Make the old tag definition visible.
2644
2646 }
2647 }
2648
2649 // If the typedef types are not identical, reject them in all languages and
2650 // with any extensions enabled.
2651 if (isIncompatibleTypedef(Old, New))
2652 return;
2653
2654 // The types match. Link up the redeclaration chain and merge attributes if
2655 // the old declaration was a typedef.
2656 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2657 New->setPreviousDecl(Typedef);
2659 }
2660
2661 if (getLangOpts().MicrosoftExt)
2662 return;
2663
2664 if (getLangOpts().CPlusPlus) {
2665 // C++ [dcl.typedef]p2:
2666 // In a given non-class scope, a typedef specifier can be used to
2667 // redefine the name of any type declared in that scope to refer
2668 // to the type to which it already refers.
2670 return;
2671
2672 // C++0x [dcl.typedef]p4:
2673 // In a given class scope, a typedef specifier can be used to redefine
2674 // any class-name declared in that scope that is not also a typedef-name
2675 // to refer to the type to which it already refers.
2676 //
2677 // This wording came in via DR424, which was a correction to the
2678 // wording in DR56, which accidentally banned code like:
2679 //
2680 // struct S {
2681 // typedef struct A { } A;
2682 // };
2683 //
2684 // in the C++03 standard. We implement the C++0x semantics, which
2685 // allow the above but disallow
2686 //
2687 // struct S {
2688 // typedef int I;
2689 // typedef int I;
2690 // };
2691 //
2692 // since that was the intent of DR56.
2693 if (!isa<TypedefNameDecl>(Old))
2694 return;
2695
2696 Diag(New->getLocation(), diag::err_redefinition)
2697 << New->getDeclName();
2698 notePreviousDefinition(Old, New->getLocation());
2699 return New->setInvalidDecl();
2700 }
2701
2702 // Modules always permit redefinition of typedefs, as does C11.
2703 if (getLangOpts().Modules || getLangOpts().C11)
2704 return;
2705
2706 // If we have a redefinition of a typedef in C, emit a warning. This warning
2707 // is normally mapped to an error, but can be controlled with
2708 // -Wtypedef-redefinition. If either the original or the redefinition is
2709 // in a system header, don't emit this for compatibility with GCC.
2710 if (getDiagnostics().getSuppressSystemWarnings() &&
2711 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2712 (Old->isImplicit() ||
2713 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2714 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2715 return;
2716
2717 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2718 << New->getDeclName();
2719 notePreviousDefinition(Old, New->getLocation());
2720}
2721
2723 // If this was an unscoped enumeration, yank all of its enumerators
2724 // out of the scope.
2725 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2726 Scope *EnumScope = getNonFieldDeclScope(S);
2727 for (auto *ECD : ED->enumerators()) {
2728 assert(EnumScope->isDeclScope(ECD));
2729 EnumScope->RemoveDecl(ECD);
2730 IdResolver.RemoveDecl(ECD);
2731 }
2732 }
2733}
2734
2735/// DeclhasAttr - returns true if decl Declaration already has the target
2736/// attribute.
2737static bool DeclHasAttr(const Decl *D, const Attr *A) {
2738 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2739 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2740 for (const auto *i : D->attrs())
2741 if (i->getKind() == A->getKind()) {
2742 if (Ann) {
2743 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2744 return true;
2745 continue;
2746 }
2747 // FIXME: Don't hardcode this check
2748 if (OA && isa<OwnershipAttr>(i))
2749 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2750 return true;
2751 }
2752
2753 return false;
2754}
2755
2757 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2758 return VD->isThisDeclarationADefinition();
2759 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2760 return TD->isCompleteDefinition() || TD->isBeingDefined();
2761 return true;
2762}
2763
2764/// Merge alignment attributes from \p Old to \p New, taking into account the
2765/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2766///
2767/// \return \c true if any attributes were added to \p New.
2768static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2769 // Look for alignas attributes on Old, and pick out whichever attribute
2770 // specifies the strictest alignment requirement.
2771 AlignedAttr *OldAlignasAttr = nullptr;
2772 AlignedAttr *OldStrictestAlignAttr = nullptr;
2773 unsigned OldAlign = 0;
2774 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2775 // FIXME: We have no way of representing inherited dependent alignments
2776 // in a case like:
2777 // template<int A, int B> struct alignas(A) X;
2778 // template<int A, int B> struct alignas(B) X {};
2779 // For now, we just ignore any alignas attributes which are not on the
2780 // definition in such a case.
2781 if (I->isAlignmentDependent())
2782 return false;
2783
2784 if (I->isAlignas())
2785 OldAlignasAttr = I;
2786
2787 unsigned Align = I->getAlignment(S.Context);
2788 if (Align > OldAlign) {
2789 OldAlign = Align;
2790 OldStrictestAlignAttr = I;
2791 }
2792 }
2793
2794 // Look for alignas attributes on New.
2795 AlignedAttr *NewAlignasAttr = nullptr;
2796 unsigned NewAlign = 0;
2797 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2798 if (I->isAlignmentDependent())
2799 return false;
2800
2801 if (I->isAlignas())
2802 NewAlignasAttr = I;
2803
2804 unsigned Align = I->getAlignment(S.Context);
2805 if (Align > NewAlign)
2806 NewAlign = Align;
2807 }
2808
2809 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2810 // Both declarations have 'alignas' attributes. We require them to match.
2811 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2812 // fall short. (If two declarations both have alignas, they must both match
2813 // every definition, and so must match each other if there is a definition.)
2814
2815 // If either declaration only contains 'alignas(0)' specifiers, then it
2816 // specifies the natural alignment for the type.
2817 if (OldAlign == 0 || NewAlign == 0) {
2818 QualType Ty;
2819 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2820 Ty = VD->getType();
2821 else
2823
2824 if (OldAlign == 0)
2825 OldAlign = S.Context.getTypeAlign(Ty);
2826 if (NewAlign == 0)
2827 NewAlign = S.Context.getTypeAlign(Ty);
2828 }
2829
2830 if (OldAlign != NewAlign) {
2831 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2834 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2835 }
2836 }
2837
2838 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2839 // C++11 [dcl.align]p6:
2840 // if any declaration of an entity has an alignment-specifier,
2841 // every defining declaration of that entity shall specify an
2842 // equivalent alignment.
2843 // C11 6.7.5/7:
2844 // If the definition of an object does not have an alignment
2845 // specifier, any other declaration of that object shall also
2846 // have no alignment specifier.
2847 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2848 << OldAlignasAttr;
2849 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2850 << OldAlignasAttr;
2851 }
2852
2853 bool AnyAdded = false;
2854
2855 // Ensure we have an attribute representing the strictest alignment.
2856 if (OldAlign > NewAlign) {
2857 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2858 Clone->setInherited(true);
2859 New->addAttr(Clone);
2860 AnyAdded = true;
2861 }
2862
2863 // Ensure we have an alignas attribute if the old declaration had one.
2864 if (OldAlignasAttr && !NewAlignasAttr &&
2865 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2866 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2867 Clone->setInherited(true);
2868 New->addAttr(Clone);
2869 AnyAdded = true;
2870 }
2871
2872 return AnyAdded;
2873}
2874
2875#define WANT_DECL_MERGE_LOGIC
2876#include "clang/Sema/AttrParsedAttrImpl.inc"
2877#undef WANT_DECL_MERGE_LOGIC
2878
2880 const InheritableAttr *Attr,
2882 // Diagnose any mutual exclusions between the attribute that we want to add
2883 // and attributes that already exist on the declaration.
2884 if (!DiagnoseMutualExclusions(S, D, Attr))
2885 return false;
2886
2887 // This function copies an attribute Attr from a previous declaration to the
2888 // new declaration D if the new declaration doesn't itself have that attribute
2889 // yet or if that attribute allows duplicates.
2890 // If you're adding a new attribute that requires logic different from
2891 // "use explicit attribute on decl if present, else use attribute from
2892 // previous decl", for example if the attribute needs to be consistent
2893 // between redeclarations, you need to call a custom merge function here.
2894 InheritableAttr *NewAttr = nullptr;
2895 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2896 NewAttr = S.mergeAvailabilityAttr(
2897 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2898 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2899 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2900 AA->getPriority(), AA->getEnvironment());
2901 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2902 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2903 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2904 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2905 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2906 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2907 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2908 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2909 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2910 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2911 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2912 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2913 FA->getFirstArg());
2914 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2915 NewAttr = S.mergeFormatMatchesAttr(
2916 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2917 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2918 NewAttr = S.mergeModularFormatAttr(
2919 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2920 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2921 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2922 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2923 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2924 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2925 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2926 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2927 IA->getInheritanceModel());
2928 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2929 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2930 &S.Context.Idents.get(AA->getSpelling()));
2931 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2934 // CUDA target attributes are part of function signature for
2935 // overloading purposes and must not be merged.
2936 return false;
2937 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2938 NewAttr = S.mergeMinSizeAttr(D, *MA);
2939 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2940 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
2941 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2942 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2943 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2944 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2945 else if (isa<AlignedAttr>(Attr))
2946 // AlignedAttrs are handled separately, because we need to handle all
2947 // such attributes on a declaration at the same time.
2948 NewAttr = nullptr;
2953 NewAttr = nullptr;
2954 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2955 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2956 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2957 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
2958 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2959 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
2960 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2961 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2962 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2963 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2964 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2965 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2966 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
2967 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
2968 NT->getZ());
2969 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
2970 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
2971 WS->getPreferred(),
2972 WS->getSpelledArgsCount());
2973 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
2974 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
2975 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
2976 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
2977 else if (isa<SuppressAttr>(Attr))
2978 // Do nothing. Each redeclaration should be suppressed separately.
2979 NewAttr = nullptr;
2980 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
2981 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
2982 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2983 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2984 else if (const auto *PA = dyn_cast<PersonalityAttr>(Attr))
2985 NewAttr = S.mergePersonalityAttr(D, PA->getRoutine(), *PA);
2986
2987 if (NewAttr) {
2988 NewAttr->setInherited(true);
2989 D->addAttr(NewAttr);
2990 if (isa<MSInheritanceAttr>(NewAttr))
2992 return true;
2993 }
2994
2995 return false;
2996}
2997
2998static const NamedDecl *getDefinition(const Decl *D) {
2999 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3000 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3001 return Def;
3002 return nullptr;
3003 }
3004 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3005 const VarDecl *Def = VD->getDefinition();
3006 if (Def)
3007 return Def;
3008 return VD->getActingDefinition();
3009 }
3010 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3011 const FunctionDecl *Def = nullptr;
3012 if (FD->isDefined(Def, true))
3013 return Def;
3014 }
3015 return nullptr;
3016}
3017
3018static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3019 for (const auto *Attribute : D->attrs())
3020 if (Attribute->getKind() == Kind)
3021 return true;
3022 return false;
3023}
3024
3025/// checkNewAttributesAfterDef - If we already have a definition, check that
3026/// there are no new attributes in this declaration.
3027static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3028 if (!New->hasAttrs())
3029 return;
3030
3031 const NamedDecl *Def = getDefinition(Old);
3032 if (!Def || Def == New)
3033 return;
3034
3035 AttrVec &NewAttributes = New->getAttrs();
3036 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3037 Attr *NewAttribute = NewAttributes[I];
3038
3039 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3040 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3041 SkipBodyInfo SkipBody;
3042 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3043
3044 // If we're skipping this definition, drop the "alias" attribute.
3045 if (SkipBody.ShouldSkip) {
3046 NewAttributes.erase(NewAttributes.begin() + I);
3047 --E;
3048 continue;
3049 }
3050 } else {
3051 VarDecl *VD = cast<VarDecl>(New);
3052 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3054 ? diag::err_alias_after_tentative
3055 : diag::err_redefinition;
3056 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3057 if (Diag == diag::err_redefinition)
3058 S.notePreviousDefinition(Def, VD->getLocation());
3059 else
3060 S.Diag(Def->getLocation(), diag::note_previous_definition);
3061 VD->setInvalidDecl();
3062 }
3063 ++I;
3064 continue;
3065 }
3066
3067 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3068 // Tentative definitions are only interesting for the alias check above.
3069 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3070 ++I;
3071 continue;
3072 }
3073 }
3074
3075 if (hasAttribute(Def, NewAttribute->getKind())) {
3076 ++I;
3077 continue; // regular attr merging will take care of validating this.
3078 }
3079
3080 if (isa<C11NoReturnAttr>(NewAttribute)) {
3081 // C's _Noreturn is allowed to be added to a function after it is defined.
3082 ++I;
3083 continue;
3084 } else if (isa<UuidAttr>(NewAttribute)) {
3085 // msvc will allow a subsequent definition to add an uuid to a class
3086 ++I;
3087 continue;
3089 NewAttribute) &&
3090 NewAttribute->isStandardAttributeSyntax()) {
3091 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3092 // deprecated attribute can later be re-declared with the attribute and
3093 // vice-versa.
3094 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3095 // maybe_unused attribute can later be redeclared with the attribute and
3096 // vice versa.
3097 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3098 // nodiscard attribute can later be redeclared with the attribute and
3099 // vice-versa.
3100 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3101 ++I;
3102 continue;
3103 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3104 if (AA->isAlignas()) {
3105 // C++11 [dcl.align]p6:
3106 // if any declaration of an entity has an alignment-specifier,
3107 // every defining declaration of that entity shall specify an
3108 // equivalent alignment.
3109 // C11 6.7.5/7:
3110 // If the definition of an object does not have an alignment
3111 // specifier, any other declaration of that object shall also
3112 // have no alignment specifier.
3113 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3114 << AA;
3115 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3116 << AA;
3117 NewAttributes.erase(NewAttributes.begin() + I);
3118 --E;
3119 continue;
3120 }
3121 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3122 // If there is a C definition followed by a redeclaration with this
3123 // attribute then there are two different definitions. In C++, prefer the
3124 // standard diagnostics.
3125 if (!S.getLangOpts().CPlusPlus) {
3126 S.Diag(NewAttribute->getLocation(),
3127 diag::err_loader_uninitialized_redeclaration);
3128 S.Diag(Def->getLocation(), diag::note_previous_definition);
3129 NewAttributes.erase(NewAttributes.begin() + I);
3130 --E;
3131 continue;
3132 }
3133 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3134 cast<VarDecl>(New)->isInline() &&
3135 !cast<VarDecl>(New)->isInlineSpecified()) {
3136 // Don't warn about applying selectany to implicitly inline variables.
3137 // Older compilers and language modes would require the use of selectany
3138 // to make such variables inline, and it would have no effect if we
3139 // honored it.
3140 ++I;
3141 continue;
3142 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3143 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3144 // declarations after definitions.
3145 ++I;
3146 continue;
3147 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3148 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3149 // error since the definition will have already been created without
3150 // the semantic effects of the attribute having been applied.
3151 S.Diag(NewAttribute->getLocation(),
3152 diag::err_sycl_entry_point_after_definition)
3153 << NewAttribute;
3154 S.Diag(Def->getLocation(), diag::note_previous_definition);
3155 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3156 ++I;
3157 continue;
3158 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3159 // SYCLExternalAttr may be added after a definition.
3160 ++I;
3161 continue;
3162 }
3163
3164 S.Diag(NewAttribute->getLocation(),
3165 diag::warn_attribute_precede_definition);
3166 S.Diag(Def->getLocation(), diag::note_previous_definition);
3167 NewAttributes.erase(NewAttributes.begin() + I);
3168 --E;
3169 }
3170}
3171
3172static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3173 const ConstInitAttr *CIAttr,
3174 bool AttrBeforeInit) {
3175 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3176
3177 // Figure out a good way to write this specifier on the old declaration.
3178 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3179 // enough of the attribute list spelling information to extract that without
3180 // heroics.
3181 std::string SuitableSpelling;
3182 if (S.getLangOpts().CPlusPlus20)
3183 SuitableSpelling = std::string(
3184 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3185 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3186 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3187 InsertLoc, {tok::l_square, tok::l_square,
3188 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3189 S.PP.getIdentifierInfo("require_constant_initialization"),
3190 tok::r_square, tok::r_square}));
3191 if (SuitableSpelling.empty())
3192 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3193 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3194 S.PP.getIdentifierInfo("require_constant_initialization"),
3195 tok::r_paren, tok::r_paren}));
3196 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3197 SuitableSpelling = "constinit";
3198 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3199 SuitableSpelling = "[[clang::require_constant_initialization]]";
3200 if (SuitableSpelling.empty())
3201 SuitableSpelling = "__attribute__((require_constant_initialization))";
3202 SuitableSpelling += " ";
3203
3204 if (AttrBeforeInit) {
3205 // extern constinit int a;
3206 // int a = 0; // error (missing 'constinit'), accepted as extension
3207 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3208 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3209 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3210 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3211 } else {
3212 // int a = 0;
3213 // constinit extern int a; // error (missing 'constinit')
3214 S.Diag(CIAttr->getLocation(),
3215 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3216 : diag::warn_require_const_init_added_too_late)
3217 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3218 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3219 << CIAttr->isConstinit()
3220 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3221 }
3222}
3223
3226 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3227 UsedAttr *NewAttr = OldAttr->clone(Context);
3228 NewAttr->setInherited(true);
3229 New->addAttr(NewAttr);
3230 }
3231 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3232 RetainAttr *NewAttr = OldAttr->clone(Context);
3233 NewAttr->setInherited(true);
3234 New->addAttr(NewAttr);
3235 }
3236
3237 if (!Old->hasAttrs() && !New->hasAttrs())
3238 return;
3239
3240 // [dcl.constinit]p1:
3241 // If the [constinit] specifier is applied to any declaration of a
3242 // variable, it shall be applied to the initializing declaration.
3243 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3244 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3245 if (bool(OldConstInit) != bool(NewConstInit)) {
3246 const auto *OldVD = cast<VarDecl>(Old);
3247 auto *NewVD = cast<VarDecl>(New);
3248
3249 // Find the initializing declaration. Note that we might not have linked
3250 // the new declaration into the redeclaration chain yet.
3251 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3252 if (!InitDecl &&
3253 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3254 InitDecl = NewVD;
3255
3256 if (InitDecl == NewVD) {
3257 // This is the initializing declaration. If it would inherit 'constinit',
3258 // that's ill-formed. (Note that we do not apply this to the attribute
3259 // form).
3260 if (OldConstInit && OldConstInit->isConstinit())
3261 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3262 /*AttrBeforeInit=*/true);
3263 } else if (NewConstInit) {
3264 // This is the first time we've been told that this declaration should
3265 // have a constant initializer. If we already saw the initializing
3266 // declaration, this is too late.
3267 if (InitDecl && InitDecl != NewVD) {
3268 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3269 /*AttrBeforeInit=*/false);
3270 NewVD->dropAttr<ConstInitAttr>();
3271 }
3272 }
3273 }
3274
3275 // Attributes declared post-definition are currently ignored.
3276 checkNewAttributesAfterDef(*this, New, Old);
3277
3278 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3279 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3280 if (!OldA->isEquivalent(NewA)) {
3281 // This redeclaration changes __asm__ label.
3282 Diag(New->getLocation(), diag::err_different_asm_label);
3283 Diag(OldA->getLocation(), diag::note_previous_declaration);
3284 }
3285 } else if (Old->isUsed()) {
3286 // This redeclaration adds an __asm__ label to a declaration that has
3287 // already been ODR-used.
3288 Diag(New->getLocation(), diag::err_late_asm_label_name)
3289 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3290 }
3291 }
3292
3293 // Re-declaration cannot add abi_tag's.
3294 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3295 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3296 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3297 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3298 Diag(NewAbiTagAttr->getLocation(),
3299 diag::err_new_abi_tag_on_redeclaration)
3300 << NewTag;
3301 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3302 }
3303 }
3304 } else {
3305 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3306 Diag(Old->getLocation(), diag::note_previous_declaration);
3307 }
3308 }
3309
3310 // This redeclaration adds a section attribute.
3311 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3312 if (auto *VD = dyn_cast<VarDecl>(New)) {
3313 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3314 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3315 Diag(Old->getLocation(), diag::note_previous_declaration);
3316 }
3317 }
3318 }
3319
3320 // Redeclaration adds code-seg attribute.
3321 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3322 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3323 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3324 Diag(New->getLocation(), diag::warn_mismatched_section)
3325 << 0 /*codeseg*/;
3326 Diag(Old->getLocation(), diag::note_previous_declaration);
3327 }
3328
3329 if (!Old->hasAttrs())
3330 return;
3331
3332 bool foundAny = New->hasAttrs();
3333
3334 // Ensure that any moving of objects within the allocated map is done before
3335 // we process them.
3336 if (!foundAny) New->setAttrs(AttrVec());
3337
3338 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3339 // Ignore deprecated/unavailable/availability attributes if requested.
3341 if (isa<DeprecatedAttr>(I) ||
3344 switch (AMK) {
3346 continue;
3347
3352 LocalAMK = AMK;
3353 break;
3354 }
3355 }
3356
3357 // Already handled.
3358 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3359 continue;
3360
3362 if (auto *FD = dyn_cast<FunctionDecl>(New);
3363 FD &&
3364 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3365 continue; // Don't propagate inferred noreturn attributes to explicit
3366 }
3367
3368 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3369 foundAny = true;
3370 }
3371
3372 if (mergeAlignedAttrs(*this, New, Old))
3373 foundAny = true;
3374
3375 if (!foundAny) New->dropAttrs();
3376}
3377
3379 for (const Attr *A : D->attrs())
3380 checkAttrIsTypeDependent(D, A);
3381}
3382
3383// Returns the number of added attributes.
3384template <class T>
3385static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3386 Sema &S) {
3387 unsigned found = 0;
3388 for (const auto *I : From->specific_attrs<T>()) {
3389 if (!DeclHasAttr(To, I)) {
3390 T *newAttr = cast<T>(I->clone(S.Context));
3391 newAttr->setInherited(true);
3392 To->addAttr(newAttr);
3393 ++found;
3394 }
3395 }
3396 return found;
3397}
3398
3399template <class F>
3400static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3401 F &&propagator) {
3402 if (!From->hasAttrs()) {
3403 return;
3404 }
3405
3406 bool foundAny = To->hasAttrs();
3407
3408 // Ensure that any moving of objects within the allocated map is
3409 // done before we process them.
3410 if (!foundAny)
3411 To->setAttrs(AttrVec());
3412
3413 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3414
3415 if (!foundAny)
3416 To->dropAttrs();
3417}
3418
3419/// mergeParamDeclAttributes - Copy attributes from the old parameter
3420/// to the new one.
3422 const ParmVarDecl *oldDecl,
3423 Sema &S) {
3424 // C++11 [dcl.attr.depend]p2:
3425 // The first declaration of a function shall specify the
3426 // carries_dependency attribute for its declarator-id if any declaration
3427 // of the function specifies the carries_dependency attribute.
3428 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3429 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3430 S.Diag(CDA->getLocation(),
3431 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3432 // Find the first declaration of the parameter.
3433 // FIXME: Should we build redeclaration chains for function parameters?
3434 const FunctionDecl *FirstFD =
3435 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3436 const ParmVarDecl *FirstVD =
3437 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3438 S.Diag(FirstVD->getLocation(),
3439 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3440 }
3441
3443 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3444 unsigned found = 0;
3445 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3446 // Propagate the lifetimebound attribute from parameters to the
3447 // most recent declaration. Note that this doesn't include the implicit
3448 // 'this' parameter, as the attribute is applied to the function type in
3449 // that case.
3450 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3451 return found;
3452 });
3453}
3454
3456 const ASTContext &Ctx) {
3457
3458 auto NoSizeInfo = [&Ctx](QualType Ty) {
3459 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3460 return true;
3461 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3462 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3463 return false;
3464 };
3465
3466 // `type[]` is equivalent to `type *` and `type[*]`.
3467 if (NoSizeInfo(Old) && NoSizeInfo(New))
3468 return true;
3469
3470 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3471 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3472 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3473 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3474 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3475 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3476 return false;
3477 return true;
3478 }
3479
3480 // Only compare size, ignore Size modifiers and CVR.
3481 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3482 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3484 }
3485
3486 // Don't try to compare dependent sized array
3487 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3488 return true;
3489 }
3490
3491 return Old == New;
3492}
3493
3494static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3495 const ParmVarDecl *OldParam,
3496 Sema &S) {
3497 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3498 if (auto Newnullability = NewParam->getType()->getNullability()) {
3499 if (*Oldnullability != *Newnullability) {
3500 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3502 *Newnullability,
3504 != 0))
3506 *Oldnullability,
3508 != 0));
3509 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3510 }
3511 } else {
3512 QualType NewT = NewParam->getType();
3513 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3514 NewParam->setType(NewT);
3515 }
3516 }
3517 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3518 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3519 if (OldParamDT && NewParamDT &&
3520 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3521 QualType OldParamOT = OldParamDT->getOriginalType();
3522 QualType NewParamOT = NewParamDT->getOriginalType();
3523 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3524 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3525 << NewParam << NewParamOT;
3526 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3527 << OldParamOT;
3528 }
3529 }
3530}
3531
3532namespace {
3533
3534/// Used in MergeFunctionDecl to keep track of function parameters in
3535/// C.
3536struct GNUCompatibleParamWarning {
3537 ParmVarDecl *OldParm;
3538 ParmVarDecl *NewParm;
3539 QualType PromotedType;
3540};
3541
3542} // end anonymous namespace
3543
3544// Determine whether the previous declaration was a definition, implicit
3545// declaration, or a declaration.
3546template <typename T>
3547static std::pair<diag::kind, SourceLocation>
3549 diag::kind PrevDiag;
3550 SourceLocation OldLocation = Old->getLocation();
3551 if (Old->isThisDeclarationADefinition())
3552 PrevDiag = diag::note_previous_definition;
3553 else if (Old->isImplicit()) {
3554 PrevDiag = diag::note_previous_implicit_declaration;
3555 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3556 if (FD->getBuiltinID())
3557 PrevDiag = diag::note_previous_builtin_declaration;
3558 }
3559 if (OldLocation.isInvalid())
3560 OldLocation = New->getLocation();
3561 } else
3562 PrevDiag = diag::note_previous_declaration;
3563 return std::make_pair(PrevDiag, OldLocation);
3564}
3565
3566/// canRedefineFunction - checks if a function can be redefined. Currently,
3567/// only extern inline functions can be redefined, and even then only in
3568/// GNU89 mode.
3569static bool canRedefineFunction(const FunctionDecl *FD,
3570 const LangOptions& LangOpts) {
3571 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3572 !LangOpts.CPlusPlus &&
3573 FD->isInlineSpecified() &&
3574 FD->getStorageClass() == SC_Extern);
3575}
3576
3577const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3578 const AttributedType *AT = T->getAs<AttributedType>();
3579 while (AT && !AT->isCallingConv())
3580 AT = AT->getModifiedType()->getAs<AttributedType>();
3581 return AT;
3582}
3583
3584template <typename T>
3585static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3586 const DeclContext *DC = Old->getDeclContext();
3587 if (DC->isRecord())
3588 return false;
3589
3590 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3591 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3592 return true;
3593 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3594 return true;
3595 return false;
3596}
3597
3598template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3599static bool isExternC(VarTemplateDecl *) { return false; }
3600static bool isExternC(FunctionTemplateDecl *) { return false; }
3601
3602/// Check whether a redeclaration of an entity introduced by a
3603/// using-declaration is valid, given that we know it's not an overload
3604/// (nor a hidden tag declaration).
3605template<typename ExpectedDecl>
3607 ExpectedDecl *New) {
3608 // C++11 [basic.scope.declarative]p4:
3609 // Given a set of declarations in a single declarative region, each of
3610 // which specifies the same unqualified name,
3611 // -- they shall all refer to the same entity, or all refer to functions
3612 // and function templates; or
3613 // -- exactly one declaration shall declare a class name or enumeration
3614 // name that is not a typedef name and the other declarations shall all
3615 // refer to the same variable or enumerator, or all refer to functions
3616 // and function templates; in this case the class name or enumeration
3617 // name is hidden (3.3.10).
3618
3619 // C++11 [namespace.udecl]p14:
3620 // If a function declaration in namespace scope or block scope has the
3621 // same name and the same parameter-type-list as a function introduced
3622 // by a using-declaration, and the declarations do not declare the same
3623 // function, the program is ill-formed.
3624
3625 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3626 if (Old &&
3627 !Old->getDeclContext()->getRedeclContext()->Equals(
3628 New->getDeclContext()->getRedeclContext()) &&
3629 !(isExternC(Old) && isExternC(New)))
3630 Old = nullptr;
3631
3632 if (!Old) {
3633 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3634 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3635 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3636 return true;
3637 }
3638 return false;
3639}
3640
3642 const FunctionDecl *B) {
3643 assert(A->getNumParams() == B->getNumParams());
3644
3645 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3646 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3647 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3648 if (AttrA == AttrB)
3649 return true;
3650 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3651 AttrA->isDynamic() == AttrB->isDynamic();
3652 };
3653
3654 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3655}
3656
3657/// If necessary, adjust the semantic declaration context for a qualified
3658/// declaration to name the correct inline namespace within the qualifier.
3660 DeclaratorDecl *OldD) {
3661 // The only case where we need to update the DeclContext is when
3662 // redeclaration lookup for a qualified name finds a declaration
3663 // in an inline namespace within the context named by the qualifier:
3664 //
3665 // inline namespace N { int f(); }
3666 // int ::f(); // Sema DC needs adjusting from :: to N::.
3667 //
3668 // For unqualified declarations, the semantic context *can* change
3669 // along the redeclaration chain (for local extern declarations,
3670 // extern "C" declarations, and friend declarations in particular).
3671 if (!NewD->getQualifier())
3672 return;
3673
3674 // NewD is probably already in the right context.
3675 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3676 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3677 if (NamedDC->Equals(SemaDC))
3678 return;
3679
3680 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3681 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3682 "unexpected context for redeclaration");
3683
3684 auto *LexDC = NewD->getLexicalDeclContext();
3685 auto FixSemaDC = [=](NamedDecl *D) {
3686 if (!D)
3687 return;
3688 D->setDeclContext(SemaDC);
3689 D->setLexicalDeclContext(LexDC);
3690 };
3691
3692 FixSemaDC(NewD);
3693 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3694 FixSemaDC(FD->getDescribedFunctionTemplate());
3695 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3696 FixSemaDC(VD->getDescribedVarTemplate());
3697}
3698
3700 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3701 // Verify the old decl was also a function.
3702 FunctionDecl *Old = OldD->getAsFunction();
3703 if (!Old) {
3704 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3705 // We don't need to check the using friend pattern from other module unit
3706 // since we should have diagnosed such cases in its unit already.
3707 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3708 Diag(New->getLocation(), diag::err_using_decl_friend);
3709 Diag(Shadow->getTargetDecl()->getLocation(),
3710 diag::note_using_decl_target);
3711 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3712 << 0;
3713 return true;
3714 }
3715
3716 // Check whether the two declarations might declare the same function or
3717 // function template.
3718 if (FunctionTemplateDecl *NewTemplate =
3719 New->getDescribedFunctionTemplate()) {
3721 NewTemplate))
3722 return true;
3723 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3724 ->getAsFunction();
3725 } else {
3726 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3727 return true;
3728 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3729 }
3730 } else {
3731 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3732 << New->getDeclName();
3733 notePreviousDefinition(OldD, New->getLocation());
3734 return true;
3735 }
3736 }
3737
3738 // If the old declaration was found in an inline namespace and the new
3739 // declaration was qualified, update the DeclContext to match.
3741
3742 // If the old declaration is invalid, just give up here.
3743 if (Old->isInvalidDecl())
3744 return true;
3745
3746 // Disallow redeclaration of some builtins.
3747 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3748 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3749 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3750 << Old << Old->getType();
3751 return true;
3752 }
3753
3754 diag::kind PrevDiag;
3755 SourceLocation OldLocation;
3756 std::tie(PrevDiag, OldLocation) =
3758
3759 // Don't complain about this if we're in GNU89 mode and the old function
3760 // is an extern inline function.
3761 // Don't complain about specializations. They are not supposed to have
3762 // storage classes.
3763 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3764 New->getStorageClass() == SC_Static &&
3765 Old->hasExternalFormalLinkage() &&
3766 !New->getTemplateSpecializationInfo() &&
3768 if (getLangOpts().MicrosoftExt) {
3769 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3770 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3771 } else {
3772 Diag(New->getLocation(), diag::err_static_non_static) << New;
3773 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3774 return true;
3775 }
3776 }
3777
3778 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3779 if (!Old->hasAttr<InternalLinkageAttr>()) {
3780 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3781 << ILA;
3782 Diag(Old->getLocation(), diag::note_previous_declaration);
3783 New->dropAttr<InternalLinkageAttr>();
3784 }
3785
3786 if (auto *EA = New->getAttr<ErrorAttr>()) {
3787 if (!Old->hasAttr<ErrorAttr>()) {
3788 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3789 Diag(Old->getLocation(), diag::note_previous_declaration);
3790 New->dropAttr<ErrorAttr>();
3791 }
3792 }
3793
3795 return true;
3796
3797 if (!getLangOpts().CPlusPlus) {
3798 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3799 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3800 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3801 << New << OldOvl;
3802
3803 // Try our best to find a decl that actually has the overloadable
3804 // attribute for the note. In most cases (e.g. programs with only one
3805 // broken declaration/definition), this won't matter.
3806 //
3807 // FIXME: We could do this if we juggled some extra state in
3808 // OverloadableAttr, rather than just removing it.
3809 const Decl *DiagOld = Old;
3810 if (OldOvl) {
3811 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3812 const auto *A = D->getAttr<OverloadableAttr>();
3813 return A && !A->isImplicit();
3814 });
3815 // If we've implicitly added *all* of the overloadable attrs to this
3816 // chain, emitting a "previous redecl" note is pointless.
3817 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3818 }
3819
3820 if (DiagOld)
3821 Diag(DiagOld->getLocation(),
3822 diag::note_attribute_overloadable_prev_overload)
3823 << OldOvl;
3824
3825 if (OldOvl)
3826 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3827 else
3828 New->dropAttr<OverloadableAttr>();
3829 }
3830 }
3831
3832 // It is not permitted to redeclare an SME function with different SME
3833 // attributes.
3834 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3835 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3836 << New->getType() << Old->getType();
3837 Diag(OldLocation, diag::note_previous_declaration);
3838 return true;
3839 }
3840
3841 // If a function is first declared with a calling convention, but is later
3842 // declared or defined without one, all following decls assume the calling
3843 // convention of the first.
3844 //
3845 // It's OK if a function is first declared without a calling convention,
3846 // but is later declared or defined with the default calling convention.
3847 //
3848 // To test if either decl has an explicit calling convention, we look for
3849 // AttributedType sugar nodes on the type as written. If they are missing or
3850 // were canonicalized away, we assume the calling convention was implicit.
3851 //
3852 // Note also that we DO NOT return at this point, because we still have
3853 // other tests to run.
3854 QualType OldQType = Context.getCanonicalType(Old->getType());
3855 QualType NewQType = Context.getCanonicalType(New->getType());
3856 const FunctionType *OldType = cast<FunctionType>(OldQType);
3857 const FunctionType *NewType = cast<FunctionType>(NewQType);
3858 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3859 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3860 bool RequiresAdjustment = false;
3861
3862 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3864 const FunctionType *FT =
3865 First->getType().getCanonicalType()->castAs<FunctionType>();
3867 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3868 if (!NewCCExplicit) {
3869 // Inherit the CC from the previous declaration if it was specified
3870 // there but not here.
3871 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3872 RequiresAdjustment = true;
3873 } else if (Old->getBuiltinID()) {
3874 // Builtin attribute isn't propagated to the new one yet at this point,
3875 // so we check if the old one is a builtin.
3876
3877 // Calling Conventions on a Builtin aren't really useful and setting a
3878 // default calling convention and cdecl'ing some builtin redeclarations is
3879 // common, so warn and ignore the calling convention on the redeclaration.
3880 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3881 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3883 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3884 RequiresAdjustment = true;
3885 } else {
3886 // Calling conventions aren't compatible, so complain.
3887 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3888 Diag(New->getLocation(), diag::err_cconv_change)
3889 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3890 << !FirstCCExplicit
3891 << (!FirstCCExplicit ? "" :
3893
3894 // Put the note on the first decl, since it is the one that matters.
3895 Diag(First->getLocation(), diag::note_previous_declaration);
3896 return true;
3897 }
3898 }
3899
3900 // FIXME: diagnose the other way around?
3901 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3902 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3903 RequiresAdjustment = true;
3904 }
3905
3906 // If the declaration is marked with cfi_unchecked_callee but the definition
3907 // isn't, the definition is also cfi_unchecked_callee.
3908 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3909 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3910 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3911 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3912
3913 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3914 EPI2.CFIUncheckedCallee = true;
3915 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3916 FPT2->getParamTypes(), EPI2);
3917 NewType = cast<FunctionType>(NewQType);
3918 New->setType(NewQType);
3919 }
3920 }
3921 }
3922
3923 // Merge regparm attribute.
3924 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3925 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3926 if (NewTypeInfo.getHasRegParm()) {
3927 Diag(New->getLocation(), diag::err_regparm_mismatch)
3928 << NewType->getRegParmType()
3929 << OldType->getRegParmType();
3930 Diag(OldLocation, diag::note_previous_declaration);
3931 return true;
3932 }
3933
3934 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3935 RequiresAdjustment = true;
3936 }
3937
3938 // Merge ns_returns_retained attribute.
3939 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3940 if (NewTypeInfo.getProducesResult()) {
3941 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3942 << "'ns_returns_retained'";
3943 Diag(OldLocation, diag::note_previous_declaration);
3944 return true;
3945 }
3946
3947 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3948 RequiresAdjustment = true;
3949 }
3950
3951 if (OldTypeInfo.getNoCallerSavedRegs() !=
3952 NewTypeInfo.getNoCallerSavedRegs()) {
3953 if (NewTypeInfo.getNoCallerSavedRegs()) {
3954 AnyX86NoCallerSavedRegistersAttr *Attr =
3955 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3956 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3957 Diag(OldLocation, diag::note_previous_declaration);
3958 return true;
3959 }
3960
3961 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3962 RequiresAdjustment = true;
3963 }
3964
3965 if (RequiresAdjustment) {
3966 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3967 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3968 New->setType(QualType(AdjustedType, 0));
3969 NewQType = Context.getCanonicalType(New->getType());
3970 }
3971
3972 // If this redeclaration makes the function inline, we may need to add it to
3973 // UndefinedButUsed.
3974 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
3975 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
3976 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
3977 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3978 SourceLocation()));
3979
3980 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3981 // about it.
3982 if (New->hasAttr<GNUInlineAttr>() &&
3983 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3984 UndefinedButUsed.erase(Old->getCanonicalDecl());
3985 }
3986
3987 // If pass_object_size params don't match up perfectly, this isn't a valid
3988 // redeclaration.
3989 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3991 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3992 << New->getDeclName();
3993 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3994 return true;
3995 }
3996
3997 QualType OldQTypeForComparison = OldQType;
3998 if (Context.hasAnyFunctionEffects()) {
3999 const auto OldFX = Old->getFunctionEffects();
4000 const auto NewFX = New->getFunctionEffects();
4001 if (OldFX != NewFX) {
4002 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4003 for (const auto &Diff : Diffs) {
4004 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
4005 Diag(New->getLocation(),
4006 diag::warn_mismatched_func_effect_redeclaration)
4007 << Diff.effectName();
4008 Diag(Old->getLocation(), diag::note_previous_declaration);
4009 }
4010 }
4011 // Following a warning, we could skip merging effects from the previous
4012 // declaration, but that would trigger an additional "conflicting types"
4013 // error.
4014 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4016 FunctionEffectSet MergedFX =
4017 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4018 if (!MergeErrs.empty())
4019 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4020 Old->getLocation());
4021
4022 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4023 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4024 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4025 NewFPT->getParamTypes(), EPI);
4026
4027 New->setType(ModQT);
4028 NewQType = New->getType();
4029
4030 // Revise OldQTForComparison to include the merged effects,
4031 // so as not to fail due to differences later.
4032 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4033 EPI = OldFPT->getExtProtoInfo();
4034 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4035 OldQTypeForComparison = Context.getFunctionType(
4036 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4037 }
4038 if (OldFX.empty()) {
4039 // A redeclaration may add the attribute to a previously seen function
4040 // body which needs to be verified.
4041 maybeAddDeclWithEffects(Old, MergedFX);
4042 }
4043 }
4044 }
4045 }
4046
4047 if (getLangOpts().CPlusPlus) {
4048 OldQType = Context.getCanonicalType(Old->getType());
4049 NewQType = Context.getCanonicalType(New->getType());
4050
4051 // Go back to the type source info to compare the declared return types,
4052 // per C++1y [dcl.type.auto]p13:
4053 // Redeclarations or specializations of a function or function template
4054 // with a declared return type that uses a placeholder type shall also
4055 // use that placeholder, not a deduced type.
4056 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4057 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4058 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4059 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4060 OldDeclaredReturnType)) {
4061 QualType ResQT;
4062 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4063 OldDeclaredReturnType->isObjCObjectPointerType())
4064 // FIXME: This does the wrong thing for a deduced return type.
4065 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4066 if (ResQT.isNull()) {
4067 if (New->isCXXClassMember() && New->isOutOfLine())
4068 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4069 << New << New->getReturnTypeSourceRange();
4070 else if (Old->isExternC() && New->isExternC() &&
4071 !Old->hasAttr<OverloadableAttr>() &&
4072 !New->hasAttr<OverloadableAttr>())
4073 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4074 else
4075 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4076 << New->getReturnTypeSourceRange();
4077 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4078 << Old->getReturnTypeSourceRange();
4079 return true;
4080 }
4081 else
4082 NewQType = ResQT;
4083 }
4084
4085 QualType OldReturnType = OldType->getReturnType();
4086 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4087 if (OldReturnType != NewReturnType) {
4088 // If this function has a deduced return type and has already been
4089 // defined, copy the deduced value from the old declaration.
4090 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4091 if (OldAT && OldAT->isDeduced()) {
4092 QualType DT = OldAT->getDeducedType();
4093 if (DT.isNull()) {
4094 New->setType(SubstAutoTypeDependent(New->getType()));
4095 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4096 } else {
4097 New->setType(SubstAutoType(New->getType(), DT));
4098 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4099 }
4100 }
4101 }
4102
4103 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4104 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4105 if (OldMethod && NewMethod) {
4106 // Preserve triviality.
4107 NewMethod->setTrivial(OldMethod->isTrivial());
4108
4109 // MSVC allows explicit template specialization at class scope:
4110 // 2 CXXMethodDecls referring to the same function will be injected.
4111 // We don't want a redeclaration error.
4112 bool IsClassScopeExplicitSpecialization =
4113 OldMethod->isFunctionTemplateSpecialization() &&
4115 bool isFriend = NewMethod->getFriendObjectKind();
4116
4117 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4118 !IsClassScopeExplicitSpecialization) {
4119 // -- Member function declarations with the same name and the
4120 // same parameter types cannot be overloaded if any of them
4121 // is a static member function declaration.
4122 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4123 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4124 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4125 return true;
4126 }
4127
4128 // C++ [class.mem]p1:
4129 // [...] A member shall not be declared twice in the
4130 // member-specification, except that a nested class or member
4131 // class template can be declared and then later defined.
4132 if (!inTemplateInstantiation()) {
4133 unsigned NewDiag;
4134 if (isa<CXXConstructorDecl>(OldMethod))
4135 NewDiag = diag::err_constructor_redeclared;
4136 else if (isa<CXXDestructorDecl>(NewMethod))
4137 NewDiag = diag::err_destructor_redeclared;
4138 else if (isa<CXXConversionDecl>(NewMethod))
4139 NewDiag = diag::err_conv_function_redeclared;
4140 else
4141 NewDiag = diag::err_member_redeclared;
4142
4143 Diag(New->getLocation(), NewDiag);
4144 } else {
4145 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4146 << New << New->getType();
4147 }
4148 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4149 return true;
4150
4151 // Complain if this is an explicit declaration of a special
4152 // member that was initially declared implicitly.
4153 //
4154 // As an exception, it's okay to befriend such methods in order
4155 // to permit the implicit constructor/destructor/operator calls.
4156 } else if (OldMethod->isImplicit()) {
4157 if (isFriend) {
4158 NewMethod->setImplicit();
4159 } else {
4160 Diag(NewMethod->getLocation(),
4161 diag::err_definition_of_implicitly_declared_member)
4162 << New << getSpecialMember(OldMethod);
4163 return true;
4164 }
4165 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4166 Diag(NewMethod->getLocation(),
4167 diag::err_definition_of_explicitly_defaulted_member)
4168 << getSpecialMember(OldMethod);
4169 return true;
4170 }
4171 }
4172
4173 // C++1z [over.load]p2
4174 // Certain function declarations cannot be overloaded:
4175 // -- Function declarations that differ only in the return type,
4176 // the exception specification, or both cannot be overloaded.
4177
4178 // Check the exception specifications match. This may recompute the type of
4179 // both Old and New if it resolved exception specifications, so grab the
4180 // types again after this. Because this updates the type, we do this before
4181 // any of the other checks below, which may update the "de facto" NewQType
4182 // but do not necessarily update the type of New.
4184 return true;
4185
4186 // C++11 [dcl.attr.noreturn]p1:
4187 // The first declaration of a function shall specify the noreturn
4188 // attribute if any declaration of that function specifies the noreturn
4189 // attribute.
4190 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4191 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4192 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4193 << NRA;
4194 Diag(Old->getLocation(), diag::note_previous_declaration);
4195 }
4196
4197 // C++11 [dcl.attr.depend]p2:
4198 // The first declaration of a function shall specify the
4199 // carries_dependency attribute for its declarator-id if any declaration
4200 // of the function specifies the carries_dependency attribute.
4201 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
4202 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
4203 Diag(CDA->getLocation(),
4204 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
4205 Diag(Old->getFirstDecl()->getLocation(),
4206 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
4207 }
4208
4209 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4210 // When a function is declared with SYCL_EXTERNAL, that macro must be
4211 // used on the first declaration of that function in the translation unit.
4212 // Redeclarations of the function in the same translation unit may
4213 // optionally use SYCL_EXTERNAL, but this is not required.
4214 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4215 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4216 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4217 << SEA;
4218 Diag(Old->getLocation(), diag::note_previous_declaration);
4219 }
4220
4221 // (C++98 8.3.5p3):
4222 // All declarations for a function shall agree exactly in both the
4223 // return type and the parameter-type-list.
4224 // We also want to respect all the extended bits except noreturn.
4225
4226 // noreturn should now match unless the old type info didn't have it.
4227 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4228 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4229 const FunctionType *OldTypeForComparison
4230 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4231 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4232 assert(OldQTypeForComparison.isCanonical());
4233 }
4234
4236 // As a special case, retain the language linkage from previous
4237 // declarations of a friend function as an extension.
4238 //
4239 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4240 // and is useful because there's otherwise no way to specify language
4241 // linkage within class scope.
4242 //
4243 // Check cautiously as the friend object kind isn't yet complete.
4244 if (New->getFriendObjectKind() != Decl::FOK_None) {
4245 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4246 Diag(OldLocation, PrevDiag);
4247 } else {
4248 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4249 Diag(OldLocation, PrevDiag);
4250 return true;
4251 }
4252 }
4253
4254 // HLSL check parameters for matching ABI specifications.
4255 if (getLangOpts().HLSL) {
4256 if (HLSL().CheckCompatibleParameterABI(New, Old))
4257 return true;
4258
4259 // If no errors are generated when checking parameter ABIs we can check if
4260 // the two declarations have the same type ignoring the ABIs and if so,
4261 // the declarations can be merged. This case for merging is only valid in
4262 // HLSL because there are no valid cases of merging mismatched parameter
4263 // ABIs except the HLSL implicit in and explicit in.
4264 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4265 NewQType))
4266 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4267 // Fall through for conflicting redeclarations and redefinitions.
4268 }
4269
4270 // If the function types are compatible, merge the declarations. Ignore the
4271 // exception specifier because it was already checked above in
4272 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4273 // about incompatible types under -fms-compatibility.
4274 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4275 NewQType))
4276 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4277
4278 // If the types are imprecise (due to dependent constructs in friends or
4279 // local extern declarations), it's OK if they differ. We'll check again
4280 // during instantiation.
4281 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4282 return false;
4283
4284 // Fall through for conflicting redeclarations and redefinitions.
4285 }
4286
4287 // C: Function types need to be compatible, not identical. This handles
4288 // duplicate function decls like "void f(int); void f(enum X);" properly.
4289 if (!getLangOpts().CPlusPlus) {
4290 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4291 // type is specified by a function definition that contains a (possibly
4292 // empty) identifier list, both shall agree in the number of parameters
4293 // and the type of each parameter shall be compatible with the type that
4294 // results from the application of default argument promotions to the
4295 // type of the corresponding identifier. ...
4296 // This cannot be handled by ASTContext::typesAreCompatible() because that
4297 // doesn't know whether the function type is for a definition or not when
4298 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4299 // we need to cover here is that the number of arguments agree as the
4300 // default argument promotion rules were already checked by
4301 // ASTContext::typesAreCompatible().
4302 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4303 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4304 if (Old->hasInheritedPrototype())
4305 Old = Old->getCanonicalDecl();
4306 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4307 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4308 return true;
4309 }
4310
4311 // If we are merging two functions where only one of them has a prototype,
4312 // we may have enough information to decide to issue a diagnostic that the
4313 // function without a prototype will change behavior in C23. This handles
4314 // cases like:
4315 // void i(); void i(int j);
4316 // void i(int j); void i();
4317 // void i(); void i(int j) {}
4318 // See ActOnFinishFunctionBody() for other cases of the behavior change
4319 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4320 // type without a prototype.
4321 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4322 !New->isImplicit() && !Old->isImplicit()) {
4323 const FunctionDecl *WithProto, *WithoutProto;
4324 if (New->hasWrittenPrototype()) {
4325 WithProto = New;
4326 WithoutProto = Old;
4327 } else {
4328 WithProto = Old;
4329 WithoutProto = New;
4330 }
4331
4332 if (WithProto->getNumParams() != 0) {
4333 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4334 // The one without the prototype will be changing behavior in C23, so
4335 // warn about that one so long as it's a user-visible declaration.
4336 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4337 if (WithoutProto == New)
4338 IsWithoutProtoADef = NewDeclIsDefn;
4339 else
4340 IsWithProtoADef = NewDeclIsDefn;
4341 Diag(WithoutProto->getLocation(),
4342 diag::warn_non_prototype_changes_behavior)
4343 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4344 << (WithoutProto == Old) << IsWithProtoADef;
4345
4346 // The reason the one without the prototype will be changing behavior
4347 // is because of the one with the prototype, so note that so long as
4348 // it's a user-visible declaration. There is one exception to this:
4349 // when the new declaration is a definition without a prototype, the
4350 // old declaration with a prototype is not the cause of the issue,
4351 // and that does not need to be noted because the one with a
4352 // prototype will not change behavior in C23.
4353 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4354 !IsWithoutProtoADef)
4355 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4356 }
4357 }
4358 }
4359
4360 if (Context.typesAreCompatible(OldQType, NewQType)) {
4361 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4362 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4363 const FunctionProtoType *OldProto = nullptr;
4364 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4365 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4366 // The old declaration provided a function prototype, but the
4367 // new declaration does not. Merge in the prototype.
4368 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4369 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4370 OldProto->getParamTypes(),
4371 OldProto->getExtProtoInfo());
4372 New->setType(NewQType);
4373 New->setHasInheritedPrototype();
4374
4375 // Synthesize parameters with the same types.
4377 for (const auto &ParamType : OldProto->param_types()) {
4379 Context, New, SourceLocation(), SourceLocation(), nullptr,
4380 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4381 Param->setScopeInfo(0, Params.size());
4382 Param->setImplicit();
4383 Params.push_back(Param);
4384 }
4385
4386 New->setParams(Params);
4387 }
4388
4389 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4390 }
4391 }
4392
4393 // Check if the function types are compatible when pointer size address
4394 // spaces are ignored.
4395 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4396 return false;
4397
4398 // GNU C permits a K&R definition to follow a prototype declaration
4399 // if the declared types of the parameters in the K&R definition
4400 // match the types in the prototype declaration, even when the
4401 // promoted types of the parameters from the K&R definition differ
4402 // from the types in the prototype. GCC then keeps the types from
4403 // the prototype.
4404 //
4405 // If a variadic prototype is followed by a non-variadic K&R definition,
4406 // the K&R definition becomes variadic. This is sort of an edge case, but
4407 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4408 // C99 6.9.1p8.
4409 if (!getLangOpts().CPlusPlus &&
4410 Old->hasPrototype() && !New->hasPrototype() &&
4411 New->getType()->getAs<FunctionProtoType>() &&
4412 Old->getNumParams() == New->getNumParams()) {
4415 const FunctionProtoType *OldProto
4416 = Old->getType()->getAs<FunctionProtoType>();
4417 const FunctionProtoType *NewProto
4418 = New->getType()->getAs<FunctionProtoType>();
4419
4420 // Determine whether this is the GNU C extension.
4421 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4422 NewProto->getReturnType());
4423 bool LooseCompatible = !MergedReturn.isNull();
4424 for (unsigned Idx = 0, End = Old->getNumParams();
4425 LooseCompatible && Idx != End; ++Idx) {
4426 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4427 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4428 if (Context.typesAreCompatible(OldParm->getType(),
4429 NewProto->getParamType(Idx))) {
4430 ArgTypes.push_back(NewParm->getType());
4431 } else if (Context.typesAreCompatible(OldParm->getType(),
4432 NewParm->getType(),
4433 /*CompareUnqualified=*/true)) {
4434 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4435 NewProto->getParamType(Idx) };
4436 Warnings.push_back(Warn);
4437 ArgTypes.push_back(NewParm->getType());
4438 } else
4439 LooseCompatible = false;
4440 }
4441
4442 if (LooseCompatible) {
4443 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4444 Diag(Warnings[Warn].NewParm->getLocation(),
4445 diag::ext_param_promoted_not_compatible_with_prototype)
4446 << Warnings[Warn].PromotedType
4447 << Warnings[Warn].OldParm->getType();
4448 if (Warnings[Warn].OldParm->getLocation().isValid())
4449 Diag(Warnings[Warn].OldParm->getLocation(),
4450 diag::note_previous_declaration);
4451 }
4452
4453 if (MergeTypeWithOld)
4454 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4455 OldProto->getExtProtoInfo()));
4456 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4457 }
4458
4459 // Fall through to diagnose conflicting types.
4460 }
4461
4462 // A function that has already been declared has been redeclared or
4463 // defined with a different type; show an appropriate diagnostic.
4464
4465 // If the previous declaration was an implicitly-generated builtin
4466 // declaration, then at the very least we should use a specialized note.
4467 unsigned BuiltinID;
4468 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4469 // If it's actually a library-defined builtin function like 'malloc'
4470 // or 'printf', just warn about the incompatible redeclaration.
4471 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4472 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4473 Diag(OldLocation, diag::note_previous_builtin_declaration)
4474 << Old << Old->getType();
4475 return false;
4476 }
4477
4478 PrevDiag = diag::note_previous_builtin_declaration;
4479 }
4480
4481 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4482 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4483 return true;
4484}
4485
4487 Scope *S, bool MergeTypeWithOld) {
4488 // Merge the attributes
4490
4491 // Merge "pure" flag.
4492 if (Old->isPureVirtual())
4493 New->setIsPureVirtual();
4494
4495 // Merge "used" flag.
4496 if (Old->getMostRecentDecl()->isUsed(false))
4497 New->setIsUsed();
4498
4499 // Merge attributes from the parameters. These can mismatch with K&R
4500 // declarations.
4501 if (New->getNumParams() == Old->getNumParams())
4502 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4503 ParmVarDecl *NewParam = New->getParamDecl(i);
4504 ParmVarDecl *OldParam = Old->getParamDecl(i);
4505 mergeParamDeclAttributes(NewParam, OldParam, *this);
4506 mergeParamDeclTypes(NewParam, OldParam, *this);
4507 }
4508
4509 if (getLangOpts().CPlusPlus)
4510 return MergeCXXFunctionDecl(New, Old, S);
4511
4512 // Merge the function types so the we get the composite types for the return
4513 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4514 // was visible.
4515 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4516 if (!Merged.isNull() && MergeTypeWithOld)
4517 New->setType(Merged);
4518
4519 return false;
4520}
4521
4523 ObjCMethodDecl *oldMethod) {
4524 // Merge the attributes, including deprecated/unavailable
4525 AvailabilityMergeKind MergeKind =
4527 ? (oldMethod->isOptional()
4530 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4533
4534 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4535
4536 // Merge attributes from the parameters.
4538 oe = oldMethod->param_end();
4540 ni = newMethod->param_begin(), ne = newMethod->param_end();
4541 ni != ne && oi != oe; ++ni, ++oi)
4542 mergeParamDeclAttributes(*ni, *oi, *this);
4543
4544 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4545}
4546
4548 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4549
4550 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4551 ? diag::err_redefinition_different_type
4552 : diag::err_redeclaration_different_type)
4553 << New->getDeclName() << New->getType() << Old->getType();
4554
4555 diag::kind PrevDiag;
4556 SourceLocation OldLocation;
4557 std::tie(PrevDiag, OldLocation)
4559 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4560 New->setInvalidDecl();
4561}
4562
4564 bool MergeTypeWithOld) {
4565 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4566 return;
4567
4568 QualType MergedT;
4569 if (getLangOpts().CPlusPlus) {
4570 if (New->getType()->isUndeducedType()) {
4571 // We don't know what the new type is until the initializer is attached.
4572 return;
4573 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4574 // These could still be something that needs exception specs checked.
4575 return MergeVarDeclExceptionSpecs(New, Old);
4576 }
4577 // C++ [basic.link]p10:
4578 // [...] the types specified by all declarations referring to a given
4579 // object or function shall be identical, except that declarations for an
4580 // array object can specify array types that differ by the presence or
4581 // absence of a major array bound (8.3.4).
4582 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4583 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4584 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4585
4586 // We are merging a variable declaration New into Old. If it has an array
4587 // bound, and that bound differs from Old's bound, we should diagnose the
4588 // mismatch.
4589 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4590 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4591 PrevVD = PrevVD->getPreviousDecl()) {
4592 QualType PrevVDTy = PrevVD->getType();
4593 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4594 continue;
4595
4596 if (!Context.hasSameType(New->getType(), PrevVDTy))
4597 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4598 }
4599 }
4600
4601 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4602 if (Context.hasSameType(OldArray->getElementType(),
4603 NewArray->getElementType()))
4604 MergedT = New->getType();
4605 }
4606 // FIXME: Check visibility. New is hidden but has a complete type. If New
4607 // has no array bound, it should not inherit one from Old, if Old is not
4608 // visible.
4609 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4610 if (Context.hasSameType(OldArray->getElementType(),
4611 NewArray->getElementType()))
4612 MergedT = Old->getType();
4613 }
4614 }
4615 else if (New->getType()->isObjCObjectPointerType() &&
4616 Old->getType()->isObjCObjectPointerType()) {
4617 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4618 Old->getType());
4619 }
4620 } else {
4621 // C 6.2.7p2:
4622 // All declarations that refer to the same object or function shall have
4623 // compatible type.
4624 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4625 }
4626 if (MergedT.isNull()) {
4627 // It's OK if we couldn't merge types if either type is dependent, for a
4628 // block-scope variable. In other cases (static data members of class
4629 // templates, variable templates, ...), we require the types to be
4630 // equivalent.
4631 // FIXME: The C++ standard doesn't say anything about this.
4632 if ((New->getType()->isDependentType() ||
4633 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4634 // If the old type was dependent, we can't merge with it, so the new type
4635 // becomes dependent for now. We'll reproduce the original type when we
4636 // instantiate the TypeSourceInfo for the variable.
4637 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4638 New->setType(Context.DependentTy);
4639 return;
4640 }
4641 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4642 }
4643
4644 // Don't actually update the type on the new declaration if the old
4645 // declaration was an extern declaration in a different scope.
4646 if (MergeTypeWithOld)
4647 New->setType(MergedT);
4648}
4649
4650static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4652 // C11 6.2.7p4:
4653 // For an identifier with internal or external linkage declared
4654 // in a scope in which a prior declaration of that identifier is
4655 // visible, if the prior declaration specifies internal or
4656 // external linkage, the type of the identifier at the later
4657 // declaration becomes the composite type.
4658 //
4659 // If the variable isn't visible, we do not merge with its type.
4660 if (Previous.isShadowed())
4661 return false;
4662
4663 if (S.getLangOpts().CPlusPlus) {
4664 // C++11 [dcl.array]p3:
4665 // If there is a preceding declaration of the entity in the same
4666 // scope in which the bound was specified, an omitted array bound
4667 // is taken to be the same as in that earlier declaration.
4668 return NewVD->isPreviousDeclInSameBlockScope() ||
4669 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4671 } else {
4672 // If the old declaration was function-local, don't merge with its
4673 // type unless we're in the same function.
4674 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4675 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4676 }
4677}
4678
4680 // If the new decl is already invalid, don't do any other checking.
4681 if (New->isInvalidDecl())
4682 return;
4683
4684 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4685 return;
4686
4687 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4688
4689 // Verify the old decl was also a variable or variable template.
4690 VarDecl *Old = nullptr;
4691 VarTemplateDecl *OldTemplate = nullptr;
4692 if (Previous.isSingleResult()) {
4693 if (NewTemplate) {
4694 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4695 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4696
4697 if (auto *Shadow =
4698 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4699 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4700 return New->setInvalidDecl();
4701 } else {
4702 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4703
4704 if (auto *Shadow =
4705 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4706 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4707 return New->setInvalidDecl();
4708 }
4709 }
4710 if (!Old) {
4711 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4712 << New->getDeclName();
4713 notePreviousDefinition(Previous.getRepresentativeDecl(),
4714 New->getLocation());
4715 return New->setInvalidDecl();
4716 }
4717
4718 // If the old declaration was found in an inline namespace and the new
4719 // declaration was qualified, update the DeclContext to match.
4721
4722 // Ensure the template parameters are compatible.
4723 if (NewTemplate &&
4725 OldTemplate->getTemplateParameters(),
4726 /*Complain=*/true, TPL_TemplateMatch))
4727 return New->setInvalidDecl();
4728
4729 // C++ [class.mem]p1:
4730 // A member shall not be declared twice in the member-specification [...]
4731 //
4732 // Here, we need only consider static data members.
4733 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4734 Diag(New->getLocation(), diag::err_duplicate_member)
4735 << New->getIdentifier();
4736 Diag(Old->getLocation(), diag::note_previous_declaration);
4737 New->setInvalidDecl();
4738 }
4739
4741 // Warn if an already-defined variable is made a weak_import in a subsequent
4742 // declaration
4743 if (New->hasAttr<WeakImportAttr>())
4744 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4745 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4746 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4747 Diag(D->getLocation(), diag::note_previous_definition);
4748 // Remove weak_import attribute on new declaration.
4749 New->dropAttr<WeakImportAttr>();
4750 break;
4751 }
4752 }
4753
4754 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4755 if (!Old->hasAttr<InternalLinkageAttr>()) {
4756 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4757 << ILA;
4758 Diag(Old->getLocation(), diag::note_previous_declaration);
4759 New->dropAttr<InternalLinkageAttr>();
4760 }
4761
4762 // Merge the types.
4763 VarDecl *MostRecent = Old->getMostRecentDecl();
4764 if (MostRecent != Old) {
4765 MergeVarDeclTypes(New, MostRecent,
4766 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4767 if (New->isInvalidDecl())
4768 return;
4769 }
4770
4772 if (New->isInvalidDecl())
4773 return;
4774
4775 diag::kind PrevDiag;
4776 SourceLocation OldLocation;
4777 std::tie(PrevDiag, OldLocation) =
4779
4780 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4781 if (New->getStorageClass() == SC_Static &&
4782 !New->isStaticDataMember() &&
4783 Old->hasExternalFormalLinkage()) {
4784 if (getLangOpts().MicrosoftExt) {
4785 Diag(New->getLocation(), diag::ext_static_non_static)
4786 << New->getDeclName();
4787 Diag(OldLocation, PrevDiag);
4788 } else {
4789 Diag(New->getLocation(), diag::err_static_non_static)
4790 << New->getDeclName();
4791 Diag(OldLocation, PrevDiag);
4792 return New->setInvalidDecl();
4793 }
4794 }
4795 // C99 6.2.2p4:
4796 // For an identifier declared with the storage-class specifier
4797 // extern in a scope in which a prior declaration of that
4798 // identifier is visible,23) if the prior declaration specifies
4799 // internal or external linkage, the linkage of the identifier at
4800 // the later declaration is the same as the linkage specified at
4801 // the prior declaration. If no prior declaration is visible, or
4802 // if the prior declaration specifies no linkage, then the
4803 // identifier has external linkage.
4804 if (New->hasExternalStorage() && Old->hasLinkage())
4805 /* Okay */;
4806 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4807 !New->isStaticDataMember() &&
4809 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4810 Diag(OldLocation, PrevDiag);
4811 return New->setInvalidDecl();
4812 }
4813
4814 // Check if extern is followed by non-extern and vice-versa.
4815 if (New->hasExternalStorage() &&
4816 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4817 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4818 Diag(OldLocation, PrevDiag);
4819 return New->setInvalidDecl();
4820 }
4821 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4822 !New->hasExternalStorage()) {
4823 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4824 Diag(OldLocation, PrevDiag);
4825 return New->setInvalidDecl();
4826 }
4827
4829 return;
4830
4831 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4832
4833 // FIXME: The test for external storage here seems wrong? We still
4834 // need to check for mismatches.
4835 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4836 // Don't complain about out-of-line definitions of static members.
4837 !(Old->getLexicalDeclContext()->isRecord() &&
4838 !New->getLexicalDeclContext()->isRecord())) {
4839 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4840 Diag(OldLocation, PrevDiag);
4841 return New->setInvalidDecl();
4842 }
4843
4844 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4845 if (VarDecl *Def = Old->getDefinition()) {
4846 // C++1z [dcl.fcn.spec]p4:
4847 // If the definition of a variable appears in a translation unit before
4848 // its first declaration as inline, the program is ill-formed.
4849 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4850 Diag(Def->getLocation(), diag::note_previous_definition);
4851 }
4852 }
4853
4854 // If this redeclaration makes the variable inline, we may need to add it to
4855 // UndefinedButUsed.
4856 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4857 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4858 !Old->isInAnotherModuleUnit())
4859 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4860 SourceLocation()));
4861
4862 if (New->getTLSKind() != Old->getTLSKind()) {
4863 if (!Old->getTLSKind()) {
4864 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4865 Diag(OldLocation, PrevDiag);
4866 } else if (!New->getTLSKind()) {
4867 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4868 Diag(OldLocation, PrevDiag);
4869 } else {
4870 // Do not allow redeclaration to change the variable between requiring
4871 // static and dynamic initialization.
4872 // FIXME: GCC allows this, but uses the TLS keyword on the first
4873 // declaration to determine the kind. Do we need to be compatible here?
4874 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4875 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4876 Diag(OldLocation, PrevDiag);
4877 }
4878 }
4879
4880 // C++ doesn't have tentative definitions, so go right ahead and check here.
4881 if (getLangOpts().CPlusPlus) {
4882 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4883 Old->getCanonicalDecl()->isConstexpr()) {
4884 // This definition won't be a definition any more once it's been merged.
4885 Diag(New->getLocation(),
4886 diag::warn_deprecated_redundant_constexpr_static_def);
4887 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4888 VarDecl *Def = Old->getDefinition();
4889 if (Def && checkVarDeclRedefinition(Def, New))
4890 return;
4891 }
4892 } else {
4893 // C++ may not have a tentative definition rule, but it has a different
4894 // rule about what constitutes a definition in the first place. See
4895 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4896 // contains the extern specifier and doesn't have an initializer, it's fine
4897 // in C++.
4898 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4899 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4900 << New;
4901 Diag(Old->getLocation(), diag::note_previous_declaration);
4902 }
4903 }
4904
4906 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4907 Diag(OldLocation, PrevDiag);
4908 New->setInvalidDecl();
4909 return;
4910 }
4911
4912 // Merge "used" flag.
4913 if (Old->getMostRecentDecl()->isUsed(false))
4914 New->setIsUsed();
4915
4916 // Keep a chain of previous declarations.
4917 New->setPreviousDecl(Old);
4918 if (NewTemplate)
4919 NewTemplate->setPreviousDecl(OldTemplate);
4920
4921 // Inherit access appropriately.
4922 New->setAccess(Old->getAccess());
4923 if (NewTemplate)
4924 NewTemplate->setAccess(New->getAccess());
4925
4926 if (Old->isInline())
4927 New->setImplicitlyInline();
4928}
4929
4932 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4933 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4934 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4935 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
4936 auto &HSI = PP.getHeaderSearchInfo();
4937 StringRef HdrFilename =
4938 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4939
4940 auto noteFromModuleOrInclude = [&](Module *Mod,
4941 SourceLocation IncLoc) -> bool {
4942 // Redefinition errors with modules are common with non modular mapped
4943 // headers, example: a non-modular header H in module A that also gets
4944 // included directly in a TU. Pointing twice to the same header/definition
4945 // is confusing, try to get better diagnostics when modules is on.
4946 if (IncLoc.isValid()) {
4947 if (Mod) {
4948 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4949 << HdrFilename.str() << Mod->getFullModuleName();
4950 if (!Mod->DefinitionLoc.isInvalid())
4951 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4952 << Mod->getFullModuleName();
4953 } else {
4954 Diag(IncLoc, diag::note_redefinition_include_same_file)
4955 << HdrFilename.str();
4956 }
4957 return true;
4958 }
4959
4960 return false;
4961 };
4962
4963 // Is it the same file and same offset? Provide more information on why
4964 // this leads to a redefinition error.
4965 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4966 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4967 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4968 bool EmittedDiag =
4969 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4970 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4971
4972 // If the header has no guards, emit a note suggesting one.
4973 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
4974 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4975
4976 if (EmittedDiag)
4977 return;
4978 }
4979
4980 // Redefinition coming from different files or couldn't do better above.
4981 if (Old->getLocation().isValid())
4982 Diag(Old->getLocation(), diag::note_previous_definition);
4983}
4984
4986 if (!hasVisibleDefinition(Old) &&
4987 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
4989 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() ||
4990 New->getDeclContext()->isDependentContext() ||
4991 New->hasAttr<SelectAnyAttr>())) {
4992 // The previous definition is hidden, and multiple definitions are
4993 // permitted (in separate TUs). Demote this to a declaration.
4994 New->demoteThisDefinitionToDeclaration();
4995
4996 // Make the canonical definition visible.
4997 if (auto *OldTD = Old->getDescribedVarTemplate())
5000 return false;
5001 } else {
5002 Diag(New->getLocation(), diag::err_redefinition) << New;
5003 notePreviousDefinition(Old, New->getLocation());
5004 New->setInvalidDecl();
5005 return true;
5006 }
5007}
5008
5010 DeclSpec &DS,
5011 const ParsedAttributesView &DeclAttrs,
5012 RecordDecl *&AnonRecord) {
5014 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5015}
5016
5017// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5018// disambiguate entities defined in different scopes.
5019// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5020// compatibility.
5021// We will pick our mangling number depending on which version of MSVC is being
5022// targeted.
5023static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5027}
5028
5029void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5030 if (!Context.getLangOpts().CPlusPlus)
5031 return;
5032
5033 if (isa<CXXRecordDecl>(Tag->getParent())) {
5034 // If this tag is the direct child of a class, number it if
5035 // it is anonymous.
5036 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5037 return;
5039 Context.getManglingNumberContext(Tag->getParent());
5040 Context.setManglingNumber(
5041 Tag, MCtx.getManglingNumber(
5042 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5043 return;
5044 }
5045
5046 // If this tag isn't a direct child of a class, number it if it is local.
5048 Decl *ManglingContextDecl;
5049 std::tie(MCtx, ManglingContextDecl) =
5050 getCurrentMangleNumberContext(Tag->getDeclContext());
5051 if (MCtx) {
5052 Context.setManglingNumber(
5053 Tag, MCtx->getManglingNumber(
5054 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5055 }
5056}
5057
5058namespace {
5059struct NonCLikeKind {
5060 enum {
5061 None,
5062 BaseClass,
5063 DefaultMemberInit,
5064 Lambda,
5065 Friend,
5066 OtherMember,
5067 Invalid,
5068 } Kind = None;
5069 SourceRange Range;
5070
5071 explicit operator bool() { return Kind != None; }
5072};
5073}
5074
5075/// Determine whether a class is C-like, according to the rules of C++
5076/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5077static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5078 if (RD->isInvalidDecl())
5079 return {NonCLikeKind::Invalid, {}};
5080
5081 // C++ [dcl.typedef]p9: [P1766R1]
5082 // An unnamed class with a typedef name for linkage purposes shall not
5083 //
5084 // -- have any base classes
5085 if (RD->getNumBases())
5086 return {NonCLikeKind::BaseClass,
5088 RD->bases_end()[-1].getEndLoc())};
5089 bool Invalid = false;
5090 for (Decl *D : RD->decls()) {
5091 // Don't complain about things we already diagnosed.
5092 if (D->isInvalidDecl()) {
5093 Invalid = true;
5094 continue;
5095 }
5096
5097 // -- have any [...] default member initializers
5098 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5099 if (FD->hasInClassInitializer()) {
5100 auto *Init = FD->getInClassInitializer();
5101 return {NonCLikeKind::DefaultMemberInit,
5102 Init ? Init->getSourceRange() : D->getSourceRange()};
5103 }
5104 continue;
5105 }
5106
5107 // FIXME: We don't allow friend declarations. This violates the wording of
5108 // P1766, but not the intent.
5109 if (isa<FriendDecl>(D))
5110 return {NonCLikeKind::Friend, D->getSourceRange()};
5111
5112 // -- declare any members other than non-static data members, member
5113 // enumerations, or member classes,
5115 isa<EnumDecl>(D))
5116 continue;
5117 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5118 if (!MemberRD) {
5119 if (D->isImplicit())
5120 continue;
5121 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5122 }
5123
5124 // -- contain a lambda-expression,
5125 if (MemberRD->isLambda())
5126 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5127
5128 // and all member classes shall also satisfy these requirements
5129 // (recursively).
5130 if (MemberRD->isThisDeclarationADefinition()) {
5131 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5132 return Kind;
5133 }
5134 }
5135
5136 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5137}
5138
5140 TypedefNameDecl *NewTD) {
5141 if (TagFromDeclSpec->isInvalidDecl())
5142 return;
5143
5144 // Do nothing if the tag already has a name for linkage purposes.
5145 if (TagFromDeclSpec->hasNameForLinkage())
5146 return;
5147
5148 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5149 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5150
5151 // The type must match the tag exactly; no qualifiers allowed.
5152 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5153 Context.getCanonicalTagType(TagFromDeclSpec))) {
5154 if (getLangOpts().CPlusPlus)
5155 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5156 return;
5157 }
5158
5159 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5160 // An unnamed class with a typedef name for linkage purposes shall [be
5161 // C-like].
5162 //
5163 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5164 // shouldn't happen, but there are constructs that the language rule doesn't
5165 // disallow for which we can't reasonably avoid computing linkage early.
5166 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5167 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5168 : NonCLikeKind();
5169 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5170 if (NonCLike || ChangesLinkage) {
5171 if (NonCLike.Kind == NonCLikeKind::Invalid)
5172 return;
5173
5174 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5175 if (ChangesLinkage) {
5176 // If the linkage changes, we can't accept this as an extension.
5177 if (NonCLike.Kind == NonCLikeKind::None)
5178 DiagID = diag::err_typedef_changes_linkage;
5179 else
5180 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5181 }
5182
5183 SourceLocation FixitLoc =
5184 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5185 llvm::SmallString<40> TextToInsert;
5186 TextToInsert += ' ';
5187 TextToInsert += NewTD->getIdentifier()->getName();
5188
5189 Diag(FixitLoc, DiagID)
5190 << isa<TypeAliasDecl>(NewTD)
5191 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5192 if (NonCLike.Kind != NonCLikeKind::None) {
5193 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5194 << NonCLike.Kind - 1 << NonCLike.Range;
5195 }
5196 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5197 << NewTD << isa<TypeAliasDecl>(NewTD);
5198
5199 if (ChangesLinkage)
5200 return;
5201 }
5202
5203 // Otherwise, set this as the anon-decl typedef for the tag.
5204 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5205
5206 // Now that we have a name for the tag, process API notes again.
5207 ProcessAPINotes(TagFromDeclSpec);
5208}
5209
5210static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5212 switch (T) {
5214 return 0;
5216 return 1;
5218 return 2;
5220 return 3;
5221 case DeclSpec::TST_enum:
5222 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5223 if (ED->isScopedUsingClassTag())
5224 return 5;
5225 if (ED->isScoped())
5226 return 6;
5227 }
5228 return 4;
5229 default:
5230 llvm_unreachable("unexpected type specifier");
5231 }
5232}
5233
5235 DeclSpec &DS,
5236 const ParsedAttributesView &DeclAttrs,
5237 MultiTemplateParamsArg TemplateParams,
5238 bool IsExplicitInstantiation,
5239 RecordDecl *&AnonRecord,
5240 SourceLocation EllipsisLoc) {
5241 Decl *TagD = nullptr;
5242 TagDecl *Tag = nullptr;
5248 TagD = DS.getRepAsDecl();
5249
5250 if (!TagD) // We probably had an error
5251 return nullptr;
5252
5253 // Note that the above type specs guarantee that the
5254 // type rep is a Decl, whereas in many of the others
5255 // it's a Type.
5256 if (isa<TagDecl>(TagD))
5257 Tag = cast<TagDecl>(TagD);
5258 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5259 Tag = CTD->getTemplatedDecl();
5260 }
5261
5262 if (Tag) {
5263 handleTagNumbering(Tag, S);
5264 Tag->setFreeStanding();
5265 if (Tag->isInvalidDecl())
5266 return Tag;
5267 }
5268
5269 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5270 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5271 // or incomplete types shall not be restrict-qualified."
5272 if (TypeQuals & DeclSpec::TQ_restrict)
5274 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5275 << DS.getSourceRange();
5276 }
5277
5278 if (DS.isInlineSpecified())
5279 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5280 << getLangOpts().CPlusPlus17;
5281
5282 if (DS.hasConstexprSpecifier()) {
5283 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5284 // and definitions of functions and variables.
5285 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5286 // the declaration of a function or function template
5287 if (Tag)
5288 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5290 << static_cast<int>(DS.getConstexprSpecifier());
5291 else if (getLangOpts().C23)
5292 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5293 else
5294 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5295 << static_cast<int>(DS.getConstexprSpecifier());
5296 // Don't emit warnings after this error.
5297 return TagD;
5298 }
5299
5301
5302 if (DS.isFriendSpecified()) {
5303 // If we're dealing with a decl but not a TagDecl, assume that
5304 // whatever routines created it handled the friendship aspect.
5305 if (TagD && !Tag)
5306 return nullptr;
5307 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5308 }
5309
5310 assert(EllipsisLoc.isInvalid() &&
5311 "Friend ellipsis but not friend-specified?");
5312
5313 // Track whether this decl-specifier declares anything.
5314 bool DeclaresAnything = true;
5315
5316 // Handle anonymous struct definitions.
5317 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5318 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5320 if (getLangOpts().CPlusPlus ||
5321 Record->getDeclContext()->isRecord()) {
5322 // If CurContext is a DeclContext that can contain statements,
5323 // RecursiveASTVisitor won't visit the decls that
5324 // BuildAnonymousStructOrUnion() will put into CurContext.
5325 // Also store them here so that they can be part of the
5326 // DeclStmt that gets created in this case.
5327 // FIXME: Also return the IndirectFieldDecls created by
5328 // BuildAnonymousStructOr union, for the same reason?
5329 if (CurContext->isFunctionOrMethod())
5330 AnonRecord = Record;
5331 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5332 Context.getPrintingPolicy());
5333 }
5334
5335 DeclaresAnything = false;
5336 }
5337 }
5338
5339 // C11 6.7.2.1p2:
5340 // A struct-declaration that does not declare an anonymous structure or
5341 // anonymous union shall contain a struct-declarator-list.
5342 //
5343 // This rule also existed in C89 and C99; the grammar for struct-declaration
5344 // did not permit a struct-declaration without a struct-declarator-list.
5345 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5347 // Check for Microsoft C extension: anonymous struct/union member.
5348 // Handle 2 kinds of anonymous struct/union:
5349 // struct STRUCT;
5350 // union UNION;
5351 // and
5352 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5353 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5354 if ((Tag && Tag->getDeclName()) ||
5356 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5357 : DS.getRepAsType().get()->getAsRecordDecl();
5358 if (Record && getLangOpts().MSAnonymousStructs) {
5359 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5360 << Record->isUnion() << DS.getSourceRange();
5362 }
5363
5364 DeclaresAnything = false;
5365 }
5366 }
5367
5368 // Skip all the checks below if we have a type error.
5370 (TagD && TagD->isInvalidDecl()))
5371 return TagD;
5372
5373 if (getLangOpts().CPlusPlus &&
5375 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5376 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5377 !Enum->isInvalidDecl())
5378 DeclaresAnything = false;
5379
5380 if (!DS.isMissingDeclaratorOk()) {
5381 // Customize diagnostic for a typedef missing a name.
5383 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5384 << DS.getSourceRange();
5385 else
5386 DeclaresAnything = false;
5387 }
5388
5389 if (DS.isModulePrivateSpecified() &&
5390 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5391 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5392 << Tag->getTagKind()
5394
5396
5397 // C 6.7/2:
5398 // A declaration [...] shall declare at least a declarator [...], a tag,
5399 // or the members of an enumeration.
5400 // C++ [dcl.dcl]p3:
5401 // [If there are no declarators], and except for the declaration of an
5402 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5403 // names into the program, or shall redeclare a name introduced by a
5404 // previous declaration.
5405 if (!DeclaresAnything) {
5406 // In C, we allow this as a (popular) extension / bug. Don't bother
5407 // producing further diagnostics for redundant qualifiers after this.
5408 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5409 ? diag::err_no_declarators
5410 : diag::ext_no_declarators)
5411 << DS.getSourceRange();
5412 return TagD;
5413 }
5414
5415 // C++ [dcl.stc]p1:
5416 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5417 // init-declarator-list of the declaration shall not be empty.
5418 // C++ [dcl.fct.spec]p1:
5419 // If a cv-qualifier appears in a decl-specifier-seq, the
5420 // init-declarator-list of the declaration shall not be empty.
5421 //
5422 // Spurious qualifiers here appear to be valid in C.
5423 unsigned DiagID = diag::warn_standalone_specifier;
5424 if (getLangOpts().CPlusPlus)
5425 DiagID = diag::ext_standalone_specifier;
5426
5427 // Note that a linkage-specification sets a storage class, but
5428 // 'extern "C" struct foo;' is actually valid and not theoretically
5429 // useless.
5430 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5431 if (SCS == DeclSpec::SCS_mutable)
5432 // Since mutable is not a viable storage class specifier in C, there is
5433 // no reason to treat it as an extension. Instead, diagnose as an error.
5434 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5435 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5436 Diag(DS.getStorageClassSpecLoc(), DiagID)
5438 }
5439
5443 if (DS.getTypeQualifiers()) {
5445 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5447 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5448 // Restrict is covered above.
5450 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5452 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5453 }
5454
5455 // Warn about ignored type attributes, for example:
5456 // __attribute__((aligned)) struct A;
5457 // Attributes should be placed after tag to apply to type declaration.
5458 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5459 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5460 if (TypeSpecType == DeclSpec::TST_class ||
5461 TypeSpecType == DeclSpec::TST_struct ||
5462 TypeSpecType == DeclSpec::TST_interface ||
5463 TypeSpecType == DeclSpec::TST_union ||
5464 TypeSpecType == DeclSpec::TST_enum) {
5465
5466 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5467 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5468 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5469 DiagnosticId = diag::warn_attribute_ignored;
5470 else if (AL.isRegularKeywordAttribute())
5471 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5472 else
5473 DiagnosticId = diag::warn_declspec_attribute_ignored;
5474 Diag(AL.getLoc(), DiagnosticId)
5475 << AL << GetDiagnosticTypeSpecifierID(DS);
5476 };
5477
5478 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5479 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5480 }
5481 }
5482
5483 return TagD;
5484}
5485
5486/// We are trying to inject an anonymous member into the given scope;
5487/// check if there's an existing declaration that can't be overloaded.
5488///
5489/// \return true if this is a forbidden redeclaration
5490static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5491 DeclContext *Owner,
5492 DeclarationName Name,
5493 SourceLocation NameLoc, bool IsUnion,
5494 StorageClass SC) {
5495 LookupResult R(SemaRef, Name, NameLoc,
5499 if (!SemaRef.LookupName(R, S)) return false;
5500
5501 // Pick a representative declaration.
5502 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5503 assert(PrevDecl && "Expected a non-null Decl");
5504
5505 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5506 return false;
5507
5508 if (SC == StorageClass::SC_None &&
5509 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5510 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5511 if (!Owner->isRecord())
5512 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5513 return false;
5514 }
5515
5516 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5517 << IsUnion << Name;
5518 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5519
5520 return true;
5521}
5522
5524 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5526}
5527
5529 if (!getLangOpts().CPlusPlus)
5530 return;
5531
5532 // This function can be parsed before we have validated the
5533 // structure as an anonymous struct
5534 if (Record->isAnonymousStructOrUnion())
5535 return;
5536
5537 const NamedDecl *First = 0;
5538 for (const Decl *D : Record->decls()) {
5539 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5540 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5541 continue;
5542 if (!First)
5543 First = ND;
5544 else
5546 }
5547}
5548
5549/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5550/// anonymous struct or union AnonRecord into the owning context Owner
5551/// and scope S. This routine will be invoked just after we realize
5552/// that an unnamed union or struct is actually an anonymous union or
5553/// struct, e.g.,
5554///
5555/// @code
5556/// union {
5557/// int i;
5558/// float f;
5559/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5560/// // f into the surrounding scope.x
5561/// @endcode
5562///
5563/// This routine is recursive, injecting the names of nested anonymous
5564/// structs/unions into the owning context and scope as well.
5565static bool
5567 RecordDecl *AnonRecord, AccessSpecifier AS,
5568 StorageClass SC,
5569 SmallVectorImpl<NamedDecl *> &Chaining) {
5570 bool Invalid = false;
5571
5572 // Look every FieldDecl and IndirectFieldDecl with a name.
5573 for (auto *D : AnonRecord->decls()) {
5574 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5575 cast<NamedDecl>(D)->getDeclName()) {
5576 ValueDecl *VD = cast<ValueDecl>(D);
5577 // C++ [class.union]p2:
5578 // The names of the members of an anonymous union shall be
5579 // distinct from the names of any other entity in the
5580 // scope in which the anonymous union is declared.
5581
5582 bool FieldInvalid = CheckAnonMemberRedeclaration(
5583 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5584 AnonRecord->isUnion(), SC);
5585 if (FieldInvalid)
5586 Invalid = true;
5587
5588 // Inject the IndirectFieldDecl even if invalid, because later
5589 // diagnostics may depend on it being present, see findDefaultInitializer.
5590
5591 // C++ [class.union]p2:
5592 // For the purpose of name lookup, after the anonymous union
5593 // definition, the members of the anonymous union are
5594 // considered to have been defined in the scope in which the
5595 // anonymous union is declared.
5596 unsigned OldChainingSize = Chaining.size();
5597 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5598 Chaining.append(IF->chain_begin(), IF->chain_end());
5599 else
5600 Chaining.push_back(VD);
5601
5602 assert(Chaining.size() >= 2);
5603 NamedDecl **NamedChain =
5604 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5605 for (unsigned i = 0; i < Chaining.size(); i++)
5606 NamedChain[i] = Chaining[i];
5607
5609 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5610 VD->getType(), {NamedChain, Chaining.size()});
5611
5612 for (const auto *Attr : VD->attrs())
5613 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5614
5615 IndirectField->setAccess(AS);
5616 IndirectField->setImplicit();
5617 IndirectField->setInvalidDecl(FieldInvalid);
5618 SemaRef.PushOnScopeChains(IndirectField, S);
5619
5620 // That includes picking up the appropriate access specifier.
5621 if (AS != AS_none)
5622 IndirectField->setAccess(AS);
5623
5624 Chaining.resize(OldChainingSize);
5625 }
5626 }
5627
5628 return Invalid;
5629}
5630
5631/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5632/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5633/// illegal input values are mapped to SC_None.
5634static StorageClass
5636 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5637 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5638 "Parser allowed 'typedef' as storage class VarDecl.");
5639 switch (StorageClassSpec) {
5642 if (DS.isExternInLinkageSpec())
5643 return SC_None;
5644 return SC_Extern;
5645 case DeclSpec::SCS_static: return SC_Static;
5646 case DeclSpec::SCS_auto: return SC_Auto;
5649 // Illegal SCSs map to None: error reporting is up to the caller.
5650 case DeclSpec::SCS_mutable: // Fall through.
5651 case DeclSpec::SCS_typedef: return SC_None;
5652 }
5653 llvm_unreachable("unknown storage class specifier");
5654}
5655
5657 assert(Record->hasInClassInitializer());
5658
5659 for (const auto *I : Record->decls()) {
5660 const auto *FD = dyn_cast<FieldDecl>(I);
5661 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5662 FD = IFD->getAnonField();
5663 if (FD && FD->hasInClassInitializer())
5664 return FD->getLocation();
5665 }
5666
5667 llvm_unreachable("couldn't find in-class initializer");
5668}
5669
5671 SourceLocation DefaultInitLoc) {
5672 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5673 return;
5674
5675 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5676 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5677}
5678
5680 CXXRecordDecl *AnonUnion) {
5681 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5682 return;
5683
5685}
5686
5688 AccessSpecifier AS,
5690 const PrintingPolicy &Policy) {
5691 DeclContext *Owner = Record->getDeclContext();
5692
5693 // Diagnose whether this anonymous struct/union is an extension.
5694 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5695 Diag(Record->getLocation(), diag::ext_anonymous_union);
5696 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5697 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5698 else if (!Record->isUnion() && !getLangOpts().C11)
5699 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5700
5701 // C and C++ require different kinds of checks for anonymous
5702 // structs/unions.
5703 bool Invalid = false;
5704 if (getLangOpts().CPlusPlus) {
5705 const char *PrevSpec = nullptr;
5706 if (Record->isUnion()) {
5707 // C++ [class.union]p6:
5708 // C++17 [class.union.anon]p2:
5709 // Anonymous unions declared in a named namespace or in the
5710 // global namespace shall be declared static.
5711 unsigned DiagID;
5712 DeclContext *OwnerScope = Owner->getRedeclContext();
5714 (OwnerScope->isTranslationUnit() ||
5715 (OwnerScope->isNamespace() &&
5716 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5717 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5718 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5719
5720 // Recover by adding 'static'.
5722 PrevSpec, DiagID, Policy);
5723 }
5724 // C++ [class.union]p6:
5725 // A storage class is not allowed in a declaration of an
5726 // anonymous union in a class scope.
5728 isa<RecordDecl>(Owner)) {
5730 diag::err_anonymous_union_with_storage_spec)
5732
5733 // Recover by removing the storage specifier.
5736 PrevSpec, DiagID, Context.getPrintingPolicy());
5737 }
5738 }
5739
5740 // Ignore const/volatile/restrict qualifiers.
5741 if (DS.getTypeQualifiers()) {
5743 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5744 << Record->isUnion() << "const"
5748 diag::ext_anonymous_struct_union_qualified)
5749 << Record->isUnion() << "volatile"
5753 diag::ext_anonymous_struct_union_qualified)
5754 << Record->isUnion() << "restrict"
5758 diag::ext_anonymous_struct_union_qualified)
5759 << Record->isUnion() << "_Atomic"
5763 diag::ext_anonymous_struct_union_qualified)
5764 << Record->isUnion() << "__unaligned"
5766
5768 }
5769
5770 // C++ [class.union]p2:
5771 // The member-specification of an anonymous union shall only
5772 // define non-static data members. [Note: nested types and
5773 // functions cannot be declared within an anonymous union. ]
5774 for (auto *Mem : Record->decls()) {
5775 // Ignore invalid declarations; we already diagnosed them.
5776 if (Mem->isInvalidDecl())
5777 continue;
5778
5779 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5780 // C++ [class.union]p3:
5781 // An anonymous union shall not have private or protected
5782 // members (clause 11).
5783 assert(FD->getAccess() != AS_none);
5784 if (FD->getAccess() != AS_public) {
5785 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5786 << Record->isUnion() << (FD->getAccess() == AS_protected);
5787 Invalid = true;
5788 }
5789
5790 // C++ [class.union]p1
5791 // An object of a class with a non-trivial constructor, a non-trivial
5792 // copy constructor, a non-trivial destructor, or a non-trivial copy
5793 // assignment operator cannot be a member of a union, nor can an
5794 // array of such objects.
5795 if (CheckNontrivialField(FD))
5796 Invalid = true;
5797 } else if (Mem->isImplicit()) {
5798 // Any implicit members are fine.
5799 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5800 // This is a type that showed up in an
5801 // elaborated-type-specifier inside the anonymous struct or
5802 // union, but which actually declares a type outside of the
5803 // anonymous struct or union. It's okay.
5804 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5805 if (!MemRecord->isAnonymousStructOrUnion() &&
5806 MemRecord->getDeclName()) {
5807 // Visual C++ allows type definition in anonymous struct or union.
5808 if (getLangOpts().MicrosoftExt)
5809 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5810 << Record->isUnion();
5811 else {
5812 // This is a nested type declaration.
5813 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5814 << Record->isUnion();
5815 Invalid = true;
5816 }
5817 } else {
5818 // This is an anonymous type definition within another anonymous type.
5819 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5820 // not part of standard C++.
5821 Diag(MemRecord->getLocation(),
5822 diag::ext_anonymous_record_with_anonymous_type)
5823 << Record->isUnion();
5824 }
5825 } else if (isa<AccessSpecDecl>(Mem)) {
5826 // Any access specifier is fine.
5827 } else if (isa<StaticAssertDecl>(Mem)) {
5828 // In C++1z, static_assert declarations are also fine.
5829 } else {
5830 // We have something that isn't a non-static data
5831 // member. Complain about it.
5832 unsigned DK = diag::err_anonymous_record_bad_member;
5833 if (isa<TypeDecl>(Mem))
5834 DK = diag::err_anonymous_record_with_type;
5835 else if (isa<FunctionDecl>(Mem))
5836 DK = diag::err_anonymous_record_with_function;
5837 else if (isa<VarDecl>(Mem))
5838 DK = diag::err_anonymous_record_with_static;
5839
5840 // Visual C++ allows type definition in anonymous struct or union.
5841 if (getLangOpts().MicrosoftExt &&
5842 DK == diag::err_anonymous_record_with_type)
5843 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5844 << Record->isUnion();
5845 else {
5846 Diag(Mem->getLocation(), DK) << Record->isUnion();
5847 Invalid = true;
5848 }
5849 }
5850 }
5851
5852 // C++11 [class.union]p8 (DR1460):
5853 // At most one variant member of a union may have a
5854 // brace-or-equal-initializer.
5855 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5856 Owner->isRecord())
5859 }
5860
5861 if (!Record->isUnion() && !Owner->isRecord()) {
5862 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5863 << getLangOpts().CPlusPlus;
5864 Invalid = true;
5865 }
5866
5867 // C++ [dcl.dcl]p3:
5868 // [If there are no declarators], and except for the declaration of an
5869 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5870 // names into the program
5871 // C++ [class.mem]p2:
5872 // each such member-declaration shall either declare at least one member
5873 // name of the class or declare at least one unnamed bit-field
5874 //
5875 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5876 if (getLangOpts().CPlusPlus && Record->field_empty())
5877 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5878
5879 // Mock up a declarator.
5883 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5884
5885 // Create a declaration for this anonymous struct/union.
5886 NamedDecl *Anon = nullptr;
5887 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5888 Anon = FieldDecl::Create(
5889 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5890 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5891 /*BitWidth=*/nullptr, /*Mutable=*/false,
5892 /*InitStyle=*/ICIS_NoInit);
5893 Anon->setAccess(AS);
5894 ProcessDeclAttributes(S, Anon, Dc);
5895
5896 if (getLangOpts().CPlusPlus)
5897 FieldCollector->Add(cast<FieldDecl>(Anon));
5898 } else {
5899 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5900 if (SCSpec == DeclSpec::SCS_mutable) {
5901 // mutable can only appear on non-static class members, so it's always
5902 // an error here
5903 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5904 Invalid = true;
5905 SC = SC_None;
5906 }
5907
5908 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5909 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5910 Context.getCanonicalTagType(Record), TInfo, SC);
5911 if (Invalid)
5912 Anon->setInvalidDecl();
5913
5914 ProcessDeclAttributes(S, Anon, Dc);
5915
5916 // Default-initialize the implicit variable. This initialization will be
5917 // trivial in almost all cases, except if a union member has an in-class
5918 // initializer:
5919 // union { int n = 0; };
5921 }
5922 Anon->setImplicit();
5923
5924 // Mark this as an anonymous struct/union type.
5925 Record->setAnonymousStructOrUnion(true);
5926
5927 // Add the anonymous struct/union object to the current
5928 // context. We'll be referencing this object when we refer to one of
5929 // its members.
5930 Owner->addDecl(Anon);
5931
5932 // Inject the members of the anonymous struct/union into the owning
5933 // context and into the identifier resolver chain for name lookup
5934 // purposes.
5936 Chain.push_back(Anon);
5937
5938 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
5939 Chain))
5940 Invalid = true;
5941
5942 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5943 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5945 Decl *ManglingContextDecl;
5946 std::tie(MCtx, ManglingContextDecl) =
5947 getCurrentMangleNumberContext(NewVD->getDeclContext());
5948 if (MCtx) {
5949 Context.setManglingNumber(
5950 NewVD, MCtx->getManglingNumber(
5951 NewVD, getMSManglingNumber(getLangOpts(), S)));
5952 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5953 }
5954 }
5955 }
5956
5957 if (Invalid)
5958 Anon->setInvalidDecl();
5959
5960 return Anon;
5961}
5962
5964 RecordDecl *Record) {
5965 assert(Record && "expected a record!");
5966
5967 // Mock up a declarator.
5970 assert(TInfo && "couldn't build declarator info for anonymous struct");
5971
5972 auto *ParentDecl = cast<RecordDecl>(CurContext);
5973 CanQualType RecTy = Context.getCanonicalTagType(Record);
5974
5975 // Create a declaration for this anonymous struct.
5976 NamedDecl *Anon =
5977 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5978 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5979 /*BitWidth=*/nullptr, /*Mutable=*/false,
5980 /*InitStyle=*/ICIS_NoInit);
5981 Anon->setImplicit();
5982
5983 // Add the anonymous struct object to the current context.
5984 CurContext->addDecl(Anon);
5985
5986 // Inject the members of the anonymous struct into the current
5987 // context and into the identifier resolver chain for name lookup
5988 // purposes.
5990 Chain.push_back(Anon);
5991
5992 RecordDecl *RecordDef = Record->getDefinition();
5993 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5994 diag::err_field_incomplete_or_sizeless) ||
5996 *this, S, CurContext, RecordDef, AS_none,
5998 Anon->setInvalidDecl();
5999 ParentDecl->setInvalidDecl();
6000 }
6001
6002 return Anon;
6003}
6004
6008
6011 DeclarationNameInfo NameInfo;
6012 NameInfo.setLoc(Name.StartLocation);
6013
6014 switch (Name.getKind()) {
6015
6018 NameInfo.setName(Name.Identifier);
6019 return NameInfo;
6020
6022 // C++ [temp.deduct.guide]p3:
6023 // The simple-template-id shall name a class template specialization.
6024 // The template-name shall be the same identifier as the template-name
6025 // of the simple-template-id.
6026 // These together intend to imply that the template-name shall name a
6027 // class template.
6028 // FIXME: template<typename T> struct X {};
6029 // template<typename T> using Y = X<T>;
6030 // Y(int) -> Y<int>;
6031 // satisfies these rules but does not name a class template.
6032 TemplateName TN = Name.TemplateName.get().get();
6033 auto *Template = TN.getAsTemplateDecl();
6035 Diag(Name.StartLocation,
6036 diag::err_deduction_guide_name_not_class_template)
6037 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6038 if (Template)
6040 return DeclarationNameInfo();
6041 }
6042
6043 NameInfo.setName(
6044 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6045 return NameInfo;
6046 }
6047
6049 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6053 return NameInfo;
6054
6056 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6057 Name.Identifier));
6059 return NameInfo;
6060
6062 TypeSourceInfo *TInfo;
6064 if (Ty.isNull())
6065 return DeclarationNameInfo();
6066 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6067 Context.getCanonicalType(Ty)));
6068 NameInfo.setNamedTypeInfo(TInfo);
6069 return NameInfo;
6070 }
6071
6073 TypeSourceInfo *TInfo;
6074 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6075 if (Ty.isNull())
6076 return DeclarationNameInfo();
6077 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6078 Context.getCanonicalType(Ty)));
6079 NameInfo.setNamedTypeInfo(TInfo);
6080 return NameInfo;
6081 }
6082
6084 // In well-formed code, we can only have a constructor
6085 // template-id that refers to the current context, so go there
6086 // to find the actual type being constructed.
6087 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6088 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6089 return DeclarationNameInfo();
6090
6091 // Determine the type of the class being constructed.
6092 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6093
6094 // FIXME: Check two things: that the template-id names the same type as
6095 // CurClassType, and that the template-id does not occur when the name
6096 // was qualified.
6097
6098 NameInfo.setName(
6099 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6100 // FIXME: should we retrieve TypeSourceInfo?
6101 NameInfo.setNamedTypeInfo(nullptr);
6102 return NameInfo;
6103 }
6104
6106 TypeSourceInfo *TInfo;
6107 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6108 if (Ty.isNull())
6109 return DeclarationNameInfo();
6110 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6111 Context.getCanonicalType(Ty)));
6112 NameInfo.setNamedTypeInfo(TInfo);
6113 return NameInfo;
6114 }
6115
6117 TemplateName TName = Name.TemplateId->Template.get();
6118 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6119 return Context.getNameForTemplate(TName, TNameLoc);
6120 }
6121
6122 } // switch (Name.getKind())
6123
6124 llvm_unreachable("Unknown name kind");
6125}
6126
6128 do {
6129 if (Ty->isPointerOrReferenceType())
6130 Ty = Ty->getPointeeType();
6131 else if (Ty->isArrayType())
6133 else
6134 return Ty.withoutLocalFastQualifiers();
6135 } while (true);
6136}
6137
6138/// hasSimilarParameters - Determine whether the C++ functions Declaration
6139/// and Definition have "nearly" matching parameters. This heuristic is
6140/// used to improve diagnostics in the case where an out-of-line function
6141/// definition doesn't match any declaration within the class or namespace.
6142/// Also sets Params to the list of indices to the parameters that differ
6143/// between the declaration and the definition. If hasSimilarParameters
6144/// returns true and Params is empty, then all of the parameters match.
6148 SmallVectorImpl<unsigned> &Params) {
6149 Params.clear();
6150 if (Declaration->param_size() != Definition->param_size())
6151 return false;
6152 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6153 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6154 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6155
6156 // The parameter types are identical
6157 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6158 continue;
6159
6160 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6161 QualType DefParamBaseTy = getCoreType(DefParamTy);
6162 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6163 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6164
6165 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6166 (DeclTyName && DeclTyName == DefTyName))
6167 Params.push_back(Idx);
6168 else // The two parameters aren't even close
6169 return false;
6170 }
6171
6172 return true;
6173}
6174
6175/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6176/// declarator needs to be rebuilt in the current instantiation.
6177/// Any bits of declarator which appear before the name are valid for
6178/// consideration here. That's specifically the type in the decl spec
6179/// and the base type in any member-pointer chunks.
6181 DeclarationName Name) {
6182 // The types we specifically need to rebuild are:
6183 // - typenames, typeofs, and decltypes
6184 // - types which will become injected class names
6185 // Of course, we also need to rebuild any type referencing such a
6186 // type. It's safest to just say "dependent", but we call out a
6187 // few cases here.
6188
6189 DeclSpec &DS = D.getMutableDeclSpec();
6190 switch (DS.getTypeSpecType()) {
6194#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6195#include "clang/Basic/TransformTypeTraits.def"
6196 case DeclSpec::TST_atomic: {
6197 // Grab the type from the parser.
6198 TypeSourceInfo *TSI = nullptr;
6199 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6200 if (T.isNull() || !T->isInstantiationDependentType()) break;
6201
6202 // Make sure there's a type source info. This isn't really much
6203 // of a waste; most dependent types should have type source info
6204 // attached already.
6205 if (!TSI)
6207
6208 // Rebuild the type in the current instantiation.
6210 if (!TSI) return true;
6211
6212 // Store the new type back in the decl spec.
6213 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6214 DS.UpdateTypeRep(LocType);
6215 break;
6216 }
6217
6221 Expr *E = DS.getRepAsExpr();
6223 if (Result.isInvalid()) return true;
6224 DS.UpdateExprRep(Result.get());
6225 break;
6226 }
6227
6228 default:
6229 // Nothing to do for these decl specs.
6230 break;
6231 }
6232
6233 // It doesn't matter what order we do this in.
6234 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6235 DeclaratorChunk &Chunk = D.getTypeObject(I);
6236
6237 // The only type information in the declarator which can come
6238 // before the declaration name is the base type of a member
6239 // pointer.
6241 continue;
6242
6243 // Rebuild the scope specifier in-place.
6244 CXXScopeSpec &SS = Chunk.Mem.Scope();
6246 return true;
6247 }
6248
6249 return false;
6250}
6251
6252/// Returns true if the declaration is declared in a system header or from a
6253/// system macro.
6254static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6255 return SM.isInSystemHeader(D->getLocation()) ||
6256 SM.isInSystemMacro(D->getLocation());
6257}
6258
6260 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6261 // of system decl.
6262 if (D->getPreviousDecl() || D->isImplicit())
6263 return;
6266 !isFromSystemHeader(Context.getSourceManager(), D)) {
6267 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6268 << D << static_cast<int>(Status);
6269 }
6270}
6271
6274
6275 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6276 // declaration only if the `bind_to_declaration` extension is set.
6278 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6279 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6280 llvm::omp::TraitProperty::
6281 implementation_extension_bind_to_declaration))
6283 S, D, MultiTemplateParamsArg(), Bases);
6284
6286
6287 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6288 Dcl && Dcl->getDeclContext()->isFileContext())
6290
6291 if (!Bases.empty())
6293 Bases);
6294
6295 return Dcl;
6296}
6297
6299 DeclarationNameInfo NameInfo) {
6300 DeclarationName Name = NameInfo.getName();
6301
6302 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6303 while (Record && Record->isAnonymousStructOrUnion())
6304 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6305 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6306 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6307 return true;
6308 }
6309
6310 return false;
6311}
6312
6314 DeclarationName Name,
6315 SourceLocation Loc,
6316 TemplateIdAnnotation *TemplateId,
6317 bool IsMemberSpecialization) {
6318 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6319 "without nested-name-specifier");
6320 DeclContext *Cur = CurContext;
6321 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6322 Cur = Cur->getParent();
6323
6324 // If the user provided a superfluous scope specifier that refers back to the
6325 // class in which the entity is already declared, diagnose and ignore it.
6326 //
6327 // class X {
6328 // void X::f();
6329 // };
6330 //
6331 // Note, it was once ill-formed to give redundant qualification in all
6332 // contexts, but that rule was removed by DR482.
6333 if (Cur->Equals(DC)) {
6334 if (Cur->isRecord()) {
6335 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6336 : diag::err_member_extra_qualification)
6337 << Name << FixItHint::CreateRemoval(SS.getRange());
6338 SS.clear();
6339 } else {
6340 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6341 }
6342 return false;
6343 }
6344
6345 // Check whether the qualifying scope encloses the scope of the original
6346 // declaration. For a template-id, we perform the checks in
6347 // CheckTemplateSpecializationScope.
6348 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6349 if (Cur->isRecord())
6350 Diag(Loc, diag::err_member_qualification)
6351 << Name << SS.getRange();
6352 else if (isa<TranslationUnitDecl>(DC))
6353 Diag(Loc, diag::err_invalid_declarator_global_scope)
6354 << Name << SS.getRange();
6355 else if (isa<FunctionDecl>(Cur))
6356 Diag(Loc, diag::err_invalid_declarator_in_function)
6357 << Name << SS.getRange();
6358 else if (isa<BlockDecl>(Cur))
6359 Diag(Loc, diag::err_invalid_declarator_in_block)
6360 << Name << SS.getRange();
6361 else if (isa<ExportDecl>(Cur)) {
6362 if (!isa<NamespaceDecl>(DC))
6363 Diag(Loc, diag::err_export_non_namespace_scope_name)
6364 << Name << SS.getRange();
6365 else
6366 // The cases that DC is not NamespaceDecl should be handled in
6367 // CheckRedeclarationExported.
6368 return false;
6369 } else
6370 Diag(Loc, diag::err_invalid_declarator_scope)
6371 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6372
6373 return true;
6374 }
6375
6376 if (Cur->isRecord()) {
6377 // Cannot qualify members within a class.
6378 Diag(Loc, diag::err_member_qualification)
6379 << Name << SS.getRange();
6380 SS.clear();
6381
6382 // C++ constructors and destructors with incorrect scopes can break
6383 // our AST invariants by having the wrong underlying types. If
6384 // that's the case, then drop this declaration entirely.
6387 !Context.hasSameType(
6388 Name.getCXXNameType(),
6389 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6390 return true;
6391
6392 return false;
6393 }
6394
6395 // C++23 [temp.names]p5:
6396 // The keyword template shall not appear immediately after a declarative
6397 // nested-name-specifier.
6398 //
6399 // First check the template-id (if any), and then check each component of the
6400 // nested-name-specifier in reverse order.
6401 //
6402 // FIXME: nested-name-specifiers in friend declarations are declarative,
6403 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6404 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6405 Diag(Loc, diag::ext_template_after_declarative_nns)
6407
6409 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6410 TL = std::exchange(NextTL, TypeLoc())) {
6411 SourceLocation TemplateKeywordLoc;
6412 switch (TL.getTypeLocClass()) {
6413 case TypeLoc::TemplateSpecialization: {
6414 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6415 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6416 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6417 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6418 << TST.getLocalSourceRange();
6419 break;
6420 }
6421 case TypeLoc::Decltype:
6422 case TypeLoc::PackIndexing: {
6423 const Type *T = TL.getTypePtr();
6424 // C++23 [expr.prim.id.qual]p2:
6425 // [...] A declarative nested-name-specifier shall not have a
6426 // computed-type-specifier.
6427 //
6428 // CWG2858 changed this from 'decltype-specifier' to
6429 // 'computed-type-specifier'.
6430 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6431 << T->isDecltypeType() << TL.getSourceRange();
6432 break;
6433 }
6434 case TypeLoc::DependentName:
6435 NextTL =
6436 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6437 break;
6438 default:
6439 break;
6440 }
6441 if (TemplateKeywordLoc.isValid())
6442 Diag(Loc, diag::ext_template_after_declarative_nns)
6443 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6444 }
6445
6446 return false;
6447}
6448
6450 MultiTemplateParamsArg TemplateParamLists) {
6451 // TODO: consider using NameInfo for diagnostic.
6453 DeclarationName Name = NameInfo.getName();
6454
6455 // All of these full declarators require an identifier. If it doesn't have
6456 // one, the ParsedFreeStandingDeclSpec action should be used.
6457 if (D.isDecompositionDeclarator()) {
6458 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6459 } else if (!Name) {
6460 if (!D.isInvalidType()) // Reject this if we think it is valid.
6461 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6463 return nullptr;
6465 return nullptr;
6466
6467 DeclContext *DC = CurContext;
6468 if (D.getCXXScopeSpec().isInvalid())
6469 D.setInvalidType();
6470 else if (D.getCXXScopeSpec().isSet()) {
6473 return nullptr;
6474
6475 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6476 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6477 if (!DC || isa<EnumDecl>(DC)) {
6478 // If we could not compute the declaration context, it's because the
6479 // declaration context is dependent but does not refer to a class,
6480 // class template, or class template partial specialization. Complain
6481 // and return early, to avoid the coming semantic disaster.
6483 diag::err_template_qualified_declarator_no_match)
6485 << D.getCXXScopeSpec().getRange();
6486 return nullptr;
6487 }
6488 bool IsDependentContext = DC->isDependentContext();
6489
6490 if (!IsDependentContext &&
6492 return nullptr;
6493
6494 // If a class is incomplete, do not parse entities inside it.
6497 diag::err_member_def_undefined_record)
6498 << Name << DC << D.getCXXScopeSpec().getRange();
6499 return nullptr;
6500 }
6501 if (!D.getDeclSpec().isFriendSpecified()) {
6502 TemplateIdAnnotation *TemplateId =
6504 ? D.getName().TemplateId
6505 : nullptr;
6507 D.getIdentifierLoc(), TemplateId,
6508 /*IsMemberSpecialization=*/false)) {
6509 if (DC->isRecord())
6510 return nullptr;
6511
6512 D.setInvalidType();
6513 }
6514 }
6515
6516 // Check whether we need to rebuild the type of the given
6517 // declaration in the current instantiation.
6518 if (EnteringContext && IsDependentContext &&
6519 TemplateParamLists.size() != 0) {
6520 ContextRAII SavedContext(*this, DC);
6521 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6522 D.setInvalidType();
6523 }
6524 }
6525
6527 QualType R = TInfo->getType();
6528
6531 D.setInvalidType();
6532
6533 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6535
6536 // See if this is a redefinition of a variable in the same scope.
6537 if (!D.getCXXScopeSpec().isSet()) {
6538 bool IsLinkageLookup = false;
6539 bool CreateBuiltins = false;
6540
6541 // If the declaration we're planning to build will be a function
6542 // or object with linkage, then look for another declaration with
6543 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6544 //
6545 // If the declaration we're planning to build will be declared with
6546 // external linkage in the translation unit, create any builtin with
6547 // the same name.
6549 /* Do nothing*/;
6550 else if (CurContext->isFunctionOrMethod() &&
6552 R->isFunctionType())) {
6553 IsLinkageLookup = true;
6554 CreateBuiltins =
6555 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6556 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6558 CreateBuiltins = true;
6559
6560 if (IsLinkageLookup) {
6562 Previous.setRedeclarationKind(
6564 }
6565
6566 LookupName(Previous, S, CreateBuiltins);
6567 } else { // Something like "int foo::x;"
6569
6570 // C++ [dcl.meaning]p1:
6571 // When the declarator-id is qualified, the declaration shall refer to a
6572 // previously declared member of the class or namespace to which the
6573 // qualifier refers (or, in the case of a namespace, of an element of the
6574 // inline namespace set of that namespace (7.3.1)) or to a specialization
6575 // thereof; [...]
6576 //
6577 // Note that we already checked the context above, and that we do not have
6578 // enough information to make sure that Previous contains the declaration
6579 // we want to match. For example, given:
6580 //
6581 // class X {
6582 // void f();
6583 // void f(float);
6584 // };
6585 //
6586 // void X::f(int) { } // ill-formed
6587 //
6588 // In this case, Previous will point to the overload set
6589 // containing the two f's declared in X, but neither of them
6590 // matches.
6591
6593 }
6594
6595 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6596 TPD && TPD->isTemplateParameter()) {
6597 // Older versions of clang allowed the names of function/variable templates
6598 // to shadow the names of their template parameters. For the compatibility
6599 // purposes we detect such cases and issue a default-to-error warning that
6600 // can be disabled with -Wno-strict-primary-template-shadow.
6601 if (!D.isInvalidType()) {
6602 bool AllowForCompatibility = false;
6603 if (Scope *DeclParent = S->getDeclParent();
6604 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6605 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6606 TemplateParamParent->isDeclScope(TPD);
6607 }
6609 AllowForCompatibility);
6610 }
6611
6612 // Just pretend that we didn't see the previous declaration.
6613 Previous.clear();
6614 }
6615
6616 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6617 // Forget that the previous declaration is the injected-class-name.
6618 Previous.clear();
6619
6620 // In C++, the previous declaration we find might be a tag type
6621 // (class or enum). In this case, the new declaration will hide the
6622 // tag type. Note that this applies to functions, function templates, and
6623 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6624 if (Previous.isSingleTagDecl() &&
6626 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6627 Previous.clear();
6628
6629 // Check that there are no default arguments other than in the parameters
6630 // of a function declaration (C++ only).
6631 if (getLangOpts().CPlusPlus)
6633
6634 /// Get the innermost enclosing declaration scope.
6635 S = S->getDeclParent();
6636
6637 NamedDecl *New;
6638
6639 bool AddToScope = true;
6641 if (TemplateParamLists.size()) {
6642 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6643 return nullptr;
6644 }
6645
6646 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6647 } else if (R->isFunctionType()) {
6648 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6649 TemplateParamLists,
6650 AddToScope);
6651 } else {
6652 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6653 AddToScope);
6654 }
6655
6656 if (!New)
6657 return nullptr;
6658
6660
6661 // If this has an identifier and is not a function template specialization,
6662 // add it to the scope stack.
6663 if (New->getDeclName() && AddToScope)
6665
6666 if (OpenMP().isInOpenMPDeclareTargetContext())
6668
6669 return New;
6670}
6671
6672/// Helper method to turn variable array types into constant array
6673/// types in certain situations which would otherwise be errors (for
6674/// GCC compatibility).
6676 ASTContext &Context,
6677 bool &SizeIsNegative,
6678 llvm::APSInt &Oversized) {
6679 // This method tries to turn a variable array into a constant
6680 // array even when the size isn't an ICE. This is necessary
6681 // for compatibility with code that depends on gcc's buggy
6682 // constant expression folding, like struct {char x[(int)(char*)2];}
6683 SizeIsNegative = false;
6684 Oversized = 0;
6685
6686 if (T->isDependentType())
6687 return QualType();
6688
6690 const Type *Ty = Qs.strip(T);
6691
6692 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6693 QualType Pointee = PTy->getPointeeType();
6694 QualType FixedType =
6695 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6696 Oversized);
6697 if (FixedType.isNull()) return FixedType;
6698 FixedType = Context.getPointerType(FixedType);
6699 return Qs.apply(Context, FixedType);
6700 }
6701 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6702 QualType Inner = PTy->getInnerType();
6703 QualType FixedType =
6704 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6705 Oversized);
6706 if (FixedType.isNull()) return FixedType;
6707 FixedType = Context.getParenType(FixedType);
6708 return Qs.apply(Context, FixedType);
6709 }
6710
6711 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6712 if (!VLATy)
6713 return QualType();
6714
6715 QualType ElemTy = VLATy->getElementType();
6716 if (ElemTy->isVariablyModifiedType()) {
6717 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6718 SizeIsNegative, Oversized);
6719 if (ElemTy.isNull())
6720 return QualType();
6721 }
6722
6723 Expr::EvalResult Result;
6724 if (!VLATy->getSizeExpr() ||
6725 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6726 return QualType();
6727
6728 llvm::APSInt Res = Result.Val.getInt();
6729
6730 // Check whether the array size is negative.
6731 if (Res.isSigned() && Res.isNegative()) {
6732 SizeIsNegative = true;
6733 return QualType();
6734 }
6735
6736 // Check whether the array is too large to be addressed.
6737 unsigned ActiveSizeBits =
6738 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6739 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6740 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6741 : Res.getActiveBits();
6742 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6743 Oversized = std::move(Res);
6744 return QualType();
6745 }
6746
6747 QualType FoldedArrayType = Context.getConstantArrayType(
6748 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6749 return Qs.apply(Context, FoldedArrayType);
6750}
6751
6752static void
6754 SrcTL = SrcTL.getUnqualifiedLoc();
6755 DstTL = DstTL.getUnqualifiedLoc();
6756 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6757 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6758 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6759 DstPTL.getPointeeLoc());
6760 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6761 return;
6762 }
6763 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6764 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6765 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6766 DstPTL.getInnerLoc());
6767 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6768 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6769 return;
6770 }
6771 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6772 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6773 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6774 TypeLoc DstElemTL = DstATL.getElementLoc();
6775 if (VariableArrayTypeLoc SrcElemATL =
6776 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6777 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6778 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6779 } else {
6780 DstElemTL.initializeFullCopy(SrcElemTL);
6781 }
6782 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6783 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6784 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6785}
6786
6787/// Helper method to turn variable array types into constant array
6788/// types in certain situations which would otherwise be errors (for
6789/// GCC compatibility).
6790static TypeSourceInfo*
6792 ASTContext &Context,
6793 bool &SizeIsNegative,
6794 llvm::APSInt &Oversized) {
6795 QualType FixedTy
6796 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6797 SizeIsNegative, Oversized);
6798 if (FixedTy.isNull())
6799 return nullptr;
6800 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6802 FixedTInfo->getTypeLoc());
6803 return FixedTInfo;
6804}
6805
6807 QualType &T, SourceLocation Loc,
6808 unsigned FailedFoldDiagID) {
6809 bool SizeIsNegative;
6810 llvm::APSInt Oversized;
6812 TInfo, Context, SizeIsNegative, Oversized);
6813 if (FixedTInfo) {
6814 Diag(Loc, diag::ext_vla_folded_to_constant);
6815 TInfo = FixedTInfo;
6816 T = FixedTInfo->getType();
6817 return true;
6818 }
6819
6820 if (SizeIsNegative)
6821 Diag(Loc, diag::err_typecheck_negative_array_size);
6822 else if (Oversized.getBoolValue())
6823 Diag(Loc, diag::err_array_too_large) << toString(
6824 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6825 /*UpperCase=*/false, /*InsertSeparators=*/true);
6826 else if (FailedFoldDiagID)
6827 Diag(Loc, FailedFoldDiagID);
6828 return false;
6829}
6830
6831void
6833 if (!getLangOpts().CPlusPlus &&
6835 // Don't need to track declarations in the TU in C.
6836 return;
6837
6838 // Note that we have a locally-scoped external with this name.
6839 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6840}
6841
6843 // FIXME: We can have multiple results via __attribute__((overloadable)).
6844 auto Result = Context.getExternCContextDecl()->lookup(Name);
6845 return Result.empty() ? nullptr : *Result.begin();
6846}
6847
6849 // FIXME: We should probably indicate the identifier in question to avoid
6850 // confusion for constructs like "virtual int a(), b;"
6851 if (DS.isVirtualSpecified())
6853 diag::err_virtual_non_function);
6854
6855 if (DS.hasExplicitSpecifier())
6857 diag::err_explicit_non_function);
6858
6859 if (DS.isNoreturnSpecified())
6861 diag::err_noreturn_non_function);
6862}
6863
6864NamedDecl*
6867 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6868 if (D.getCXXScopeSpec().isSet()) {
6869 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6870 << D.getCXXScopeSpec().getRange();
6871 D.setInvalidType();
6872 // Pretend we didn't see the scope specifier.
6873 DC = CurContext;
6874 Previous.clear();
6875 }
6876
6878
6881 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6882 ? diag::warn_ms_inline_non_function
6883 : diag::err_inline_non_function)
6884 << getLangOpts().CPlusPlus17;
6886 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6887 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6888
6892 diag::err_deduction_guide_invalid_specifier)
6893 << "typedef";
6894 else
6895 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6896 << D.getName().getSourceRange();
6897 return nullptr;
6898 }
6899
6900 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6901 if (!NewTD) return nullptr;
6902
6903 // Handle attributes prior to checking for duplicates in MergeVarDecl
6904 ProcessDeclAttributes(S, NewTD, D);
6905
6907
6908 bool Redeclaration = D.isRedeclaration();
6911 return ND;
6912}
6913
6914void
6916 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6917 // then it shall have block scope.
6918 // Note that variably modified types must be fixed before merging the decl so
6919 // that redeclarations will match.
6920 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6921 QualType T = TInfo->getType();
6922 if (T->isVariablyModifiedType()) {
6924
6925 if (S->getFnParent() == nullptr) {
6926 bool SizeIsNegative;
6927 llvm::APSInt Oversized;
6928 TypeSourceInfo *FixedTInfo =
6930 SizeIsNegative,
6931 Oversized);
6932 if (FixedTInfo) {
6933 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6934 NewTD->setTypeSourceInfo(FixedTInfo);
6935 } else {
6936 if (SizeIsNegative)
6937 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6938 else if (T->isVariableArrayType())
6939 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6940 else if (Oversized.getBoolValue())
6941 Diag(NewTD->getLocation(), diag::err_array_too_large)
6942 << toString(Oversized, 10);
6943 else
6944 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6945 NewTD->setInvalidDecl();
6946 }
6947 }
6948 }
6949}
6950
6951NamedDecl*
6954
6955 // Find the shadowed declaration before filtering for scope.
6956 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6957
6958 // Merge the decl with the existing one if appropriate. If the decl is
6959 // in an outer scope, it isn't the same thing.
6960 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6961 /*AllowInlineNamespace*/false);
6963 if (!Previous.empty()) {
6964 Redeclaration = true;
6965 MergeTypedefNameDecl(S, NewTD, Previous);
6966 } else {
6968 }
6969
6970 if (ShadowedDecl && !Redeclaration)
6971 CheckShadow(NewTD, ShadowedDecl, Previous);
6972
6973 // If this is the C FILE type, notify the AST context.
6974 if (IdentifierInfo *II = NewTD->getIdentifier())
6975 if (!NewTD->isInvalidDecl() &&
6977 switch (II->getNotableIdentifierID()) {
6978 case tok::NotableIdentifierKind::FILE:
6979 Context.setFILEDecl(NewTD);
6980 break;
6981 case tok::NotableIdentifierKind::jmp_buf:
6982 Context.setjmp_bufDecl(NewTD);
6983 break;
6984 case tok::NotableIdentifierKind::sigjmp_buf:
6985 Context.setsigjmp_bufDecl(NewTD);
6986 break;
6987 case tok::NotableIdentifierKind::ucontext_t:
6988 Context.setucontext_tDecl(NewTD);
6989 break;
6990 case tok::NotableIdentifierKind::float_t:
6991 case tok::NotableIdentifierKind::double_t:
6992 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
6993 break;
6994 default:
6995 break;
6996 }
6997 }
6998
6999 return NewTD;
7000}
7001
7002/// Determines whether the given declaration is an out-of-scope
7003/// previous declaration.
7004///
7005/// This routine should be invoked when name lookup has found a
7006/// previous declaration (PrevDecl) that is not in the scope where a
7007/// new declaration by the same name is being introduced. If the new
7008/// declaration occurs in a local scope, previous declarations with
7009/// linkage may still be considered previous declarations (C99
7010/// 6.2.2p4-5, C++ [basic.link]p6).
7011///
7012/// \param PrevDecl the previous declaration found by name
7013/// lookup
7014///
7015/// \param DC the context in which the new declaration is being
7016/// declared.
7017///
7018/// \returns true if PrevDecl is an out-of-scope previous declaration
7019/// for a new delcaration with the same name.
7020static bool
7022 ASTContext &Context) {
7023 if (!PrevDecl)
7024 return false;
7025
7026 if (!PrevDecl->hasLinkage())
7027 return false;
7028
7029 if (Context.getLangOpts().CPlusPlus) {
7030 // C++ [basic.link]p6:
7031 // If there is a visible declaration of an entity with linkage
7032 // having the same name and type, ignoring entities declared
7033 // outside the innermost enclosing namespace scope, the block
7034 // scope declaration declares that same entity and receives the
7035 // linkage of the previous declaration.
7036 DeclContext *OuterContext = DC->getRedeclContext();
7037 if (!OuterContext->isFunctionOrMethod())
7038 // This rule only applies to block-scope declarations.
7039 return false;
7040
7041 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7042 if (PrevOuterContext->isRecord())
7043 // We found a member function: ignore it.
7044 return false;
7045
7046 // Find the innermost enclosing namespace for the new and
7047 // previous declarations.
7048 OuterContext = OuterContext->getEnclosingNamespaceContext();
7049 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7050
7051 // The previous declaration is in a different namespace, so it
7052 // isn't the same function.
7053 if (!OuterContext->Equals(PrevOuterContext))
7054 return false;
7055 }
7056
7057 return true;
7058}
7059
7061 CXXScopeSpec &SS = D.getCXXScopeSpec();
7062 if (!SS.isSet()) return;
7064}
7065
7067 QualType Type = Var->getType();
7068 if (Type.hasAddressSpace())
7069 return;
7070 if (Type->isDependentType())
7071 return;
7072 if (Type->isSamplerT() || Type->isVoidType())
7073 return;
7075 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7076 // __opencl_c_program_scope_global_variables feature, the address space
7077 // for a variable at program scope or a static or extern variable inside
7078 // a function are inferred to be __global.
7079 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7080 Var->hasGlobalStorage())
7081 ImplAS = LangAS::opencl_global;
7082 // If the original type from a decayed type is an array type and that array
7083 // type has no address space yet, deduce it now.
7084 if (auto DT = dyn_cast<DecayedType>(Type)) {
7085 auto OrigTy = DT->getOriginalType();
7086 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
7087 // Add the address space to the original array type and then propagate
7088 // that to the element type through `getAsArrayType`.
7089 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
7090 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
7091 // Re-generate the decayed type.
7092 Type = Context.getDecayedType(OrigTy);
7093 }
7094 }
7095 Type = Context.getAddrSpaceQualType(Type, ImplAS);
7096 // Apply any qualifiers (including address space) from the array type to
7097 // the element type. This implements C99 6.7.3p8: "If the specification of
7098 // an array type includes any type qualifiers, the element type is so
7099 // qualified, not the array type."
7100 if (Type->isArrayType())
7101 Type = QualType(Context.getAsArrayType(Type), 0);
7102 Var->setType(Type);
7103}
7104
7105static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7106 // 'weak' only applies to declarations with external linkage.
7107 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7108 if (!ND.isExternallyVisible()) {
7109 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7110 ND.dropAttr<WeakAttr>();
7111 }
7112 }
7113}
7114
7115static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7116 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7117 if (ND.isExternallyVisible()) {
7118 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7119 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7120 }
7121 }
7122}
7123
7124static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7125 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7126 if (VD->hasInit()) {
7127 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7128 assert(VD->isThisDeclarationADefinition() &&
7129 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7130 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7131 VD->dropAttr<AliasAttr>();
7132 }
7133 }
7134 }
7135}
7136
7137static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7138 // 'selectany' only applies to externally visible variable declarations.
7139 // It does not apply to functions.
7140 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7141 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7142 S.Diag(Attr->getLocation(),
7143 diag::err_attribute_selectany_non_extern_data);
7144 ND.dropAttr<SelectAnyAttr>();
7145 }
7146 }
7147}
7148
7150 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7151 if (!ND.isExternallyVisible())
7152 S.Diag(Attr->getLocation(),
7153 diag::warn_attribute_hybrid_patchable_non_extern);
7154 }
7155}
7156
7158 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7159 auto *VD = dyn_cast<VarDecl>(&ND);
7160 bool IsAnonymousNS = false;
7161 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7162 if (VD) {
7163 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7164 while (NS && !IsAnonymousNS) {
7165 IsAnonymousNS = NS->isAnonymousNamespace();
7166 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7167 }
7168 }
7169 // dll attributes require external linkage. Static locals may have external
7170 // linkage but still cannot be explicitly imported or exported.
7171 // In Microsoft mode, a variable defined in anonymous namespace must have
7172 // external linkage in order to be exported.
7173 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7174 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7175 (!AnonNSInMicrosoftMode &&
7176 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7177 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7178 << &ND << Attr;
7179 ND.setInvalidDecl();
7180 }
7181 }
7182}
7183
7185 // Check the attributes on the function type and function params, if any.
7186 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7187 FD = FD->getMostRecentDecl();
7188 // Don't declare this variable in the second operand of the for-statement;
7189 // GCC miscompiles that by ending its lifetime before evaluating the
7190 // third operand. See gcc.gnu.org/PR86769.
7192 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7193 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7194 TL = ATL.getModifiedLoc()) {
7195 // The [[lifetimebound]] attribute can be applied to the implicit object
7196 // parameter of a non-static member function (other than a ctor or dtor)
7197 // by applying it to the function type.
7198 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7199 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7200 int NoImplicitObjectError = -1;
7201 if (!MD)
7202 NoImplicitObjectError = 0;
7203 else if (MD->isStatic())
7204 NoImplicitObjectError = 1;
7205 else if (MD->isExplicitObjectMemberFunction())
7206 NoImplicitObjectError = 2;
7207 if (NoImplicitObjectError != -1) {
7208 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7209 << NoImplicitObjectError << A->getRange();
7210 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7211 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7212 << isa<CXXDestructorDecl>(MD) << A->getRange();
7213 } else if (MD->getReturnType()->isVoidType()) {
7214 S.Diag(
7215 MD->getLocation(),
7216 diag::
7217 err_lifetimebound_implicit_object_parameter_void_return_type);
7218 }
7219 }
7220 }
7221
7222 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7223 const ParmVarDecl *P = FD->getParamDecl(I);
7224
7225 // The [[lifetimebound]] attribute can be applied to a function parameter
7226 // only if the function returns a value.
7227 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7228 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7229 S.Diag(A->getLocation(),
7230 diag::err_lifetimebound_parameter_void_return_type);
7231 }
7232 }
7233 }
7234 }
7235}
7236
7238 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7239 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7240}
7241
7243 // Ensure that an auto decl is deduced otherwise the checks below might cache
7244 // the wrong linkage.
7245 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7246
7247 checkWeakAttr(S, ND);
7248 checkWeakRefAttr(S, ND);
7249 checkAliasAttr(S, ND);
7250 checkSelectAnyAttr(S, ND);
7252 checkInheritableAttr(S, ND);
7255}
7256
7258 NamedDecl *NewDecl,
7259 bool IsSpecialization,
7260 bool IsDefinition) {
7261 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7262 return;
7263
7264 bool IsTemplate = false;
7265 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7266 OldDecl = OldTD->getTemplatedDecl();
7267 IsTemplate = true;
7268 if (!IsSpecialization)
7269 IsDefinition = false;
7270 }
7271 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7272 NewDecl = NewTD->getTemplatedDecl();
7273 IsTemplate = true;
7274 }
7275
7276 if (!OldDecl || !NewDecl)
7277 return;
7278
7279 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7280 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7281 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7282 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7283
7284 // dllimport and dllexport are inheritable attributes so we have to exclude
7285 // inherited attribute instances.
7286 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7287 (NewExportAttr && !NewExportAttr->isInherited());
7288
7289 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7290 // the only exception being explicit specializations.
7291 // Implicitly generated declarations are also excluded for now because there
7292 // is no other way to switch these to use dllimport or dllexport.
7293 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7294
7295 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7296 // Allow with a warning for free functions and global variables.
7297 bool JustWarn = false;
7298 if (!OldDecl->isCXXClassMember()) {
7299 auto *VD = dyn_cast<VarDecl>(OldDecl);
7300 if (VD && !VD->getDescribedVarTemplate())
7301 JustWarn = true;
7302 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7303 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7304 JustWarn = true;
7305 }
7306
7307 // We cannot change a declaration that's been used because IR has already
7308 // been emitted. Dllimported functions will still work though (modulo
7309 // address equality) as they can use the thunk.
7310 if (OldDecl->isUsed())
7311 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7312 JustWarn = false;
7313
7314 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7315 : diag::err_attribute_dll_redeclaration;
7316 S.Diag(NewDecl->getLocation(), DiagID)
7317 << NewDecl
7318 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7319 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7320 if (!JustWarn) {
7321 NewDecl->setInvalidDecl();
7322 return;
7323 }
7324 }
7325
7326 // A redeclaration is not allowed to drop a dllimport attribute, the only
7327 // exceptions being inline function definitions (except for function
7328 // templates), local extern declarations, qualified friend declarations or
7329 // special MSVC extension: in the last case, the declaration is treated as if
7330 // it were marked dllexport.
7331 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7332 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7333 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7334 // Ignore static data because out-of-line definitions are diagnosed
7335 // separately.
7336 IsStaticDataMember = VD->isStaticDataMember();
7337 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7339 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7340 IsInline = FD->isInlined();
7341 IsQualifiedFriend = FD->getQualifier() &&
7342 FD->getFriendObjectKind() == Decl::FOK_Declared;
7343 }
7344
7345 if (OldImportAttr && !HasNewAttr &&
7346 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7347 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7348 if (IsMicrosoftABI && IsDefinition) {
7349 if (IsSpecialization) {
7350 S.Diag(
7351 NewDecl->getLocation(),
7352 diag::err_attribute_dllimport_function_specialization_definition);
7353 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7354 NewDecl->dropAttr<DLLImportAttr>();
7355 } else {
7356 S.Diag(NewDecl->getLocation(),
7357 diag::warn_redeclaration_without_import_attribute)
7358 << NewDecl;
7359 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7360 NewDecl->dropAttr<DLLImportAttr>();
7361 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7362 S.Context, NewImportAttr->getRange()));
7363 }
7364 } else if (IsMicrosoftABI && IsSpecialization) {
7365 assert(!IsDefinition);
7366 // MSVC allows this. Keep the inherited attribute.
7367 } else {
7368 S.Diag(NewDecl->getLocation(),
7369 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7370 << NewDecl << OldImportAttr;
7371 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7372 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7373 OldDecl->dropAttr<DLLImportAttr>();
7374 NewDecl->dropAttr<DLLImportAttr>();
7375 }
7376 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7377 // In MinGW, seeing a function declared inline drops the dllimport
7378 // attribute.
7379 OldDecl->dropAttr<DLLImportAttr>();
7380 NewDecl->dropAttr<DLLImportAttr>();
7381 S.Diag(NewDecl->getLocation(),
7382 diag::warn_dllimport_dropped_from_inline_function)
7383 << NewDecl << OldImportAttr;
7384 }
7385
7386 // A specialization of a class template member function is processed here
7387 // since it's a redeclaration. If the parent class is dllexport, the
7388 // specialization inherits that attribute. This doesn't happen automatically
7389 // since the parent class isn't instantiated until later.
7390 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7391 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7392 !NewImportAttr && !NewExportAttr) {
7393 if (const DLLExportAttr *ParentExportAttr =
7394 MD->getParent()->getAttr<DLLExportAttr>()) {
7395 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7396 NewAttr->setInherited(true);
7397 NewDecl->addAttr(NewAttr);
7398 }
7399 }
7400 }
7401}
7402
7403/// Given that we are within the definition of the given function,
7404/// will that definition behave like C99's 'inline', where the
7405/// definition is discarded except for optimization purposes?
7407 // Try to avoid calling GetGVALinkageForFunction.
7408
7409 // All cases of this require the 'inline' keyword.
7410 if (!FD->isInlined()) return false;
7411
7412 // This is only possible in C++ with the gnu_inline attribute.
7413 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7414 return false;
7415
7416 // Okay, go ahead and call the relatively-more-expensive function.
7418}
7419
7420/// Determine whether a variable is extern "C" prior to attaching
7421/// an initializer. We can't just call isExternC() here, because that
7422/// will also compute and cache whether the declaration is externally
7423/// visible, which might change when we attach the initializer.
7424///
7425/// This can only be used if the declaration is known to not be a
7426/// redeclaration of an internal linkage declaration.
7427///
7428/// For instance:
7429///
7430/// auto x = []{};
7431///
7432/// Attaching the initializer here makes this declaration not externally
7433/// visible, because its type has internal linkage.
7434///
7435/// FIXME: This is a hack.
7436template<typename T>
7437static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7438 if (S.getLangOpts().CPlusPlus) {
7439 // In C++, the overloadable attribute negates the effects of extern "C".
7440 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7441 return false;
7442
7443 // So do CUDA's host/device attributes.
7444 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7445 D->template hasAttr<CUDAHostAttr>()))
7446 return false;
7447 }
7448 return D->isExternC();
7449}
7450
7451static bool shouldConsiderLinkage(const VarDecl *VD) {
7452 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7455 return VD->hasExternalStorage();
7456 if (DC->isFileContext())
7457 return true;
7458 if (DC->isRecord())
7459 return false;
7460 if (DC->getDeclKind() == Decl::HLSLBuffer)
7461 return false;
7462
7464 return false;
7465 llvm_unreachable("Unexpected context");
7466}
7467
7468static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7469 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7470 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7472 return true;
7473 if (DC->isRecord())
7474 return false;
7475 llvm_unreachable("Unexpected context");
7476}
7477
7478static bool hasParsedAttr(Scope *S, const Declarator &PD,
7479 ParsedAttr::Kind Kind) {
7480 // Check decl attributes on the DeclSpec.
7481 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7482 return true;
7483
7484 // Walk the declarator structure, checking decl attributes that were in a type
7485 // position to the decl itself.
7486 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7487 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7488 return true;
7489 }
7490
7491 // Finally, check attributes on the decl itself.
7492 return PD.getAttributes().hasAttribute(Kind) ||
7494}
7495
7497 if (!DC->isFunctionOrMethod())
7498 return false;
7499
7500 // If this is a local extern function or variable declared within a function
7501 // template, don't add it into the enclosing namespace scope until it is
7502 // instantiated; it might have a dependent type right now.
7503 if (DC->isDependentContext())
7504 return true;
7505
7506 // C++11 [basic.link]p7:
7507 // When a block scope declaration of an entity with linkage is not found to
7508 // refer to some other declaration, then that entity is a member of the
7509 // innermost enclosing namespace.
7510 //
7511 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7512 // semantically-enclosing namespace, not a lexically-enclosing one.
7513 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7514 DC = DC->getParent();
7515 return true;
7516}
7517
7518/// Returns true if given declaration has external C language linkage.
7519static bool isDeclExternC(const Decl *D) {
7520 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7521 return FD->isExternC();
7522 if (const auto *VD = dyn_cast<VarDecl>(D))
7523 return VD->isExternC();
7524
7525 llvm_unreachable("Unknown type of decl!");
7526}
7527
7528/// Returns true if there hasn't been any invalid type diagnosed.
7529static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7530 DeclContext *DC = NewVD->getDeclContext();
7531 QualType R = NewVD->getType();
7532
7533 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7534 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7535 // argument.
7536 if (R->isImageType() || R->isPipeType()) {
7537 Se.Diag(NewVD->getLocation(),
7538 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7539 << R;
7540 NewVD->setInvalidDecl();
7541 return false;
7542 }
7543
7544 // OpenCL v1.2 s6.9.r:
7545 // The event type cannot be used to declare a program scope variable.
7546 // OpenCL v2.0 s6.9.q:
7547 // The clk_event_t and reserve_id_t types cannot be declared in program
7548 // scope.
7549 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7550 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7551 Se.Diag(NewVD->getLocation(),
7552 diag::err_invalid_type_for_program_scope_var)
7553 << R;
7554 NewVD->setInvalidDecl();
7555 return false;
7556 }
7557 }
7558
7559 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7560 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7561 Se.getLangOpts())) {
7562 QualType NR = R.getCanonicalType();
7563 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7564 NR->isReferenceType()) {
7567 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7568 << NR->isReferenceType();
7569 NewVD->setInvalidDecl();
7570 return false;
7571 }
7572 NR = NR->getPointeeType();
7573 }
7574 }
7575
7576 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7577 Se.getLangOpts())) {
7578 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7579 // half array type (unless the cl_khr_fp16 extension is enabled).
7580 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7581 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7582 NewVD->setInvalidDecl();
7583 return false;
7584 }
7585 }
7586
7587 // OpenCL v1.2 s6.9.r:
7588 // The event type cannot be used with the __local, __constant and __global
7589 // address space qualifiers.
7590 if (R->isEventT()) {
7591 if (R.getAddressSpace() != LangAS::opencl_private) {
7592 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7593 NewVD->setInvalidDecl();
7594 return false;
7595 }
7596 }
7597
7598 if (R->isSamplerT()) {
7599 // OpenCL v1.2 s6.9.b p4:
7600 // The sampler type cannot be used with the __local and __global address
7601 // space qualifiers.
7602 if (R.getAddressSpace() == LangAS::opencl_local ||
7603 R.getAddressSpace() == LangAS::opencl_global) {
7604 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7605 NewVD->setInvalidDecl();
7606 }
7607
7608 // OpenCL v1.2 s6.12.14.1:
7609 // A global sampler must be declared with either the constant address
7610 // space qualifier or with the const qualifier.
7611 if (DC->isTranslationUnit() &&
7612 !(R.getAddressSpace() == LangAS::opencl_constant ||
7613 R.isConstQualified())) {
7614 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7615 NewVD->setInvalidDecl();
7616 }
7617 if (NewVD->isInvalidDecl())
7618 return false;
7619 }
7620
7621 return true;
7622}
7623
7624template <typename AttrTy>
7625static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7626 const TypedefNameDecl *TND = TT->getDecl();
7627 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7628 AttrTy *Clone = Attribute->clone(S.Context);
7629 Clone->setInherited(true);
7630 D->addAttr(Clone);
7631 }
7632}
7633
7634// This function emits warning and a corresponding note based on the
7635// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7636// declarations of an annotated type must be const qualified.
7638 QualType VarType = VD->getType().getCanonicalType();
7639
7640 // Ignore local declarations (for now) and those with const qualification.
7641 // TODO: Local variables should not be allowed if their type declaration has
7642 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7643 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7644 return;
7645
7646 if (VarType->isArrayType()) {
7647 // Retrieve element type for array declarations.
7648 VarType = S.getASTContext().getBaseElementType(VarType);
7649 }
7650
7651 const RecordDecl *RD = VarType->getAsRecordDecl();
7652
7653 // Check if the record declaration is present and if it has any attributes.
7654 if (RD == nullptr)
7655 return;
7656
7657 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7658 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7659 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7660 return;
7661 }
7662}
7663
7665 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7666 "NewD is not a function or variable");
7667
7668 if (PendingExportedNames.empty())
7669 return;
7670 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(NewD)) {
7671 if (getLangOpts().CPlusPlus && !FD->isExternC())
7672 return;
7673 }
7674 IdentifierInfo *IdentName = NewD->getIdentifier();
7675 if (IdentName == nullptr)
7676 return;
7677 auto PendingName = PendingExportedNames.find(IdentName);
7678 if (PendingName != PendingExportedNames.end()) {
7679 auto &Label = PendingName->second;
7680 if (!Label.Used) {
7681 Label.Used = true;
7682 if (NewD->hasExternalFormalLinkage())
7683 mergeVisibilityType(NewD, Label.NameLoc, VisibilityAttr::Default);
7684 else
7685 Diag(Label.NameLoc, diag::warn_pragma_not_applied) << "export" << NewD;
7686 }
7687 }
7688}
7689
7690// Checks if VD is declared at global scope or with C language linkage.
7691static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7692 return Name.getAsIdentifierInfo() &&
7693 Name.getAsIdentifierInfo()->isStr("main") &&
7694 !VD->getDescribedVarTemplate() &&
7695 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7696 VD->isExternC());
7697}
7698
7699void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7700 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7701
7702 // Quickly return if the function does not have an `asm` attribute.
7703 if (E == nullptr)
7704 return;
7705
7706 // The parser guarantees this is a string.
7707 StringLiteral *SE = cast<StringLiteral>(E);
7708 StringRef Label = SE->getString();
7709 QualType R = TInfo->getType();
7710 if (S->getFnParent() != nullptr) {
7711 switch (SC) {
7712 case SC_None:
7713 case SC_Auto:
7714 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7715 break;
7716 case SC_Register:
7717 // Local Named register
7718 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7720 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7721 break;
7722 case SC_Static:
7723 case SC_Extern:
7724 case SC_PrivateExtern:
7725 break;
7726 }
7727 } else if (SC == SC_Register) {
7728 // Global Named register
7729 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7730 const auto &TI = Context.getTargetInfo();
7731 bool HasSizeMismatch;
7732
7733 if (!TI.isValidGCCRegisterName(Label))
7734 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7735 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7736 HasSizeMismatch))
7737 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7738 else if (HasSizeMismatch)
7739 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7740 }
7741
7742 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7743 Diag(TInfo->getTypeLoc().getBeginLoc(),
7744 diag::err_asm_unsupported_register_type)
7745 << TInfo->getTypeLoc().getSourceRange();
7746 NewVD->setInvalidDecl(true);
7747 }
7748 }
7749}
7750
7752 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7753 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7754 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7755 QualType R = TInfo->getType();
7757
7759 bool IsPlaceholderVariable = false;
7760
7761 if (D.isDecompositionDeclarator()) {
7762 // Take the name of the first declarator as our name for diagnostic
7763 // purposes.
7764 auto &Decomp = D.getDecompositionDeclarator();
7765 if (!Decomp.bindings().empty()) {
7766 II = Decomp.bindings()[0].Name;
7767 Name = II;
7768 }
7769 } else if (!II) {
7770 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7771 return nullptr;
7772 }
7773
7774
7777 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7778 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7779
7780 IsPlaceholderVariable = true;
7781
7782 if (!Previous.empty()) {
7783 NamedDecl *PrevDecl = *Previous.begin();
7784 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7785 DC->getRedeclContext());
7786 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7787 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7788 if (IsPlaceholderVariable)
7790 }
7791 }
7792 }
7793
7794 // dllimport globals without explicit storage class are treated as extern. We
7795 // have to change the storage class this early to get the right DeclContext.
7796 if (SC == SC_None && !DC->isRecord() &&
7797 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7798 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7799 SC = SC_Extern;
7800
7801 DeclContext *OriginalDC = DC;
7802 bool IsLocalExternDecl = SC == SC_Extern &&
7804
7805 if (SCSpec == DeclSpec::SCS_mutable) {
7806 // mutable can only appear on non-static class members, so it's always
7807 // an error here
7808 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7809 D.setInvalidType();
7810 SC = SC_None;
7811 }
7812
7813 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7814 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7816 // In C++11, the 'register' storage class specifier is deprecated.
7817 // Suppress the warning in system macros, it's used in macros in some
7818 // popular C system headers, such as in glibc's htonl() macro.
7820 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7821 : diag::warn_deprecated_register)
7823 }
7824
7826
7827 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7828 // C99 6.9p2: The storage-class specifiers auto and register shall not
7829 // appear in the declaration specifiers in an external declaration.
7830 // Global Register+Asm is a GNU extension we support.
7831 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7832 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7833 D.setInvalidType();
7834 }
7835 }
7836
7837 // If this variable has a VLA type and an initializer, try to
7838 // fold to a constant-sized type. This is otherwise invalid.
7839 if (D.hasInitializer() && R->isVariableArrayType())
7841 /*DiagID=*/0);
7842
7843 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7844 const AutoType *AT = TL.getTypePtr();
7845 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7846 }
7847
7848 bool IsMemberSpecialization = false;
7849 bool IsVariableTemplateSpecialization = false;
7850 bool IsPartialSpecialization = false;
7851 bool IsVariableTemplate = false;
7852 VarDecl *NewVD = nullptr;
7853 VarTemplateDecl *NewTemplate = nullptr;
7854 TemplateParameterList *TemplateParams = nullptr;
7855 if (!getLangOpts().CPlusPlus) {
7857 II, R, TInfo, SC);
7858
7859 if (R->getContainedDeducedType())
7860 ParsingInitForAutoVars.insert(NewVD);
7861
7862 if (D.isInvalidType())
7863 NewVD->setInvalidDecl();
7864
7866 NewVD->hasLocalStorage())
7867 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7869 } else {
7870 bool Invalid = false;
7871 // Match up the template parameter lists with the scope specifier, then
7872 // determine whether we have a template or a template specialization.
7875 D.getCXXScopeSpec(),
7877 ? D.getName().TemplateId
7878 : nullptr,
7879 TemplateParamLists,
7880 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7881
7882 if (TemplateParams) {
7883 if (DC->isDependentContext()) {
7884 ContextRAII SavedContext(*this, DC);
7886 Invalid = true;
7887 }
7888
7889 if (!TemplateParams->size() &&
7891 // There is an extraneous 'template<>' for this variable. Complain
7892 // about it, but allow the declaration of the variable.
7893 Diag(TemplateParams->getTemplateLoc(),
7894 diag::err_template_variable_noparams)
7895 << II
7896 << SourceRange(TemplateParams->getTemplateLoc(),
7897 TemplateParams->getRAngleLoc());
7898 TemplateParams = nullptr;
7899 } else {
7900 // Check that we can declare a template here.
7901 if (CheckTemplateDeclScope(S, TemplateParams))
7902 return nullptr;
7903
7905 // This is an explicit specialization or a partial specialization.
7906 IsVariableTemplateSpecialization = true;
7907 IsPartialSpecialization = TemplateParams->size() > 0;
7908 } else { // if (TemplateParams->size() > 0)
7909 // This is a template declaration.
7910 IsVariableTemplate = true;
7911
7912 // Only C++1y supports variable templates (N3651).
7913 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7914 }
7915 }
7916 } else {
7917 // Check that we can declare a member specialization here.
7918 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7919 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7920 return nullptr;
7921 assert((Invalid ||
7923 "should have a 'template<>' for this decl");
7924 }
7925
7926 bool IsExplicitSpecialization =
7927 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7928
7929 // C++ [temp.expl.spec]p2:
7930 // The declaration in an explicit-specialization shall not be an
7931 // export-declaration. An explicit specialization shall not use a
7932 // storage-class-specifier other than thread_local.
7933 //
7934 // We use the storage-class-specifier from DeclSpec because we may have
7935 // added implicit 'extern' for declarations with __declspec(dllimport)!
7936 if (SCSpec != DeclSpec::SCS_unspecified &&
7937 (IsExplicitSpecialization || IsMemberSpecialization)) {
7939 diag::ext_explicit_specialization_storage_class)
7941 }
7942
7943 if (CurContext->isRecord()) {
7944 if (SC == SC_Static) {
7945 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7946 // Walk up the enclosing DeclContexts to check for any that are
7947 // incompatible with static data members.
7948 const DeclContext *FunctionOrMethod = nullptr;
7949 const CXXRecordDecl *AnonStruct = nullptr;
7950 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7951 if (Ctxt->isFunctionOrMethod()) {
7952 FunctionOrMethod = Ctxt;
7953 break;
7954 }
7955 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7956 if (ParentDecl && !ParentDecl->getDeclName()) {
7957 AnonStruct = ParentDecl;
7958 break;
7959 }
7960 }
7961 if (FunctionOrMethod) {
7962 // C++ [class.static.data]p5: A local class shall not have static
7963 // data members.
7965 diag::err_static_data_member_not_allowed_in_local_class)
7966 << Name << RD->getDeclName() << RD->getTagKind();
7967 } else if (AnonStruct) {
7968 // C++ [class.static.data]p4: Unnamed classes and classes contained
7969 // directly or indirectly within unnamed classes shall not contain
7970 // static data members.
7972 diag::err_static_data_member_not_allowed_in_anon_struct)
7973 << Name << AnonStruct->getTagKind();
7974 Invalid = true;
7975 } else if (RD->isUnion()) {
7976 // C++98 [class.union]p1: If a union contains a static data member,
7977 // the program is ill-formed. C++11 drops this restriction.
7979 diag_compat::static_data_member_in_union)
7980 << Name;
7981 }
7982 }
7983 } else if (IsVariableTemplate || IsPartialSpecialization) {
7984 // There is no such thing as a member field template.
7985 Diag(D.getIdentifierLoc(), diag::err_template_member)
7986 << II << TemplateParams->getSourceRange();
7987 // Recover by pretending this is a static data member template.
7988 SC = SC_Static;
7989 }
7990 } else if (DC->isRecord()) {
7991 // This is an out-of-line definition of a static data member.
7992 switch (SC) {
7993 case SC_None:
7994 break;
7995 case SC_Static:
7997 diag::err_static_out_of_line)
8000 break;
8001 case SC_Auto:
8002 case SC_Register:
8003 case SC_Extern:
8004 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8005 // to names of variables declared in a block or to function parameters.
8006 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8007 // of class members
8008
8010 diag::err_storage_class_for_static_member)
8013 break;
8014 case SC_PrivateExtern:
8015 llvm_unreachable("C storage class in c++!");
8016 }
8017 }
8018
8019 if (IsVariableTemplateSpecialization) {
8020 SourceLocation TemplateKWLoc =
8021 TemplateParamLists.size() > 0
8022 ? TemplateParamLists[0]->getTemplateLoc()
8023 : SourceLocation();
8025 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8027 if (Res.isInvalid())
8028 return nullptr;
8029 NewVD = cast<VarDecl>(Res.get());
8030 AddToScope = false;
8031 } else if (D.isDecompositionDeclarator()) {
8033 D.getIdentifierLoc(), R, TInfo, SC,
8034 Bindings);
8035 } else
8036 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
8037 D.getIdentifierLoc(), II, R, TInfo, SC);
8038
8039 // If this is supposed to be a variable template, create it as such.
8040 if (IsVariableTemplate) {
8041 NewTemplate =
8043 TemplateParams, NewVD);
8044 NewVD->setDescribedVarTemplate(NewTemplate);
8045 }
8046
8047 // If this decl has an auto type in need of deduction, make a note of the
8048 // Decl so we can diagnose uses of it in its own initializer.
8049 if (R->getContainedDeducedType())
8050 ParsingInitForAutoVars.insert(NewVD);
8051
8052 if (D.isInvalidType() || Invalid) {
8053 NewVD->setInvalidDecl();
8054 if (NewTemplate)
8055 NewTemplate->setInvalidDecl();
8056 }
8057
8058 SetNestedNameSpecifier(*this, NewVD, D);
8059
8060 // If we have any template parameter lists that don't directly belong to
8061 // the variable (matching the scope specifier), store them.
8062 // An explicit variable template specialization does not own any template
8063 // parameter lists.
8064 unsigned VDTemplateParamLists =
8065 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8066 if (TemplateParamLists.size() > VDTemplateParamLists)
8068 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8069 }
8070
8071 if (D.getDeclSpec().isInlineSpecified()) {
8072 if (!getLangOpts().CPlusPlus) {
8073 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8074 << 0;
8075 } else if (CurContext->isFunctionOrMethod()) {
8076 // 'inline' is not allowed on block scope variable declaration.
8078 diag::err_inline_declaration_block_scope) << Name
8080 } else {
8082 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8083 : diag::compat_pre_cxx17_inline_variable);
8084 NewVD->setInlineSpecified();
8085 }
8086 }
8087
8088 // Set the lexical context. If the declarator has a C++ scope specifier, the
8089 // lexical context will be different from the semantic context.
8091 if (NewTemplate)
8092 NewTemplate->setLexicalDeclContext(CurContext);
8093
8094 if (IsLocalExternDecl) {
8096 for (auto *B : Bindings)
8097 B->setLocalExternDecl();
8098 else
8099 NewVD->setLocalExternDecl();
8100 }
8101
8102 bool EmitTLSUnsupportedError = false;
8104 // C++11 [dcl.stc]p4:
8105 // When thread_local is applied to a variable of block scope the
8106 // storage-class-specifier static is implied if it does not appear
8107 // explicitly.
8108 // Core issue: 'static' is not implied if the variable is declared
8109 // 'extern'.
8110 if (NewVD->hasLocalStorage() &&
8111 (SCSpec != DeclSpec::SCS_unspecified ||
8113 !DC->isFunctionOrMethod()))
8115 diag::err_thread_non_global)
8117 else if (!Context.getTargetInfo().isTLSSupported()) {
8118 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8119 // Postpone error emission until we've collected attributes required to
8120 // figure out whether it's a host or device variable and whether the
8121 // error should be ignored.
8122 EmitTLSUnsupportedError = true;
8123 // We still need to mark the variable as TLS so it shows up in AST with
8124 // proper storage class for other tools to use even if we're not going
8125 // to emit any code for it.
8126 NewVD->setTSCSpec(TSCS);
8127 } else
8129 diag::err_thread_unsupported);
8130 } else
8131 NewVD->setTSCSpec(TSCS);
8132 }
8133
8134 switch (D.getDeclSpec().getConstexprSpecifier()) {
8136 break;
8137
8140 diag::err_constexpr_wrong_decl_kind)
8141 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8142 [[fallthrough]];
8143
8145 NewVD->setConstexpr(true);
8146 // C++1z [dcl.spec.constexpr]p1:
8147 // A static data member declared with the constexpr specifier is
8148 // implicitly an inline variable.
8149 if (NewVD->isStaticDataMember() &&
8151 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8152 NewVD->setImplicitlyInline();
8153 break;
8154
8156 if (!NewVD->hasGlobalStorage())
8158 diag::err_constinit_local_variable);
8159 else
8160 NewVD->addAttr(
8161 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8162 ConstInitAttr::Keyword_constinit));
8163 break;
8164 }
8165
8166 // C99 6.7.4p3
8167 // An inline definition of a function with external linkage shall
8168 // not contain a definition of a modifiable object with static or
8169 // thread storage duration...
8170 // We only apply this when the function is required to be defined
8171 // elsewhere, i.e. when the function is not 'extern inline'. Note
8172 // that a local variable with thread storage duration still has to
8173 // be marked 'static'. Also note that it's possible to get these
8174 // semantics in C++ using __attribute__((gnu_inline)).
8175 if (SC == SC_Static && S->getFnParent() != nullptr &&
8176 !NewVD->getType().isConstQualified()) {
8178 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8180 diag::warn_static_local_in_extern_inline);
8182 }
8183 }
8184
8186 if (IsVariableTemplateSpecialization)
8187 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8188 << (IsPartialSpecialization ? 1 : 0)
8191 else if (IsMemberSpecialization)
8192 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8193 << 2
8195 else if (NewVD->hasLocalStorage())
8196 Diag(NewVD->getLocation(), diag::err_module_private_local)
8197 << 0 << NewVD
8201 else {
8202 NewVD->setModulePrivate();
8203 if (NewTemplate)
8204 NewTemplate->setModulePrivate();
8205 for (auto *B : Bindings)
8206 B->setModulePrivate();
8207 }
8208 }
8209
8210 if (getLangOpts().OpenCL) {
8212
8214 if (TSC != TSCS_unspecified) {
8216 diag::err_opencl_unknown_type_specifier)
8218 << DeclSpec::getSpecifierName(TSC) << 1;
8219 NewVD->setInvalidDecl();
8220 }
8221 }
8222
8223 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8224 // address space if the table has local storage (semantic checks elsewhere
8225 // will produce an error anyway).
8226 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8227 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8228 !NewVD->hasLocalStorage()) {
8229 QualType Type = Context.getAddrSpaceQualType(
8230 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8231 NewVD->setType(Type);
8232 }
8233 }
8234
8235 if (Expr *E = D.getAsmLabel()) {
8236 // The parser guarantees this is a string.
8238 StringRef Label = SE->getString();
8239
8240 // Insert the asm attribute.
8241 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8242 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8243 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8245 if (I != ExtnameUndeclaredIdentifiers.end()) {
8246 if (isDeclExternC(NewVD)) {
8247 NewVD->addAttr(I->second);
8249 } else
8250 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8251 << /*Variable*/ 1 << NewVD;
8252 }
8253 }
8254
8255 // Handle attributes prior to checking for duplicates in MergeVarDecl
8256 ProcessDeclAttributes(S, NewVD, D);
8257
8258 if (getLangOpts().HLSL)
8260
8261 if (getLangOpts().OpenACC)
8263
8264 // FIXME: This is probably the wrong location to be doing this and we should
8265 // probably be doing this for more attributes (especially for function
8266 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8267 // the code to copy attributes would be generated by TableGen.
8268 if (R->isFunctionPointerType())
8269 if (const auto *TT = R->getAs<TypedefType>())
8271
8272 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8273 if (EmitTLSUnsupportedError &&
8275 (getLangOpts().OpenMPIsTargetDevice &&
8276 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8278 diag::err_thread_unsupported);
8279
8280 if (EmitTLSUnsupportedError &&
8281 (LangOpts.SYCLIsDevice ||
8282 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8283 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8284 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8285 // storage [duration]."
8286 if (SC == SC_None && S->getFnParent() != nullptr &&
8287 (NewVD->hasAttr<CUDASharedAttr>() ||
8288 NewVD->hasAttr<CUDAConstantAttr>())) {
8289 NewVD->setStorageClass(SC_Static);
8290 }
8291 }
8292
8293 // Ensure that dllimport globals without explicit storage class are treated as
8294 // extern. The storage class is set above using parsed attributes. Now we can
8295 // check the VarDecl itself.
8296 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8297 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8298 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8299
8300 // In auto-retain/release, infer strong retension for variables of
8301 // retainable type.
8302 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8303 NewVD->setInvalidDecl();
8304
8305 // Check the ASM label here, as we need to know all other attributes of the
8306 // Decl first. Otherwise, we can't know if the asm label refers to the
8307 // host or device in a CUDA context. The device has other registers than
8308 // host and we must know where the function will be placed.
8309 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8310
8311 // Find the shadowed declaration before filtering for scope.
8312 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8314 : nullptr;
8315
8316 // Don't consider existing declarations that are in a different
8317 // scope and are out-of-semantic-context declarations (if the new
8318 // declaration has linkage).
8321 IsMemberSpecialization ||
8322 IsVariableTemplateSpecialization);
8323
8324 // Check whether the previous declaration is in the same block scope. This
8325 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8326 if (getLangOpts().CPlusPlus &&
8327 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8329 Previous.isSingleResult() && !Previous.isShadowed() &&
8330 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8331
8332 if (!getLangOpts().CPlusPlus) {
8334 } else {
8335 // If this is an explicit specialization of a static data member, check it.
8336 if (IsMemberSpecialization && !IsVariableTemplate &&
8337 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8339 NewVD->setInvalidDecl();
8340
8341 // Merge the decl with the existing one if appropriate.
8342 if (!Previous.empty()) {
8343 if (Previous.isSingleResult() &&
8344 isa<FieldDecl>(Previous.getFoundDecl()) &&
8345 D.getCXXScopeSpec().isSet()) {
8346 // The user tried to define a non-static data member
8347 // out-of-line (C++ [dcl.meaning]p1).
8348 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8349 << D.getCXXScopeSpec().getRange();
8350 Previous.clear();
8351 NewVD->setInvalidDecl();
8352 }
8353 } else if (D.getCXXScopeSpec().isSet() &&
8354 !IsVariableTemplateSpecialization) {
8355 // No previous declaration in the qualifying scope.
8356 Diag(D.getIdentifierLoc(), diag::err_no_member)
8357 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8358 << D.getCXXScopeSpec().getRange();
8359 NewVD->setInvalidDecl();
8360 }
8361
8362 if (!IsPlaceholderVariable)
8364
8365 // CheckVariableDeclaration will set NewVD as invalid if something is in
8366 // error like WebAssembly tables being declared as arrays with a non-zero
8367 // size, but then parsing continues and emits further errors on that line.
8368 // To avoid that we check here if it happened and return nullptr.
8369 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8370 return nullptr;
8371
8372 if (NewTemplate) {
8373 VarTemplateDecl *PrevVarTemplate =
8374 NewVD->getPreviousDecl()
8376 : nullptr;
8377
8378 // Check the template parameter list of this declaration, possibly
8379 // merging in the template parameter list from the previous variable
8380 // template declaration.
8382 TemplateParams,
8383 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8384 : nullptr,
8385 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8386 DC->isDependentContext())
8388 : TPC_Other))
8389 NewVD->setInvalidDecl();
8390
8391 // If we are providing an explicit specialization of a static variable
8392 // template, make a note of that.
8393 if (PrevVarTemplate &&
8394 PrevVarTemplate->getInstantiatedFromMemberTemplate())
8395 PrevVarTemplate->setMemberSpecialization();
8396 }
8397 }
8398
8399 // Diagnose shadowed variables iff this isn't a redeclaration.
8400 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8401 CheckShadow(NewVD, ShadowedDecl, Previous);
8402
8403 ProcessPragmaWeak(S, NewVD);
8404 ProcessPragmaExport(NewVD);
8405
8406 // If this is the first declaration of an extern C variable, update
8407 // the map of such variables.
8408 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8409 isIncompleteDeclExternC(*this, NewVD))
8411
8412 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8414 Decl *ManglingContextDecl;
8415 std::tie(MCtx, ManglingContextDecl) =
8417 if (MCtx) {
8418 Context.setManglingNumber(
8419 NewVD, MCtx->getManglingNumber(
8420 NewVD, getMSManglingNumber(getLangOpts(), S)));
8421 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8422 }
8423 }
8424
8425 // Special handling of variable named 'main'.
8426 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8427 // C++ [basic.start.main]p3:
8428 // A program that declares
8429 // - a variable main at global scope, or
8430 // - an entity named main with C language linkage (in any namespace)
8431 // is ill-formed
8432 if (getLangOpts().CPlusPlus)
8433 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8434 << NewVD->isExternC();
8435
8436 // In C, and external-linkage variable named main results in undefined
8437 // behavior.
8438 else if (NewVD->hasExternalFormalLinkage())
8439 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8440 }
8441
8442 if (D.isRedeclaration() && !Previous.empty()) {
8443 NamedDecl *Prev = Previous.getRepresentativeDecl();
8444 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8446 }
8447
8448 if (NewTemplate) {
8449 if (NewVD->isInvalidDecl())
8450 NewTemplate->setInvalidDecl();
8451 ActOnDocumentableDecl(NewTemplate);
8452 return NewTemplate;
8453 }
8454
8455 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8457
8459
8460 return NewVD;
8461}
8462
8463/// Enum describing the %select options in diag::warn_decl_shadow.
8473
8474/// Determine what kind of declaration we're shadowing.
8476 const DeclContext *OldDC) {
8477 if (isa<TypeAliasDecl>(ShadowedDecl))
8478 return SDK_Using;
8479 else if (isa<TypedefDecl>(ShadowedDecl))
8480 return SDK_Typedef;
8481 else if (isa<BindingDecl>(ShadowedDecl))
8482 return SDK_StructuredBinding;
8483 else if (isa<RecordDecl>(OldDC))
8484 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8485
8486 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8487}
8488
8489/// Return the location of the capture if the given lambda captures the given
8490/// variable \p VD, or an invalid source location otherwise.
8492 const ValueDecl *VD) {
8493 for (const Capture &Capture : LSI->Captures) {
8495 return Capture.getLocation();
8496 }
8497 return SourceLocation();
8498}
8499
8501 const LookupResult &R) {
8502 // Only diagnose if we're shadowing an unambiguous field or variable.
8503 if (R.getResultKind() != LookupResultKind::Found)
8504 return false;
8505
8506 // Return false if warning is ignored.
8507 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8508}
8509
8511 const LookupResult &R) {
8513 return nullptr;
8514
8515 // Don't diagnose declarations at file scope.
8516 if (D->hasGlobalStorage() && !D->isStaticLocal())
8517 return nullptr;
8518
8519 NamedDecl *ShadowedDecl = R.getFoundDecl();
8520 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8521 : nullptr;
8522}
8523
8525 const LookupResult &R) {
8526 // Don't warn if typedef declaration is part of a class
8527 if (D->getDeclContext()->isRecord())
8528 return nullptr;
8529
8531 return nullptr;
8532
8533 NamedDecl *ShadowedDecl = R.getFoundDecl();
8534 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8535}
8536
8538 const LookupResult &R) {
8540 return nullptr;
8541
8542 NamedDecl *ShadowedDecl = R.getFoundDecl();
8543 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8544 : nullptr;
8545}
8546
8548 const LookupResult &R) {
8549 DeclContext *NewDC = D->getDeclContext();
8550
8551 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8552 if (const auto *MD =
8553 dyn_cast<CXXMethodDecl>(getFunctionLevelDeclContext())) {
8554 // Fields aren't shadowed in C++ static members or in member functions
8555 // with an explicit object parameter.
8556 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8557 return;
8558 }
8559 // Fields shadowed by constructor parameters are a special case. Usually
8560 // the constructor initializes the field with the parameter.
8561 if (isa<CXXConstructorDecl>(NewDC))
8562 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8563 // Remember that this was shadowed so we can either warn about its
8564 // modification or its existence depending on warning settings.
8565 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8566 return;
8567 }
8568 }
8569
8570 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8571 if (shadowedVar->isExternC()) {
8572 // For shadowing external vars, make sure that we point to the global
8573 // declaration, not a locally scoped extern declaration.
8574 for (auto *I : shadowedVar->redecls())
8575 if (I->isFileVarDecl()) {
8576 ShadowedDecl = I;
8577 break;
8578 }
8579 }
8580
8581 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8582
8583 unsigned WarningDiag = diag::warn_decl_shadow;
8584 SourceLocation CaptureLoc;
8585 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8586 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8587 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8588 // Handle both VarDecl and BindingDecl in lambda contexts
8589 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8590 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8591 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8592 if (RD->getLambdaCaptureDefault() == LCD_None) {
8593 // Try to avoid warnings for lambdas with an explicit capture
8594 // list. Warn only when the lambda captures the shadowed decl
8595 // explicitly.
8596 CaptureLoc = getCaptureLocation(LSI, VD);
8597 if (CaptureLoc.isInvalid())
8598 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8599 } else {
8600 // Remember that this was shadowed so we can avoid the warning if
8601 // the shadowed decl isn't captured and the warning settings allow
8602 // it.
8604 ->ShadowingDecls.push_back({D, VD});
8605 return;
8606 }
8607 }
8608 if (isa<FieldDecl>(ShadowedDecl)) {
8609 // If lambda can capture this, then emit default shadowing warning,
8610 // Otherwise it is not really a shadowing case since field is not
8611 // available in lambda's body.
8612 // At this point we don't know that lambda can capture this, so
8613 // remember that this was shadowed and delay until we know.
8615 ->ShadowingDecls.push_back({D, ShadowedDecl});
8616 return;
8617 }
8618 }
8619 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8620 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8621 bool HasLocalStorage = false;
8622 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8623 HasLocalStorage = VD->hasLocalStorage();
8624 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8625 HasLocalStorage =
8626 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8627
8628 if (HasLocalStorage) {
8629 // A variable can't shadow a local variable or binding in an enclosing
8630 // scope, if they are separated by a non-capturing declaration
8631 // context.
8632 for (DeclContext *ParentDC = NewDC;
8633 ParentDC && !ParentDC->Equals(OldDC);
8634 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8635 // Only block literals, captured statements, and lambda expressions
8636 // can capture; other scopes don't.
8637 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8638 !isLambdaCallOperator(ParentDC))
8639 return;
8640 }
8641 }
8642 }
8643 }
8644 }
8645
8646 // Never warn about shadowing a placeholder variable.
8647 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8648 return;
8649
8650 // Only warn about certain kinds of shadowing for class members.
8651 if (NewDC) {
8652 // In particular, don't warn about shadowing non-class members.
8653 if (NewDC->isRecord() && !OldDC->isRecord())
8654 return;
8655
8656 // Skip shadowing check if we're in a class scope, dealing with an enum
8657 // constant in a different context.
8658 DeclContext *ReDC = NewDC->getRedeclContext();
8659 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8660 return;
8661
8662 // TODO: should we warn about static data members shadowing
8663 // static data members from base classes?
8664
8665 // TODO: don't diagnose for inaccessible shadowed members.
8666 // This is hard to do perfectly because we might friend the
8667 // shadowing context, but that's just a false negative.
8668 }
8669
8670 DeclarationName Name = R.getLookupName();
8671
8672 // Emit warning and note.
8673 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8674 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8675 if (!CaptureLoc.isInvalid())
8676 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8677 << Name << /*explicitly*/ 1;
8678 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8679}
8680
8682 for (const auto &Shadow : LSI->ShadowingDecls) {
8683 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8684 // Try to avoid the warning when the shadowed decl isn't captured.
8685 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8686 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8687 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8688 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8689 Diag(Shadow.VD->getLocation(),
8690 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8691 : diag::warn_decl_shadow)
8692 << Shadow.VD->getDeclName()
8693 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8694 if (CaptureLoc.isValid())
8695 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8696 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8697 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8698 } else if (isa<FieldDecl>(ShadowedDecl)) {
8699 Diag(Shadow.VD->getLocation(),
8700 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8701 : diag::warn_decl_shadow_uncaptured_local)
8702 << Shadow.VD->getDeclName()
8703 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8704 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8705 }
8706 }
8707}
8708
8710 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8711 return;
8712
8713 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8716 LookupName(R, S);
8717 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8718 CheckShadow(D, ShadowedDecl, R);
8719}
8720
8721/// Check if 'E', which is an expression that is about to be modified, refers
8722/// to a constructor parameter that shadows a field.
8724 // Quickly ignore expressions that can't be shadowing ctor parameters.
8725 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8726 return;
8727 E = E->IgnoreParenImpCasts();
8728 auto *DRE = dyn_cast<DeclRefExpr>(E);
8729 if (!DRE)
8730 return;
8731 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8732 auto I = ShadowingDecls.find(D);
8733 if (I == ShadowingDecls.end())
8734 return;
8735 const NamedDecl *ShadowedDecl = I->second;
8736 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8737 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8738 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8739 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8740
8741 // Avoid issuing multiple warnings about the same decl.
8742 ShadowingDecls.erase(I);
8743}
8744
8745/// Check for conflict between this global or extern "C" declaration and
8746/// previous global or extern "C" declarations. This is only used in C++.
8747template<typename T>
8749 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8750 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8751 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8752
8753 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8754 // The common case: this global doesn't conflict with any extern "C"
8755 // declaration.
8756 return false;
8757 }
8758
8759 if (Prev) {
8760 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8761 // Both the old and new declarations have C language linkage. This is a
8762 // redeclaration.
8763 Previous.clear();
8764 Previous.addDecl(Prev);
8765 return true;
8766 }
8767
8768 // This is a global, non-extern "C" declaration, and there is a previous
8769 // non-global extern "C" declaration. Diagnose if this is a variable
8770 // declaration.
8771 if (!isa<VarDecl>(ND))
8772 return false;
8773 } else {
8774 // The declaration is extern "C". Check for any declaration in the
8775 // translation unit which might conflict.
8776 if (IsGlobal) {
8777 // We have already performed the lookup into the translation unit.
8778 IsGlobal = false;
8779 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8780 I != E; ++I) {
8781 if (isa<VarDecl>(*I)) {
8782 Prev = *I;
8783 break;
8784 }
8785 }
8786 } else {
8788 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8789 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8790 I != E; ++I) {
8791 if (isa<VarDecl>(*I)) {
8792 Prev = *I;
8793 break;
8794 }
8795 // FIXME: If we have any other entity with this name in global scope,
8796 // the declaration is ill-formed, but that is a defect: it breaks the
8797 // 'stat' hack, for instance. Only variables can have mangled name
8798 // clashes with extern "C" declarations, so only they deserve a
8799 // diagnostic.
8800 }
8801 }
8802
8803 if (!Prev)
8804 return false;
8805 }
8806
8807 // Use the first declaration's location to ensure we point at something which
8808 // is lexically inside an extern "C" linkage-spec.
8809 assert(Prev && "should have found a previous declaration to diagnose");
8810 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8811 Prev = FD->getFirstDecl();
8812 else
8813 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8814
8815 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8816 << IsGlobal << ND;
8817 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8818 << IsGlobal;
8819 return false;
8820}
8821
8822/// Apply special rules for handling extern "C" declarations. Returns \c true
8823/// if we have found that this is a redeclaration of some prior entity.
8824///
8825/// Per C++ [dcl.link]p6:
8826/// Two declarations [for a function or variable] with C language linkage
8827/// with the same name that appear in different scopes refer to the same
8828/// [entity]. An entity with C language linkage shall not be declared with
8829/// the same name as an entity in global scope.
8830template<typename T>
8833 if (!S.getLangOpts().CPlusPlus) {
8834 // In C, when declaring a global variable, look for a corresponding 'extern'
8835 // variable declared in function scope. We don't need this in C++, because
8836 // we find local extern decls in the surrounding file-scope DeclContext.
8837 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8838 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8839 Previous.clear();
8840 Previous.addDecl(Prev);
8841 return true;
8842 }
8843 }
8844 return false;
8845 }
8846
8847 // A declaration in the translation unit can conflict with an extern "C"
8848 // declaration.
8849 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8850 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8851
8852 // An extern "C" declaration can conflict with a declaration in the
8853 // translation unit or can be a redeclaration of an extern "C" declaration
8854 // in another scope.
8855 if (isIncompleteDeclExternC(S,ND))
8856 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8857
8858 // Neither global nor extern "C": nothing to do.
8859 return false;
8860}
8861
8862static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8863 QualType T) {
8864 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8865 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8866 // any of its members, even recursively, shall not have an atomic type, or a
8867 // variably modified type, or a type that is volatile or restrict qualified.
8868 if (CanonT->isVariablyModifiedType()) {
8869 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8870 return true;
8871 }
8872
8873 // Arrays are qualified by their element type, so get the base type (this
8874 // works on non-arrays as well).
8875 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8876
8877 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8878 CanonT.isRestrictQualified()) {
8879 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8880 return true;
8881 }
8882
8883 if (CanonT->isRecordType()) {
8884 const RecordDecl *RD = CanonT->getAsRecordDecl();
8885 if (!RD->isInvalidDecl() &&
8886 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8887 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8888 }))
8889 return true;
8890 }
8891
8892 return false;
8893}
8894
8896 // If the decl is already known invalid, don't check it.
8897 if (NewVD->isInvalidDecl())
8898 return;
8899
8900 QualType T = NewVD->getType();
8901
8902 // Defer checking an 'auto' type until its initializer is attached.
8903 if (T->isUndeducedType())
8904 return;
8905
8906 if (NewVD->hasAttrs())
8908
8909 if (T->isObjCObjectType()) {
8910 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8911 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8912 T = Context.getObjCObjectPointerType(T);
8913 NewVD->setType(T);
8914 }
8915
8916 // Emit an error if an address space was applied to decl with local storage.
8917 // This includes arrays of objects with address space qualifiers, but not
8918 // automatic variables that point to other address spaces.
8919 // ISO/IEC TR 18037 S5.1.2
8920 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8921 T.getAddressSpace() != LangAS::Default) {
8922 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8923 NewVD->setInvalidDecl();
8924 return;
8925 }
8926
8927 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8928 // scope.
8929 if (getLangOpts().OpenCLVersion == 120 &&
8930 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8931 getLangOpts()) &&
8932 NewVD->isStaticLocal()) {
8933 Diag(NewVD->getLocation(), diag::err_static_function_scope);
8934 NewVD->setInvalidDecl();
8935 return;
8936 }
8937
8938 if (getLangOpts().OpenCL) {
8939 if (!diagnoseOpenCLTypes(*this, NewVD))
8940 return;
8941
8942 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8943 if (NewVD->hasAttr<BlocksAttr>()) {
8944 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8945 return;
8946 }
8947
8948 if (T->isBlockPointerType()) {
8949 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8950 // can't use 'extern' storage class.
8951 if (!T.isConstQualified()) {
8952 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8953 << 0 /*const*/;
8954 NewVD->setInvalidDecl();
8955 return;
8956 }
8957 if (NewVD->hasExternalStorage()) {
8958 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8959 NewVD->setInvalidDecl();
8960 return;
8961 }
8962 }
8963
8964 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8965 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8966 NewVD->hasExternalStorage()) {
8967 if (!T->isSamplerT() && !T->isDependentType() &&
8968 !(T.getAddressSpace() == LangAS::opencl_constant ||
8969 (T.getAddressSpace() == LangAS::opencl_global &&
8970 getOpenCLOptions().areProgramScopeVariablesSupported(
8971 getLangOpts())))) {
8972 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8973 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8974 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8975 << Scope << "global or constant";
8976 else
8977 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8978 << Scope << "constant";
8979 NewVD->setInvalidDecl();
8980 return;
8981 }
8982 } else {
8983 if (T.getAddressSpace() == LangAS::opencl_global) {
8984 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8985 << 1 /*is any function*/ << "global";
8986 NewVD->setInvalidDecl();
8987 return;
8988 }
8989 // When this extension is enabled, 'local' variables are permitted in
8990 // non-kernel functions and within nested scopes of kernel functions,
8991 // bypassing standard OpenCL address space restrictions.
8992 bool AllowFunctionScopeLocalVariables =
8993 T.getAddressSpace() == LangAS::opencl_local &&
8995 "__cl_clang_function_scope_local_variables", getLangOpts());
8996 if (AllowFunctionScopeLocalVariables) {
8997 // Direct pass: No further diagnostics needed for this specific case.
8998 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
8999 T.getAddressSpace() == LangAS::opencl_local) {
9001 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9002 // in functions.
9003 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9004 if (T.getAddressSpace() == LangAS::opencl_constant)
9005 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9006 << 0 /*non-kernel only*/ << "constant";
9007 else
9008 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9009 << 0 /*non-kernel only*/ << "local";
9010 NewVD->setInvalidDecl();
9011 return;
9012 }
9013 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9014 // in the outermost scope of a kernel function.
9015 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9016 if (!getCurScope()->isFunctionScope()) {
9017 if (T.getAddressSpace() == LangAS::opencl_constant)
9018 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9019 << "constant";
9020 else
9021 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9022 << "local";
9023 NewVD->setInvalidDecl();
9024 return;
9025 }
9026 }
9027 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9028 // If we are parsing a template we didn't deduce an addr
9029 // space yet.
9030 T.getAddressSpace() != LangAS::Default) {
9031 // Do not allow other address spaces on automatic variable.
9032 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
9033 NewVD->setInvalidDecl();
9034 return;
9035 }
9036 }
9037 }
9038
9039 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9040 && !NewVD->hasAttr<BlocksAttr>()) {
9041 if (getLangOpts().getGC() != LangOptions::NonGC)
9042 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
9043 else {
9044 assert(!getLangOpts().ObjCAutoRefCount);
9045 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
9046 }
9047 }
9048
9049 // WebAssembly tables must be static with a zero length and can't be
9050 // declared within functions.
9051 if (T->isWebAssemblyTableType()) {
9052 if (getCurScope()->getParent()) { // Parent is null at top-level
9053 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9054 NewVD->setInvalidDecl();
9055 return;
9056 }
9057 if (NewVD->getStorageClass() != SC_Static) {
9058 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9059 NewVD->setInvalidDecl();
9060 return;
9061 }
9062 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9063 if (!ATy || ATy->getZExtSize() != 0) {
9064 Diag(NewVD->getLocation(),
9065 diag::err_typecheck_wasm_table_must_have_zero_length);
9066 NewVD->setInvalidDecl();
9067 return;
9068 }
9069 }
9070
9071 // zero sized static arrays are not allowed in HIP device functions
9072 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9073 if (FunctionDecl *FD = getCurFunctionDecl();
9074 FD &&
9075 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9076 if (const ConstantArrayType *ArrayT =
9077 getASTContext().getAsConstantArrayType(T);
9078 ArrayT && ArrayT->isZeroSize()) {
9079 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9080 }
9081 }
9082 }
9083
9084 bool isVM = T->isVariablyModifiedType();
9085 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9086 NewVD->hasAttr<BlocksAttr>())
9088
9089 if ((isVM && NewVD->hasLinkage()) ||
9090 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9091 bool SizeIsNegative;
9092 llvm::APSInt Oversized;
9094 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9095 QualType FixedT;
9096 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9097 FixedT = FixedTInfo->getType();
9098 else if (FixedTInfo) {
9099 // Type and type-as-written are canonically different. We need to fix up
9100 // both types separately.
9101 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9102 Oversized);
9103 }
9104 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9105 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9106 // FIXME: This won't give the correct result for
9107 // int a[10][n];
9108 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9109
9110 if (NewVD->isFileVarDecl())
9111 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9112 << SizeRange;
9113 else if (NewVD->isStaticLocal())
9114 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9115 << SizeRange;
9116 else
9117 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9118 << SizeRange;
9119 NewVD->setInvalidDecl();
9120 return;
9121 }
9122
9123 if (!FixedTInfo) {
9124 if (NewVD->isFileVarDecl())
9125 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9126 else
9127 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9128 NewVD->setInvalidDecl();
9129 return;
9130 }
9131
9132 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9133 NewVD->setType(FixedT);
9134 NewVD->setTypeSourceInfo(FixedTInfo);
9135 }
9136
9137 if (T->isVoidType()) {
9138 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9139 // of objects and functions.
9141 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9142 << T;
9143 NewVD->setInvalidDecl();
9144 return;
9145 }
9146 }
9147
9148 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
9149 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
9150 NewVD->setInvalidDecl();
9151 return;
9152 }
9153
9154 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9155 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9156 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9157 NewVD->setInvalidDecl();
9158 return;
9159 }
9160
9161 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9162 Diag(NewVD->getLocation(), diag::err_block_on_vm);
9163 NewVD->setInvalidDecl();
9164 return;
9165 }
9166
9167 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9168 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9169 NewVD->setInvalidDecl();
9170 return;
9171 }
9172
9173 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9174 !T->isDependentType() &&
9175 RequireLiteralType(NewVD->getLocation(), T,
9176 diag::err_constexpr_var_non_literal)) {
9177 NewVD->setInvalidDecl();
9178 return;
9179 }
9180
9181 // PPC MMA non-pointer types are not allowed as non-local variable types.
9182 if (Context.getTargetInfo().getTriple().isPPC64() &&
9183 !NewVD->isLocalVarDecl() &&
9184 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9185 NewVD->setInvalidDecl();
9186 return;
9187 }
9188
9189 // Check that SVE types are only used in functions with SVE available.
9190 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9192 llvm::StringMap<bool> CallerFeatureMap;
9193 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9194 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9195 CallerFeatureMap)) {
9196 NewVD->setInvalidDecl();
9197 return;
9198 }
9199 }
9200
9201 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9203 llvm::StringMap<bool> CallerFeatureMap;
9204 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9206 CallerFeatureMap);
9207 }
9208
9209 if (T.hasAddressSpace() &&
9210 !CheckVarDeclSizeAddressSpace(NewVD, T.getAddressSpace())) {
9211 NewVD->setInvalidDecl();
9212 return;
9213 }
9214}
9215
9218
9219 // If the decl is already known invalid, don't check it.
9220 if (NewVD->isInvalidDecl())
9221 return false;
9222
9223 // If we did not find anything by this name, look for a non-visible
9224 // extern "C" declaration with the same name.
9225 if (Previous.empty() &&
9227 Previous.setShadowed();
9228
9229 if (!Previous.empty()) {
9230 MergeVarDecl(NewVD, Previous);
9231 return true;
9232 }
9233 return false;
9234}
9235
9238
9239 // Look for methods in base classes that this method might override.
9240 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9241 /*DetectVirtual=*/false);
9242 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9243 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9244 DeclarationName Name = MD->getDeclName();
9245
9247 // We really want to find the base class destructor here.
9248 Name = Context.DeclarationNames.getCXXDestructorName(
9249 Context.getCanonicalTagType(BaseRecord));
9250 }
9251
9252 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9253 CXXMethodDecl *BaseMD =
9254 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9255 if (!BaseMD || !BaseMD->isVirtual() ||
9256 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9257 /*ConsiderCudaAttrs=*/true))
9258 continue;
9259 if (!CheckExplicitObjectOverride(MD, BaseMD))
9260 continue;
9261 if (Overridden.insert(BaseMD).second) {
9262 MD->addOverriddenMethod(BaseMD);
9267 }
9268
9269 // A method can only override one function from each base class. We
9270 // don't track indirectly overridden methods from bases of bases.
9271 return true;
9272 }
9273
9274 return false;
9275 };
9276
9277 DC->lookupInBases(VisitBase, Paths);
9278 return !Overridden.empty();
9279}
9280
9281namespace {
9282 // Struct for holding all of the extra arguments needed by
9283 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9284 struct ActOnFDArgs {
9285 Scope *S;
9286 Declarator &D;
9287 MultiTemplateParamsArg TemplateParamLists;
9288 bool AddToScope;
9289 };
9290} // end anonymous namespace
9291
9292namespace {
9293
9294// Callback to only accept typo corrections that have a non-zero edit distance.
9295// Also only accept corrections that have the same parent decl.
9296class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9297 public:
9298 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9299 CXXRecordDecl *Parent)
9300 : Context(Context), OriginalFD(TypoFD),
9301 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9302
9303 bool ValidateCandidate(const TypoCorrection &candidate) override {
9304 if (candidate.getEditDistance() == 0)
9305 return false;
9306
9307 SmallVector<unsigned, 1> MismatchedParams;
9308 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9309 CDeclEnd = candidate.end();
9310 CDecl != CDeclEnd; ++CDecl) {
9311 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9312
9313 if (FD && !FD->hasBody() &&
9314 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9315 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9316 CXXRecordDecl *Parent = MD->getParent();
9317 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9318 return true;
9319 } else if (!ExpectedParent) {
9320 return true;
9321 }
9322 }
9323 }
9324
9325 return false;
9326 }
9327
9328 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9329 return std::make_unique<DifferentNameValidatorCCC>(*this);
9330 }
9331
9332 private:
9333 ASTContext &Context;
9334 FunctionDecl *OriginalFD;
9335 CXXRecordDecl *ExpectedParent;
9336};
9337
9338} // end anonymous namespace
9339
9343
9344/// Generate diagnostics for an invalid function redeclaration.
9345///
9346/// This routine handles generating the diagnostic messages for an invalid
9347/// function redeclaration, including finding possible similar declarations
9348/// or performing typo correction if there are no previous declarations with
9349/// the same name.
9350///
9351/// Returns a NamedDecl iff typo correction was performed and substituting in
9352/// the new declaration name does not cause new errors.
9354 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9355 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9356 DeclarationName Name = NewFD->getDeclName();
9357 DeclContext *NewDC = NewFD->getDeclContext();
9358 SmallVector<unsigned, 1> MismatchedParams;
9360 TypoCorrection Correction;
9361 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9362 unsigned DiagMsg =
9363 IsLocalFriend ? diag::err_no_matching_local_friend :
9364 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9365 diag::err_member_decl_does_not_match;
9366 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9367 IsLocalFriend ? Sema::LookupLocalFriendName
9370
9371 NewFD->setInvalidDecl();
9372 if (IsLocalFriend)
9373 SemaRef.LookupName(Prev, S);
9374 else
9375 SemaRef.LookupQualifiedName(Prev, NewDC);
9376 assert(!Prev.isAmbiguous() &&
9377 "Cannot have an ambiguity in previous-declaration lookup");
9378 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9379 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9380 MD ? MD->getParent() : nullptr);
9381 if (!Prev.empty()) {
9382 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9383 Func != FuncEnd; ++Func) {
9384 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9385 if (FD &&
9386 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9387 // Add 1 to the index so that 0 can mean the mismatch didn't
9388 // involve a parameter
9389 unsigned ParamNum =
9390 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9391 NearMatches.push_back(std::make_pair(FD, ParamNum));
9392 }
9393 }
9394 // If the qualified name lookup yielded nothing, try typo correction
9395 } else if ((Correction = SemaRef.CorrectTypo(
9396 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9397 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9399 IsLocalFriend ? nullptr : NewDC))) {
9400 // Set up everything for the call to ActOnFunctionDeclarator
9401 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9402 ExtraArgs.D.getIdentifierLoc());
9403 Previous.clear();
9404 Previous.setLookupName(Correction.getCorrection());
9405 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9406 CDeclEnd = Correction.end();
9407 CDecl != CDeclEnd; ++CDecl) {
9408 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9409 if (FD && !FD->hasBody() &&
9410 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9411 Previous.addDecl(FD);
9412 }
9413 }
9414 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9415
9416 NamedDecl *Result;
9417 // Retry building the function declaration with the new previous
9418 // declarations, and with errors suppressed.
9419 {
9420 // Trap errors.
9421 Sema::SFINAETrap Trap(SemaRef);
9422
9423 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9424 // pieces need to verify the typo-corrected C++ declaration and hopefully
9425 // eliminate the need for the parameter pack ExtraArgs.
9426 Result = SemaRef.ActOnFunctionDeclarator(
9427 ExtraArgs.S, ExtraArgs.D,
9428 Correction.getCorrectionDecl()->getDeclContext(),
9429 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9430 ExtraArgs.AddToScope);
9431
9432 if (Trap.hasErrorOccurred())
9433 Result = nullptr;
9434 }
9435
9436 if (Result) {
9437 // Determine which correction we picked.
9438 Decl *Canonical = Result->getCanonicalDecl();
9439 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9440 I != E; ++I)
9441 if ((*I)->getCanonicalDecl() == Canonical)
9442 Correction.setCorrectionDecl(*I);
9443
9444 // Let Sema know about the correction.
9446 SemaRef.diagnoseTypo(
9447 Correction,
9448 SemaRef.PDiag(IsLocalFriend
9449 ? diag::err_no_matching_local_friend_suggest
9450 : diag::err_member_decl_does_not_match_suggest)
9451 << Name << NewDC << IsDefinition);
9452 return Result;
9453 }
9454
9455 // Pretend the typo correction never occurred
9456 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9457 ExtraArgs.D.getIdentifierLoc());
9458 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9459 Previous.clear();
9460 Previous.setLookupName(Name);
9461 }
9462
9463 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9464 << Name << NewDC << IsDefinition << NewFD->getLocation();
9465
9466 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9467 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9468 CXXRecordDecl *RD = NewMD->getParent();
9469 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9470 << RD->getName() << RD->getLocation();
9471 }
9472
9473 bool NewFDisConst = NewMD && NewMD->isConst();
9474
9475 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9476 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9477 NearMatch != NearMatchEnd; ++NearMatch) {
9478 FunctionDecl *FD = NearMatch->first;
9479 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9480 bool FDisConst = MD && MD->isConst();
9481 bool IsMember = MD || !IsLocalFriend;
9482
9483 // FIXME: These notes are poorly worded for the local friend case.
9484 if (unsigned Idx = NearMatch->second) {
9485 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9486 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9487 if (Loc.isInvalid()) Loc = FD->getLocation();
9488 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9489 : diag::note_local_decl_close_param_match)
9490 << Idx << FDParam->getType()
9491 << NewFD->getParamDecl(Idx - 1)->getType();
9492 } else if (FDisConst != NewFDisConst) {
9493 auto DB = SemaRef.Diag(FD->getLocation(),
9494 diag::note_member_def_close_const_match)
9495 << NewFDisConst << FD->getSourceRange().getEnd();
9496 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9497 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9498 " const");
9499 else if (FTI.hasMethodTypeQualifiers() &&
9500 FTI.getConstQualifierLoc().isValid())
9501 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9502 } else {
9503 SemaRef.Diag(FD->getLocation(),
9504 IsMember ? diag::note_member_def_close_match
9505 : diag::note_local_decl_close_match);
9506 }
9507 }
9508 return nullptr;
9509}
9510
9512 switch (D.getDeclSpec().getStorageClassSpec()) {
9513 default: llvm_unreachable("Unknown storage class!");
9514 case DeclSpec::SCS_auto:
9518 diag::err_typecheck_sclass_func);
9520 D.setInvalidType();
9521 break;
9522 case DeclSpec::SCS_unspecified: break;
9525 return SC_None;
9526 return SC_Extern;
9527 case DeclSpec::SCS_static: {
9529 // C99 6.7.1p5:
9530 // The declaration of an identifier for a function that has
9531 // block scope shall have no explicit storage-class specifier
9532 // other than extern
9533 // See also (C++ [dcl.stc]p4).
9535 diag::err_static_block_func);
9536 break;
9537 } else
9538 return SC_Static;
9539 }
9541 }
9542
9543 // No explicit storage class has already been returned
9544 return SC_None;
9545}
9546
9548 DeclContext *DC, QualType &R,
9549 TypeSourceInfo *TInfo,
9550 StorageClass SC,
9551 bool &IsVirtualOkay) {
9552 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9553 DeclarationName Name = NameInfo.getName();
9554
9555 FunctionDecl *NewFD = nullptr;
9556 bool isInline = D.getDeclSpec().isInlineSpecified();
9557
9559 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9560 (SemaRef.getLangOpts().C23 &&
9561 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9562
9563 if (SemaRef.getLangOpts().C23)
9564 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9565 diag::err_c23_constexpr_not_variable);
9566 else
9567 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9568 diag::err_constexpr_wrong_decl_kind)
9569 << static_cast<int>(ConstexprKind);
9570 ConstexprKind = ConstexprSpecKind::Unspecified;
9572 }
9573
9574 if (!SemaRef.getLangOpts().CPlusPlus) {
9575 // Determine whether the function was written with a prototype. This is
9576 // true when:
9577 // - there is a prototype in the declarator, or
9578 // - the type R of the function is some kind of typedef or other non-
9579 // attributed reference to a type name (which eventually refers to a
9580 // function type). Note, we can't always look at the adjusted type to
9581 // check this case because attributes may cause a non-function
9582 // declarator to still have a function type. e.g.,
9583 // typedef void func(int a);
9584 // __attribute__((noreturn)) func other_func; // This has a prototype
9585 bool HasPrototype =
9587 (D.getDeclSpec().isTypeRep() &&
9588 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9589 ->isFunctionProtoType()) ||
9590 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9591 assert(
9592 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9593 "Strict prototypes are required");
9594
9595 NewFD = FunctionDecl::Create(
9596 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9597 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9599 /*TrailingRequiresClause=*/{});
9600 if (D.isInvalidType())
9601 NewFD->setInvalidDecl();
9602
9603 return NewFD;
9604 }
9605
9607 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9608
9609 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9610
9612 // This is a C++ constructor declaration.
9613 assert(DC->isRecord() &&
9614 "Constructors can only be declared in a member context");
9615
9616 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9618 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9620 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9621 InheritedConstructor(), TrailingRequiresClause);
9622
9623 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9624 // This is a C++ destructor declaration.
9625 if (DC->isRecord()) {
9626 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9629 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9630 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9631 /*isImplicitlyDeclared=*/false, ConstexprKind,
9632 TrailingRequiresClause);
9633 // User defined destructors start as not selected if the class definition is still
9634 // not done.
9635 if (Record->isBeingDefined())
9636 NewDD->setIneligibleOrNotSelected(true);
9637
9638 // If the destructor needs an implicit exception specification, set it
9639 // now. FIXME: It'd be nice to be able to create the right type to start
9640 // with, but the type needs to reference the destructor declaration.
9641 if (SemaRef.getLangOpts().CPlusPlus11)
9642 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9643
9644 IsVirtualOkay = true;
9645 return NewDD;
9646
9647 } else {
9648 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9649 D.setInvalidType();
9650
9651 // Create a FunctionDecl to satisfy the function definition parsing
9652 // code path.
9653 return FunctionDecl::Create(
9654 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9655 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9656 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9657 }
9658
9660 if (!DC->isRecord()) {
9661 SemaRef.Diag(D.getIdentifierLoc(),
9662 diag::err_conv_function_not_member);
9663 return nullptr;
9664 }
9665
9666 SemaRef.CheckConversionDeclarator(D, R, SC);
9667 if (D.isInvalidType())
9668 return nullptr;
9669
9670 IsVirtualOkay = true;
9672 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9673 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9674 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9675 TrailingRequiresClause);
9676
9678 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9679 return nullptr;
9681 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9682 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9683 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9684 } else if (DC->isRecord()) {
9685 // If the name of the function is the same as the name of the record,
9686 // then this must be an invalid constructor that has a return type.
9687 // (The parser checks for a return type and makes the declarator a
9688 // constructor if it has no return type).
9689 if (Name.getAsIdentifierInfo() &&
9690 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9691 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9694 return nullptr;
9695 }
9696
9697 // This is a C++ method declaration.
9699 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9700 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9701 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9702 IsVirtualOkay = !Ret->isStatic();
9703 return Ret;
9704 } else {
9705 bool isFriend =
9706 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9707 if (!isFriend && SemaRef.CurContext->isRecord())
9708 return nullptr;
9709
9710 // Determine whether the function was written with a
9711 // prototype. This true when:
9712 // - we're in C++ (where every function has a prototype),
9713 return FunctionDecl::Create(
9714 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9715 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9716 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9717 }
9718}
9719
9728
9730 // Size dependent types are just typedefs to normal integer types
9731 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9732 // integers other than by their names.
9733 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9734
9735 // Remove typedefs one by one until we reach a typedef
9736 // for a size dependent type.
9737 QualType DesugaredTy = Ty;
9738 do {
9739 ArrayRef<StringRef> Names(SizeTypeNames);
9740 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9741 if (Names.end() != Match)
9742 return true;
9743
9744 Ty = DesugaredTy;
9745 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9746 } while (DesugaredTy != Ty);
9747
9748 return false;
9749}
9750
9752 if (PT->isDependentType())
9753 return InvalidKernelParam;
9754
9755 if (PT->isPointerOrReferenceType()) {
9756 QualType PointeeType = PT->getPointeeType();
9757 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9758 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9759 PointeeType.getAddressSpace() == LangAS::Default)
9761
9762 if (PointeeType->isPointerType()) {
9763 // This is a pointer to pointer parameter.
9764 // Recursively check inner type.
9765 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9766 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9767 ParamKind == InvalidKernelParam)
9768 return ParamKind;
9769
9770 // OpenCL v3.0 s6.11.a:
9771 // A restriction to pass pointers to pointers only applies to OpenCL C
9772 // v1.2 or below.
9774 return ValidKernelParam;
9775
9776 return PtrPtrKernelParam;
9777 }
9778
9779 // C++ for OpenCL v1.0 s2.4:
9780 // Moreover the types used in parameters of the kernel functions must be:
9781 // Standard layout types for pointer parameters. The same applies to
9782 // reference if an implementation supports them in kernel parameters.
9783 if (S.getLangOpts().OpenCLCPlusPlus &&
9785 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9786 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9787 bool IsStandardLayoutType = true;
9788 if (CXXRec) {
9789 // If template type is not ODR-used its definition is only available
9790 // in the template definition not its instantiation.
9791 // FIXME: This logic doesn't work for types that depend on template
9792 // parameter (PR58590).
9793 if (!CXXRec->hasDefinition())
9794 CXXRec = CXXRec->getTemplateInstantiationPattern();
9795 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9796 IsStandardLayoutType = false;
9797 }
9798 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9799 !IsStandardLayoutType)
9800 return InvalidKernelParam;
9801 }
9802
9803 // OpenCL v1.2 s6.9.p:
9804 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9806 return ValidKernelParam;
9807
9808 return PtrKernelParam;
9809 }
9810
9811 // OpenCL v1.2 s6.9.k:
9812 // Arguments to kernel functions in a program cannot be declared with the
9813 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9814 // uintptr_t or a struct and/or union that contain fields declared to be one
9815 // of these built-in scalar types.
9817 return InvalidKernelParam;
9818
9819 if (PT->isImageType())
9820 return PtrKernelParam;
9821
9822 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9823 return InvalidKernelParam;
9824
9825 // OpenCL extension spec v1.2 s9.5:
9826 // This extension adds support for half scalar and vector types as built-in
9827 // types that can be used for arithmetic operations, conversions etc.
9828 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9829 PT->isHalfType())
9830 return InvalidKernelParam;
9831
9832 // Look into an array argument to check if it has a forbidden type.
9833 if (PT->isArrayType()) {
9834 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9835 // Call ourself to check an underlying type of an array. Since the
9836 // getPointeeOrArrayElementType returns an innermost type which is not an
9837 // array, this recursive call only happens once.
9838 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9839 }
9840
9841 // C++ for OpenCL v1.0 s2.4:
9842 // Moreover the types used in parameters of the kernel functions must be:
9843 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9844 // types) for parameters passed by value;
9845 if (S.getLangOpts().OpenCLCPlusPlus &&
9847 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9848 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9849 return InvalidKernelParam;
9850
9851 if (PT->isRecordType())
9852 return RecordKernelParam;
9853
9854 return ValidKernelParam;
9855}
9856
9858 Sema &S,
9859 Declarator &D,
9860 ParmVarDecl *Param,
9861 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9862 QualType PT = Param->getType();
9863
9864 // Cache the valid types we encounter to avoid rechecking structs that are
9865 // used again
9866 if (ValidTypes.count(PT.getTypePtr()))
9867 return;
9868
9869 switch (getOpenCLKernelParameterType(S, PT)) {
9870 case PtrPtrKernelParam:
9871 // OpenCL v3.0 s6.11.a:
9872 // A kernel function argument cannot be declared as a pointer to a pointer
9873 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9874 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9875 D.setInvalidType();
9876 return;
9877
9879 // OpenCL v1.0 s6.5:
9880 // __kernel function arguments declared to be a pointer of a type can point
9881 // to one of the following address spaces only : __global, __local or
9882 // __constant.
9883 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9884 D.setInvalidType();
9885 return;
9886
9887 // OpenCL v1.2 s6.9.k:
9888 // Arguments to kernel functions in a program cannot be declared with the
9889 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9890 // uintptr_t or a struct and/or union that contain fields declared to be
9891 // one of these built-in scalar types.
9892
9893 case InvalidKernelParam:
9894 // OpenCL v1.2 s6.8 n:
9895 // A kernel function argument cannot be declared
9896 // of event_t type.
9897 // Do not diagnose half type since it is diagnosed as invalid argument
9898 // type for any function elsewhere.
9899 if (!PT->isHalfType()) {
9900 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9901
9902 // Explain what typedefs are involved.
9903 const TypedefType *Typedef = nullptr;
9904 while ((Typedef = PT->getAs<TypedefType>())) {
9905 SourceLocation Loc = Typedef->getDecl()->getLocation();
9906 // SourceLocation may be invalid for a built-in type.
9907 if (Loc.isValid())
9908 S.Diag(Loc, diag::note_entity_declared_at) << PT;
9909 PT = Typedef->desugar();
9910 }
9911 }
9912
9913 D.setInvalidType();
9914 return;
9915
9916 case PtrKernelParam:
9917 case ValidKernelParam:
9918 ValidTypes.insert(PT.getTypePtr());
9919 return;
9920
9921 case RecordKernelParam:
9922 break;
9923 }
9924
9925 // Track nested structs we will inspect
9927
9928 // Track where we are in the nested structs. Items will migrate from
9929 // VisitStack to HistoryStack as we do the DFS for bad field.
9931 HistoryStack.push_back(nullptr);
9932
9933 // At this point we already handled everything except of a RecordType.
9934 assert(PT->isRecordType() && "Unexpected type.");
9935 const auto *PD = PT->castAsRecordDecl();
9936 VisitStack.push_back(PD);
9937 assert(VisitStack.back() && "First decl null?");
9938
9939 do {
9940 const Decl *Next = VisitStack.pop_back_val();
9941 if (!Next) {
9942 assert(!HistoryStack.empty());
9943 // Found a marker, we have gone up a level
9944 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9945 ValidTypes.insert(Hist->getType().getTypePtr());
9946
9947 continue;
9948 }
9949
9950 // Adds everything except the original parameter declaration (which is not a
9951 // field itself) to the history stack.
9952 const RecordDecl *RD;
9953 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9954 HistoryStack.push_back(Field);
9955
9956 QualType FieldTy = Field->getType();
9957 // Other field types (known to be valid or invalid) are handled while we
9958 // walk around RecordDecl::fields().
9959 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9960 "Unexpected type.");
9961 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9962
9963 RD = FieldRecTy->castAsRecordDecl();
9964 } else {
9965 RD = cast<RecordDecl>(Next);
9966 }
9967
9968 // Add a null marker so we know when we've gone back up a level
9969 VisitStack.push_back(nullptr);
9970
9971 for (const auto *FD : RD->fields()) {
9972 QualType QT = FD->getType();
9973
9974 if (ValidTypes.count(QT.getTypePtr()))
9975 continue;
9976
9978 if (ParamType == ValidKernelParam)
9979 continue;
9980
9981 if (ParamType == RecordKernelParam) {
9982 VisitStack.push_back(FD);
9983 continue;
9984 }
9985
9986 // OpenCL v1.2 s6.9.p:
9987 // Arguments to kernel functions that are declared to be a struct or union
9988 // do not allow OpenCL objects to be passed as elements of the struct or
9989 // union. This restriction was lifted in OpenCL v2.0 with the introduction
9990 // of SVM.
9991 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9992 ParamType == InvalidAddrSpacePtrKernelParam) {
9993 S.Diag(Param->getLocation(),
9994 diag::err_record_with_pointers_kernel_param)
9995 << PT->isUnionType()
9996 << PT;
9997 } else {
9998 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9999 }
10000
10001 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
10002 << PD->getDeclName();
10003
10004 // We have an error, now let's go back up through history and show where
10005 // the offending field came from
10007 I = HistoryStack.begin() + 1,
10008 E = HistoryStack.end();
10009 I != E; ++I) {
10010 const FieldDecl *OuterField = *I;
10011 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
10012 << OuterField->getType();
10013 }
10014
10015 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
10016 << QT->isPointerType()
10017 << QT;
10018 D.setInvalidType();
10019 return;
10020 }
10021 } while (!VisitStack.empty());
10022}
10023
10024/// Find the DeclContext in which a tag is implicitly declared if we see an
10025/// elaborated type specifier in the specified context, and lookup finds
10026/// nothing.
10028 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10029 DC = DC->getParent();
10030 return DC;
10031}
10032
10033/// Find the Scope in which a tag is implicitly declared if we see an
10034/// elaborated type specifier in the specified context, and lookup finds
10035/// nothing.
10036static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10037 while (S->isClassScope() ||
10038 (LangOpts.CPlusPlus &&
10040 ((S->getFlags() & Scope::DeclScope) == 0) ||
10041 (S->getEntity() && S->getEntity()->isTransparentContext()))
10042 S = S->getParent();
10043 return S;
10044}
10045
10046/// Determine whether a declaration matches a known function in namespace std.
10048 unsigned BuiltinID) {
10049 switch (BuiltinID) {
10050 case Builtin::BI__GetExceptionInfo:
10051 // No type checking whatsoever.
10052 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10053
10054 case Builtin::BIaddressof:
10055 case Builtin::BI__addressof:
10056 case Builtin::BIforward:
10057 case Builtin::BIforward_like:
10058 case Builtin::BImove:
10059 case Builtin::BImove_if_noexcept:
10060 case Builtin::BIas_const: {
10061 // Ensure that we don't treat the algorithm
10062 // OutputIt std::move(InputIt, InputIt, OutputIt)
10063 // as the builtin std::move.
10064 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10065 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10066 }
10067
10068 default:
10069 return false;
10070 }
10071}
10072
10073NamedDecl*
10076 MultiTemplateParamsArg TemplateParamListsRef,
10077 bool &AddToScope) {
10078 QualType R = TInfo->getType();
10079
10080 assert(R->isFunctionType());
10081 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10082 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10083
10084 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10085 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10087 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10088 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10089 TemplateParamLists.back() = Invented;
10090 else
10091 TemplateParamLists.push_back(Invented);
10092 }
10093
10094 // TODO: consider using NameInfo for diagnostic.
10096 DeclarationName Name = NameInfo.getName();
10098
10101 diag::err_invalid_thread)
10103
10108
10109 bool isFriend = false;
10111 bool isMemberSpecialization = false;
10112 bool isFunctionTemplateSpecialization = false;
10113
10114 bool HasExplicitTemplateArgs = false;
10115 TemplateArgumentListInfo TemplateArgs;
10116
10117 bool isVirtualOkay = false;
10118
10119 DeclContext *OriginalDC = DC;
10120 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10121
10122 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10123 isVirtualOkay);
10124 if (!NewFD) return nullptr;
10125
10126 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10128
10129 // Set the lexical context. If this is a function-scope declaration, or has a
10130 // C++ scope specifier, or is the object of a friend declaration, the lexical
10131 // context will be different from the semantic context.
10133
10134 if (IsLocalExternDecl)
10135 NewFD->setLocalExternDecl();
10136
10137 if (getLangOpts().CPlusPlus) {
10138 // The rules for implicit inlines changed in C++20 for methods and friends
10139 // with an in-class definition (when such a definition is not attached to
10140 // the global module). This does not affect declarations that are already
10141 // inline (whether explicitly or implicitly by being declared constexpr,
10142 // consteval, etc).
10143 // FIXME: We need a better way to separate C++ standard and clang modules.
10144 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10145 !NewFD->getOwningModule() ||
10146 NewFD->isFromGlobalModule() ||
10148 bool isInline = D.getDeclSpec().isInlineSpecified();
10149 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10150 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10151 isFriend = D.getDeclSpec().isFriendSpecified();
10152 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10153 // Pre-C++20 [class.friend]p5
10154 // A function can be defined in a friend declaration of a
10155 // class . . . . Such a function is implicitly inline.
10156 // Post C++20 [class.friend]p7
10157 // Such a function is implicitly an inline function if it is attached
10158 // to the global module.
10159 NewFD->setImplicitlyInline();
10160 }
10161
10162 // If this is a method defined in an __interface, and is not a constructor
10163 // or an overloaded operator, then set the pure flag (isVirtual will already
10164 // return true).
10165 if (const CXXRecordDecl *Parent =
10166 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10167 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10168 NewFD->setIsPureVirtual(true);
10169
10170 // C++ [class.union]p2
10171 // A union can have member functions, but not virtual functions.
10172 if (isVirtual && Parent->isUnion()) {
10173 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10174 NewFD->setInvalidDecl();
10175 }
10176 if ((Parent->isClass() || Parent->isStruct()) &&
10177 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10178 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10179 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10180 if (auto *Def = Parent->getDefinition())
10181 Def->setInitMethod(true);
10182 }
10183 }
10184
10185 SetNestedNameSpecifier(*this, NewFD, D);
10186 isMemberSpecialization = false;
10187 isFunctionTemplateSpecialization = false;
10188 if (D.isInvalidType())
10189 NewFD->setInvalidDecl();
10190
10191 // Match up the template parameter lists with the scope specifier, then
10192 // determine whether we have a template or a template specialization.
10193 bool Invalid = false;
10194 TemplateIdAnnotation *TemplateId =
10196 ? D.getName().TemplateId
10197 : nullptr;
10198 TemplateParameterList *TemplateParams =
10201 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10202 isMemberSpecialization, Invalid);
10203 if (TemplateParams) {
10204 // Check that we can declare a template here.
10205 if (CheckTemplateDeclScope(S, TemplateParams))
10206 NewFD->setInvalidDecl();
10207
10208 if (TemplateParams->size() > 0) {
10209 // This is a function template
10210
10211 // A destructor cannot be a template.
10213 Diag(NewFD->getLocation(), diag::err_destructor_template);
10214 NewFD->setInvalidDecl();
10215 // Function template with explicit template arguments.
10216 } else if (TemplateId) {
10217 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10218 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10219 NewFD->setInvalidDecl();
10220 }
10221
10222 // If we're adding a template to a dependent context, we may need to
10223 // rebuilding some of the types used within the template parameter list,
10224 // now that we know what the current instantiation is.
10225 if (DC->isDependentContext()) {
10226 ContextRAII SavedContext(*this, DC);
10228 Invalid = true;
10229 }
10230
10232 NewFD->getLocation(),
10233 Name, TemplateParams,
10234 NewFD);
10235 FunctionTemplate->setLexicalDeclContext(CurContext);
10237
10238 // For source fidelity, store the other template param lists.
10239 if (TemplateParamLists.size() > 1) {
10241 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10242 .drop_back(1));
10243 }
10244 } else {
10245 // This is a function template specialization.
10246 isFunctionTemplateSpecialization = true;
10247 // For source fidelity, store all the template param lists.
10248 if (TemplateParamLists.size() > 0)
10249 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10250
10251 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10252 if (isFriend) {
10253 // We want to remove the "template<>", found here.
10254 SourceRange RemoveRange = TemplateParams->getSourceRange();
10255
10256 // If we remove the template<> and the name is not a
10257 // template-id, we're actually silently creating a problem:
10258 // the friend declaration will refer to an untemplated decl,
10259 // and clearly the user wants a template specialization. So
10260 // we need to insert '<>' after the name.
10261 SourceLocation InsertLoc;
10263 InsertLoc = D.getName().getSourceRange().getEnd();
10264 InsertLoc = getLocForEndOfToken(InsertLoc);
10265 }
10266
10267 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10268 << Name << RemoveRange
10269 << FixItHint::CreateRemoval(RemoveRange)
10270 << FixItHint::CreateInsertion(InsertLoc, "<>");
10271 Invalid = true;
10272
10273 // Recover by faking up an empty template argument list.
10274 HasExplicitTemplateArgs = true;
10275 TemplateArgs.setLAngleLoc(InsertLoc);
10276 TemplateArgs.setRAngleLoc(InsertLoc);
10277 }
10278 }
10279 } else {
10280 // Check that we can declare a template here.
10281 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10282 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10283 NewFD->setInvalidDecl();
10284
10285 // All template param lists were matched against the scope specifier:
10286 // this is NOT (an explicit specialization of) a template.
10287 if (TemplateParamLists.size() > 0)
10288 // For source fidelity, store all the template param lists.
10289 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10290
10291 // "friend void foo<>(int);" is an implicit specialization decl.
10292 if (isFriend && TemplateId)
10293 isFunctionTemplateSpecialization = true;
10294 }
10295
10296 // If this is a function template specialization and the unqualified-id of
10297 // the declarator-id is a template-id, convert the template argument list
10298 // into our AST format and check for unexpanded packs.
10299 if (isFunctionTemplateSpecialization && TemplateId) {
10300 HasExplicitTemplateArgs = true;
10301
10302 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10303 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10304 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10305 TemplateId->NumArgs);
10306 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10307
10308 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10309 // declaration of a function template partial specialization? Should we
10310 // consider the unexpanded pack context to be a partial specialization?
10311 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10313 ArgLoc, isFriend ? UPPC_FriendDeclaration
10315 NewFD->setInvalidDecl();
10316 }
10317 }
10318
10319 if (Invalid) {
10320 NewFD->setInvalidDecl();
10321 if (FunctionTemplate)
10322 FunctionTemplate->setInvalidDecl();
10323 }
10324
10325 // C++ [dcl.fct.spec]p5:
10326 // The virtual specifier shall only be used in declarations of
10327 // nonstatic class member functions that appear within a
10328 // member-specification of a class declaration; see 10.3.
10329 //
10330 if (isVirtual && !NewFD->isInvalidDecl()) {
10331 if (!isVirtualOkay) {
10333 diag::err_virtual_non_function);
10334 } else if (!CurContext->isRecord()) {
10335 // 'virtual' was specified outside of the class.
10337 diag::err_virtual_out_of_class)
10339 } else if (NewFD->getDescribedFunctionTemplate()) {
10340 // C++ [temp.mem]p3:
10341 // A member function template shall not be virtual.
10343 diag::err_virtual_member_function_template)
10345 } else {
10346 // Okay: Add virtual to the method.
10347 NewFD->setVirtualAsWritten(true);
10348 }
10349
10350 if (getLangOpts().CPlusPlus14 &&
10351 NewFD->getReturnType()->isUndeducedType())
10352 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10353 }
10354
10355 // C++ [dcl.fct.spec]p3:
10356 // The inline specifier shall not appear on a block scope function
10357 // declaration.
10358 if (isInline && !NewFD->isInvalidDecl()) {
10359 if (CurContext->isFunctionOrMethod()) {
10360 // 'inline' is not allowed on block scope function declaration.
10362 diag::err_inline_declaration_block_scope) << Name
10364 }
10365 }
10366
10367 // C++ [dcl.fct.spec]p6:
10368 // The explicit specifier shall be used only in the declaration of a
10369 // constructor or conversion function within its class definition;
10370 // see 12.3.1 and 12.3.2.
10371 if (hasExplicit && !NewFD->isInvalidDecl() &&
10373 if (!CurContext->isRecord()) {
10374 // 'explicit' was specified outside of the class.
10376 diag::err_explicit_out_of_class)
10378 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10379 !isa<CXXConversionDecl>(NewFD)) {
10380 // 'explicit' was specified on a function that wasn't a constructor
10381 // or conversion function.
10383 diag::err_explicit_non_ctor_or_conv_function)
10385 }
10386 }
10387
10389 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10390 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10391 // are implicitly inline.
10392 NewFD->setImplicitlyInline();
10393
10394 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10395 // be either constructors or to return a literal type. Therefore,
10396 // destructors cannot be declared constexpr.
10397 if (isa<CXXDestructorDecl>(NewFD) &&
10399 ConstexprKind == ConstexprSpecKind::Consteval)) {
10400 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10401 << static_cast<int>(ConstexprKind);
10405 }
10406 // C++20 [dcl.constexpr]p2: An allocation function, or a
10407 // deallocation function shall not be declared with the consteval
10408 // specifier.
10409 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10412 diag::err_invalid_consteval_decl_kind)
10413 << NewFD;
10415 }
10416 }
10417
10418 // If __module_private__ was specified, mark the function accordingly.
10420 if (isFunctionTemplateSpecialization) {
10421 SourceLocation ModulePrivateLoc
10423 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10424 << 0
10425 << FixItHint::CreateRemoval(ModulePrivateLoc);
10426 } else {
10427 NewFD->setModulePrivate();
10428 if (FunctionTemplate)
10429 FunctionTemplate->setModulePrivate();
10430 }
10431 }
10432
10433 if (isFriend) {
10434 if (FunctionTemplate) {
10435 FunctionTemplate->setObjectOfFriendDecl();
10436 FunctionTemplate->setAccess(AS_public);
10437 }
10438 NewFD->setObjectOfFriendDecl();
10439 NewFD->setAccess(AS_public);
10440 }
10441
10442 // If a function is defined as defaulted or deleted, mark it as such now.
10443 // We'll do the relevant checks on defaulted / deleted functions later.
10444 switch (D.getFunctionDefinitionKind()) {
10447 break;
10448
10450 NewFD->setDefaulted();
10451 break;
10452
10454 NewFD->setDeletedAsWritten();
10455 break;
10456 }
10457
10458 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10460 // Pre C++20 [class.mfct]p2:
10461 // A member function may be defined (8.4) in its class definition, in
10462 // which case it is an inline member function (7.1.2)
10463 // Post C++20 [class.mfct]p1:
10464 // If a member function is attached to the global module and is defined
10465 // in its class definition, it is inline.
10466 NewFD->setImplicitlyInline();
10467 }
10468
10469 if (!isFriend && SC != SC_None) {
10470 // C++ [temp.expl.spec]p2:
10471 // The declaration in an explicit-specialization shall not be an
10472 // export-declaration. An explicit specialization shall not use a
10473 // storage-class-specifier other than thread_local.
10474 //
10475 // We diagnose friend declarations with storage-class-specifiers
10476 // elsewhere.
10477 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10479 diag::ext_explicit_specialization_storage_class)
10482 }
10483
10484 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10485 assert(isa<CXXMethodDecl>(NewFD) &&
10486 "Out-of-line member function should be a CXXMethodDecl");
10487 // C++ [class.static]p1:
10488 // A data or function member of a class may be declared static
10489 // in a class definition, in which case it is a static member of
10490 // the class.
10491
10492 // Complain about the 'static' specifier if it's on an out-of-line
10493 // member function definition.
10494
10495 // MSVC permits the use of a 'static' storage specifier on an
10496 // out-of-line member function template declaration and class member
10497 // template declaration (MSVC versions before 2015), warn about this.
10499 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10500 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10501 (getLangOpts().MSVCCompat &&
10503 ? diag::ext_static_out_of_line
10504 : diag::err_static_out_of_line)
10507 }
10508 }
10509
10510 // C++11 [except.spec]p15:
10511 // A deallocation function with no exception-specification is treated
10512 // as if it were specified with noexcept(true).
10513 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10514 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10515 !FPT->hasExceptionSpec())
10516 NewFD->setType(Context.getFunctionType(
10517 FPT->getReturnType(), FPT->getParamTypes(),
10519
10520 // C++20 [dcl.inline]/7
10521 // If an inline function or variable that is attached to a named module
10522 // is declared in a definition domain, it shall be defined in that
10523 // domain.
10524 // So, if the current declaration does not have a definition, we must
10525 // check at the end of the TU (or when the PMF starts) to see that we
10526 // have a definition at that point.
10527 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10528 NewFD->isInNamedModule()) {
10529 PendingInlineFuncDecls.insert(NewFD);
10530 }
10531 }
10532
10533 // Filter out previous declarations that don't match the scope.
10536 isMemberSpecialization ||
10537 isFunctionTemplateSpecialization);
10538
10539 // Handle GNU asm-label extension (encoded as an attribute).
10540 if (Expr *E = D.getAsmLabel()) {
10541 // The parser guarantees this is a string.
10543 NewFD->addAttr(
10544 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10545 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10546 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
10548 if (I != ExtnameUndeclaredIdentifiers.end()) {
10549 if (isDeclExternC(NewFD)) {
10550 NewFD->addAttr(I->second);
10552 } else
10553 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10554 << /*Variable*/0 << NewFD;
10555 }
10556 }
10557
10558 // Copy the parameter declarations from the declarator D to the function
10559 // declaration NewFD, if they are available. First scavenge them into Params.
10561 unsigned FTIIdx;
10562 if (D.isFunctionDeclarator(FTIIdx)) {
10564
10565 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10566 // function that takes no arguments, not a function that takes a
10567 // single void argument.
10568 // We let through "const void" here because Sema::GetTypeForDeclarator
10569 // already checks for that case.
10570 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10571 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10572 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10573 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10574 Param->setDeclContext(NewFD);
10575 Params.push_back(Param);
10576
10577 if (Param->isInvalidDecl())
10578 NewFD->setInvalidDecl();
10579 }
10580 }
10581
10582 if (!getLangOpts().CPlusPlus) {
10583 // In C, find all the tag declarations from the prototype and move them
10584 // into the function DeclContext. Remove them from the surrounding tag
10585 // injection context of the function, which is typically but not always
10586 // the TU.
10587 DeclContext *PrototypeTagContext =
10589 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10590 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10591
10592 // We don't want to reparent enumerators. Look at their parent enum
10593 // instead.
10594 if (!TD) {
10595 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10596 TD = cast<EnumDecl>(ECD->getDeclContext());
10597 }
10598 if (!TD)
10599 continue;
10600 DeclContext *TagDC = TD->getLexicalDeclContext();
10601 if (!TagDC->containsDecl(TD))
10602 continue;
10603 TagDC->removeDecl(TD);
10604 TD->setDeclContext(NewFD);
10605 NewFD->addDecl(TD);
10606
10607 // Preserve the lexical DeclContext if it is not the surrounding tag
10608 // injection context of the FD. In this example, the semantic context of
10609 // E will be f and the lexical context will be S, while both the
10610 // semantic and lexical contexts of S will be f:
10611 // void f(struct S { enum E { a } f; } s);
10612 if (TagDC != PrototypeTagContext)
10613 TD->setLexicalDeclContext(TagDC);
10614 }
10615 }
10616 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10617 // When we're declaring a function with a typedef, typeof, etc as in the
10618 // following example, we'll need to synthesize (unnamed)
10619 // parameters for use in the declaration.
10620 //
10621 // @code
10622 // typedef void fn(int);
10623 // fn f;
10624 // @endcode
10625
10626 // Synthesize a parameter for each argument type.
10627 for (const auto &AI : FT->param_types()) {
10628 ParmVarDecl *Param =
10630 Param->setScopeInfo(0, Params.size());
10631 Params.push_back(Param);
10632 }
10633 } else {
10634 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10635 "Should not need args for typedef of non-prototype fn");
10636 }
10637
10638 // Finally, we know we have the right number of parameters, install them.
10639 NewFD->setParams(Params);
10640
10641 // If this declarator is a declaration and not a definition, its parameters
10642 // will not be pushed onto a scope chain. That means we will not issue any
10643 // reserved identifier warnings for the declaration, but we will for the
10644 // definition. Handle those here.
10645 if (!D.isFunctionDefinition()) {
10646 for (const ParmVarDecl *PVD : Params)
10648 }
10649
10651 NewFD->addAttr(
10652 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10653
10654 // Functions returning a variably modified type violate C99 6.7.5.2p2
10655 // because all functions have linkage.
10656 if (!NewFD->isInvalidDecl() &&
10658 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10659 NewFD->setInvalidDecl();
10660 }
10661
10662 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10664 !NewFD->hasAttr<SectionAttr>())
10665 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10666 Context, PragmaClangTextSection.SectionName,
10667 PragmaClangTextSection.PragmaLocation));
10668
10669 // Apply an implicit SectionAttr if #pragma code_seg is active.
10670 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10671 !NewFD->hasAttr<SectionAttr>()) {
10672 NewFD->addAttr(SectionAttr::CreateImplicit(
10673 Context, CodeSegStack.CurrentValue->getString(),
10674 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10675 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10678 NewFD))
10679 NewFD->dropAttr<SectionAttr>();
10680 }
10681
10682 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10683 // active.
10684 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10685 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10686 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10687 Context, PragmaClangTextSection.PragmaLocation));
10688
10689 // Apply an implicit CodeSegAttr from class declspec or
10690 // apply an implicit SectionAttr from #pragma code_seg if active.
10691 if (!NewFD->hasAttr<CodeSegAttr>()) {
10693 D.isFunctionDefinition())) {
10694 NewFD->addAttr(SAttr);
10695 }
10696 }
10697
10698 // Handle attributes.
10699 ProcessDeclAttributes(S, NewFD, D);
10700 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10701 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10702 !NewTVA->isDefaultVersion() &&
10703 !Context.getTargetInfo().hasFeature("fmv")) {
10704 // Don't add to scope fmv functions declarations if fmv disabled
10705 AddToScope = false;
10706 return NewFD;
10707 }
10708
10709 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10710 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10711 // type.
10712 //
10713 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10714 // type declaration will generate a compilation error.
10715 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10716 if (AddressSpace != LangAS::Default) {
10717 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10718 NewFD->setInvalidDecl();
10719 }
10720 }
10721
10722 if (!getLangOpts().CPlusPlus) {
10723 // Perform semantic checking on the function declaration.
10724 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10725 CheckMain(NewFD, D.getDeclSpec());
10726
10727 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10728 CheckMSVCRTEntryPoint(NewFD);
10729
10730 if (!NewFD->isInvalidDecl())
10732 isMemberSpecialization,
10734 else if (!Previous.empty())
10735 // Recover gracefully from an invalid redeclaration.
10736 D.setRedeclaration(true);
10737 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10738 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10739 "previous declaration set still overloaded");
10740
10741 // Diagnose no-prototype function declarations with calling conventions that
10742 // don't support variadic calls. Only do this in C and do it after merging
10743 // possibly prototyped redeclarations.
10744 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10746 CallingConv CC = FT->getExtInfo().getCC();
10747 if (!supportsVariadicCall(CC)) {
10748 // Windows system headers sometimes accidentally use stdcall without
10749 // (void) parameters, so we relax this to a warning.
10750 int DiagID =
10751 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10752 Diag(NewFD->getLocation(), DiagID)
10754 }
10755 }
10756
10760 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10762 } else {
10763 // C++11 [replacement.functions]p3:
10764 // The program's definitions shall not be specified as inline.
10765 //
10766 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10767 //
10768 // Suppress the diagnostic if the function is __attribute__((used)), since
10769 // that forces an external definition to be emitted.
10770 if (D.getDeclSpec().isInlineSpecified() &&
10772 !NewFD->hasAttr<UsedAttr>())
10774 diag::ext_operator_new_delete_declared_inline)
10775 << NewFD->getDeclName();
10776
10777 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10778 // C++20 [dcl.decl.general]p4:
10779 // The optional requires-clause in an init-declarator or
10780 // member-declarator shall be present only if the declarator declares a
10781 // templated function.
10782 //
10783 // C++20 [temp.pre]p8:
10784 // An entity is templated if it is
10785 // - a template,
10786 // - an entity defined or created in a templated entity,
10787 // - a member of a templated entity,
10788 // - an enumerator for an enumeration that is a templated entity, or
10789 // - the closure type of a lambda-expression appearing in the
10790 // declaration of a templated entity.
10791 //
10792 // [Note 6: A local class, a local or block variable, or a friend
10793 // function defined in a templated entity is a templated entity.
10794 // — end note]
10795 //
10796 // A templated function is a function template or a function that is
10797 // templated. A templated class is a class template or a class that is
10798 // templated. A templated variable is a variable template or a variable
10799 // that is templated.
10800 if (!FunctionTemplate) {
10801 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10802 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10803 // An explicit specialization shall not have a trailing
10804 // requires-clause unless it declares a function template.
10805 //
10806 // Since a friend function template specialization cannot be
10807 // definition, and since a non-template friend declaration with a
10808 // trailing requires-clause must be a definition, we diagnose
10809 // friend function template specializations with trailing
10810 // requires-clauses on the same path as explicit specializations
10811 // even though they aren't necessarily prohibited by the same
10812 // language rule.
10813 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10814 << isFriend;
10815 } else if (isFriend && NewFD->isTemplated() &&
10816 !D.isFunctionDefinition()) {
10817 // C++ [temp.friend]p9:
10818 // A non-template friend declaration with a requires-clause shall be
10819 // a definition.
10820 Diag(NewFD->getBeginLoc(),
10821 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10822 NewFD->setInvalidDecl();
10823 } else if (!NewFD->isTemplated() ||
10824 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10825 Diag(TRC->getBeginLoc(),
10826 diag::err_constrained_non_templated_function);
10827 }
10828 }
10829 }
10830
10831 // We do not add HD attributes to specializations here because
10832 // they may have different constexpr-ness compared to their
10833 // templates and, after maybeAddHostDeviceAttrs() is applied,
10834 // may end up with different effective targets. Instead, a
10835 // specialization inherits its target attributes from its template
10836 // in the CheckFunctionTemplateSpecialization() call below.
10837 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
10839
10840 // Handle explicit specializations of function templates
10841 // and friend function declarations with an explicit
10842 // template argument list.
10843 if (isFunctionTemplateSpecialization) {
10844 bool isDependentSpecialization = false;
10845 if (isFriend) {
10846 // For friend function specializations, this is a dependent
10847 // specialization if its semantic context is dependent, its
10848 // type is dependent, or if its template-id is dependent.
10849 isDependentSpecialization =
10850 DC->isDependentContext() || NewFD->getType()->isDependentType() ||
10851 (HasExplicitTemplateArgs &&
10852 TemplateSpecializationType::
10853 anyInstantiationDependentTemplateArguments(
10854 TemplateArgs.arguments()));
10855 assert((!isDependentSpecialization ||
10856 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
10857 "dependent friend function specialization without template "
10858 "args");
10859 } else {
10860 // For class-scope explicit specializations of function templates,
10861 // if the lexical context is dependent, then the specialization
10862 // is dependent.
10863 isDependentSpecialization =
10864 CurContext->isRecord() && CurContext->isDependentContext();
10865 }
10866
10867 TemplateArgumentListInfo *ExplicitTemplateArgs =
10868 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
10869 if (isDependentSpecialization) {
10870 // If it's a dependent specialization, it may not be possible
10871 // to determine the primary template (for explicit specializations)
10872 // or befriended declaration (for friends) until the enclosing
10873 // template is instantiated. In such cases, we store the declarations
10874 // found by name lookup and defer resolution until instantiation.
10876 NewFD, ExplicitTemplateArgs, Previous))
10877 NewFD->setInvalidDecl();
10878 } else if (!NewFD->isInvalidDecl()) {
10879 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
10880 Previous))
10881 NewFD->setInvalidDecl();
10882 }
10883 } else if (isMemberSpecialization && !FunctionTemplate) {
10885 NewFD->setInvalidDecl();
10886 }
10887
10888 // Perform semantic checking on the function declaration.
10889 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10890 CheckMain(NewFD, D.getDeclSpec());
10891
10892 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10893 CheckMSVCRTEntryPoint(NewFD);
10894
10895 if (!NewFD->isInvalidDecl())
10897 isMemberSpecialization,
10899 else if (!Previous.empty())
10900 // Recover gracefully from an invalid redeclaration.
10901 D.setRedeclaration(true);
10902
10903 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
10904 !D.isRedeclaration() ||
10905 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10906 "previous declaration set still overloaded");
10907
10908 NamedDecl *PrincipalDecl = (FunctionTemplate
10910 : NewFD);
10911
10912 if (isFriend && NewFD->getPreviousDecl()) {
10913 AccessSpecifier Access = AS_public;
10914 if (!NewFD->isInvalidDecl())
10915 Access = NewFD->getPreviousDecl()->getAccess();
10916
10917 NewFD->setAccess(Access);
10918 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
10919 }
10920
10921 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
10923 PrincipalDecl->setNonMemberOperator();
10924
10925 // If we have a function template, check the template parameter
10926 // list. This will check and merge default template arguments.
10927 if (FunctionTemplate) {
10928 FunctionTemplateDecl *PrevTemplate =
10929 FunctionTemplate->getPreviousDecl();
10930 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
10931 PrevTemplate ? PrevTemplate->getTemplateParameters()
10932 : nullptr,
10937 : (D.getCXXScopeSpec().isSet() &&
10938 DC && DC->isRecord() &&
10939 DC->isDependentContext())
10942 }
10943
10944 if (NewFD->isInvalidDecl()) {
10945 // Ignore all the rest of this.
10946 } else if (!D.isRedeclaration()) {
10947 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
10948 AddToScope };
10949 // Fake up an access specifier if it's supposed to be a class member.
10950 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
10951 NewFD->setAccess(AS_public);
10952
10953 // Qualified decls generally require a previous declaration.
10954 if (D.getCXXScopeSpec().isSet()) {
10955 // ...with the major exception of templated-scope or
10956 // dependent-scope friend declarations.
10957
10958 // TODO: we currently also suppress this check in dependent
10959 // contexts because (1) the parameter depth will be off when
10960 // matching friend templates and (2) we might actually be
10961 // selecting a friend based on a dependent factor. But there
10962 // are situations where these conditions don't apply and we
10963 // can actually do this check immediately.
10964 //
10965 // Unless the scope is dependent, it's always an error if qualified
10966 // redeclaration lookup found nothing at all. Diagnose that now;
10967 // nothing will diagnose that error later.
10968 if (isFriend &&
10970 (!Previous.empty() && CurContext->isDependentContext()))) {
10971 // ignore these
10972 } else if (NewFD->isCPUDispatchMultiVersion() ||
10973 NewFD->isCPUSpecificMultiVersion()) {
10974 // ignore this, we allow the redeclaration behavior here to create new
10975 // versions of the function.
10976 } else {
10977 // The user tried to provide an out-of-line definition for a
10978 // function that is a member of a class or namespace, but there
10979 // was no such member function declared (C++ [class.mfct]p2,
10980 // C++ [namespace.memdef]p2). For example:
10981 //
10982 // class X {
10983 // void f() const;
10984 // };
10985 //
10986 // void X::f() { } // ill-formed
10987 //
10988 // Complain about this problem, and attempt to suggest close
10989 // matches (e.g., those that differ only in cv-qualifiers and
10990 // whether the parameter types are references).
10991
10993 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10994 AddToScope = ExtraArgs.AddToScope;
10995 return Result;
10996 }
10997 }
10998
10999 // Unqualified local friend declarations are required to resolve
11000 // to something.
11001 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
11003 *this, Previous, NewFD, ExtraArgs, true, S)) {
11004 AddToScope = ExtraArgs.AddToScope;
11005 return Result;
11006 }
11007 }
11008 } else if (!D.isFunctionDefinition() &&
11009 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
11010 !isFriend && !isFunctionTemplateSpecialization &&
11011 !isMemberSpecialization) {
11012 // An out-of-line member function declaration must also be a
11013 // definition (C++ [class.mfct]p2).
11014 // Note that this is not the case for explicit specializations of
11015 // function templates or member functions of class templates, per
11016 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11017 // extension for compatibility with old SWIG code which likes to
11018 // generate them.
11019 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
11020 << D.getCXXScopeSpec().getRange();
11021 }
11022 }
11023
11024 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11025 // Any top level function could potentially be specified as an entry.
11026 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11027 HLSL().ActOnTopLevelFunction(NewFD);
11028
11029 if (NewFD->hasAttr<HLSLShaderAttr>())
11030 HLSL().CheckEntryPoint(NewFD);
11031 }
11032
11033 // If this is the first declaration of a library builtin function, add
11034 // attributes as appropriate.
11035 if (!D.isRedeclaration()) {
11036 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11037 if (unsigned BuiltinID = II->getBuiltinID()) {
11038 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
11039 if (!InStdNamespace &&
11041 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11042 // Validate the type matches unless this builtin is specified as
11043 // matching regardless of its declared type.
11044 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
11045 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11046 } else {
11048 LookupNecessaryTypesForBuiltin(S, BuiltinID);
11049 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
11050
11051 if (!Error && !BuiltinType.isNull() &&
11052 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11053 NewFD->getType(), BuiltinType))
11054 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11055 }
11056 }
11057 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11058 isStdBuiltin(Context, NewFD, BuiltinID)) {
11059 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11060 }
11061 }
11062 }
11063 }
11064
11065 ProcessPragmaWeak(S, NewFD);
11066 ProcessPragmaExport(NewFD);
11067 checkAttributesAfterMerging(*this, *NewFD);
11068
11070
11071 if (NewFD->hasAttr<OverloadableAttr>() &&
11072 !NewFD->getType()->getAs<FunctionProtoType>()) {
11073 Diag(NewFD->getLocation(),
11074 diag::err_attribute_overloadable_no_prototype)
11075 << NewFD;
11076 NewFD->dropAttr<OverloadableAttr>();
11077 }
11078
11079 // If there's a #pragma GCC visibility in scope, and this isn't a class
11080 // member, set the visibility of this function.
11081 if (!DC->isRecord() && NewFD->isExternallyVisible())
11083
11084 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11085 // marking the function.
11086 ObjC().AddCFAuditedAttribute(NewFD);
11087
11088 // If this is a function definition, check if we have to apply any
11089 // attributes (i.e. optnone and no_builtin) due to a pragma.
11090 if (D.isFunctionDefinition()) {
11091 AddRangeBasedOptnone(NewFD);
11093 AddSectionMSAllocText(NewFD);
11095 }
11096
11097 // If this is the first declaration of an extern C variable, update
11098 // the map of such variables.
11099 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11100 isIncompleteDeclExternC(*this, NewFD))
11102
11103 // Set this FunctionDecl's range up to the right paren.
11104 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11105
11106 if (D.isRedeclaration() && !Previous.empty()) {
11107 NamedDecl *Prev = Previous.getRepresentativeDecl();
11108 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11109 isMemberSpecialization ||
11110 isFunctionTemplateSpecialization,
11112 }
11113
11114 if (getLangOpts().CUDA) {
11115 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11116 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11118 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11119 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11121 Context.setcudaConfigureCallDecl(NewFD);
11122 }
11123 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11124 !NewFD->isInvalidDecl() &&
11126 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11127 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11129 Context.setcudaGetParameterBufferDecl(NewFD);
11130 }
11131 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11132 !NewFD->isInvalidDecl() &&
11134 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11135 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11137 Context.setcudaLaunchDeviceDecl(NewFD);
11138 }
11139 }
11140 }
11141
11143
11144 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11145 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11146 if (SC == SC_Static) {
11147 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11148 D.setInvalidType();
11149 }
11150
11151 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11152 if (!NewFD->getReturnType()->isVoidType()) {
11153 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11154 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11155 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11156 : FixItHint());
11157 D.setInvalidType();
11158 }
11159
11161 for (auto *Param : NewFD->parameters())
11162 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11163
11164 if (getLangOpts().OpenCLCPlusPlus) {
11165 if (DC->isRecord()) {
11166 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11167 D.setInvalidType();
11168 }
11169 if (FunctionTemplate) {
11170 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11171 D.setInvalidType();
11172 }
11173 }
11174 }
11175
11176 if (getLangOpts().CPlusPlus) {
11177 // Precalculate whether this is a friend function template with a constraint
11178 // that depends on an enclosing template, per [temp.friend]p9.
11179 if (isFriend && FunctionTemplate &&
11182
11183 // C++ [temp.friend]p9:
11184 // A friend function template with a constraint that depends on a
11185 // template parameter from an enclosing template shall be a definition.
11186 if (!D.isFunctionDefinition()) {
11187 Diag(NewFD->getBeginLoc(),
11188 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11189 NewFD->setInvalidDecl();
11190 }
11191 }
11192
11193 if (FunctionTemplate) {
11194 if (NewFD->isInvalidDecl())
11195 FunctionTemplate->setInvalidDecl();
11196 return FunctionTemplate;
11197 }
11198
11199 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11201 }
11202
11203 for (const ParmVarDecl *Param : NewFD->parameters()) {
11204 QualType PT = Param->getType();
11205
11206 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11207 // types.
11208 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11209 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11210 QualType ElemTy = PipeTy->getElementType();
11211 if (ElemTy->isPointerOrReferenceType()) {
11212 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11213 D.setInvalidType();
11214 }
11215 }
11216 }
11217 // WebAssembly tables can't be used as function parameters.
11218 if (Context.getTargetInfo().getTriple().isWasm()) {
11220 Diag(Param->getTypeSpecStartLoc(),
11221 diag::err_wasm_table_as_function_parameter);
11222 D.setInvalidType();
11223 }
11224 }
11225 }
11226
11227 // Diagnose availability attributes. Availability cannot be used on functions
11228 // that are run during load/unload.
11229 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11230 if (NewFD->hasAttr<ConstructorAttr>()) {
11231 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11232 << 1;
11233 NewFD->dropAttr<AvailabilityAttr>();
11234 }
11235 if (NewFD->hasAttr<DestructorAttr>()) {
11236 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11237 << 2;
11238 NewFD->dropAttr<AvailabilityAttr>();
11239 }
11240 }
11241
11242 // Diagnose no_builtin attribute on function declaration that are not a
11243 // definition.
11244 // FIXME: We should really be doing this in
11245 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11246 // the FunctionDecl and at this point of the code
11247 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11248 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11249 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11250 switch (D.getFunctionDefinitionKind()) {
11253 Diag(NBA->getLocation(),
11254 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11255 << NBA->getSpelling();
11256 break;
11258 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11259 << NBA->getSpelling();
11260 break;
11262 break;
11263 }
11264
11265 // Similar to no_builtin logic above, at this point of the code
11266 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11267 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11268 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11269 !NewFD->isInvalidDecl() &&
11271 ExternalDeclarations.push_back(NewFD);
11272
11273 // Used for a warning on the 'next' declaration when used with a
11274 // `routine(name)`.
11275 if (getLangOpts().OpenACC)
11277
11278 return NewFD;
11279}
11280
11281/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11282/// when __declspec(code_seg) "is applied to a class, all member functions of
11283/// the class and nested classes -- this includes compiler-generated special
11284/// member functions -- are put in the specified segment."
11285/// The actual behavior is a little more complicated. The Microsoft compiler
11286/// won't check outer classes if there is an active value from #pragma code_seg.
11287/// The CodeSeg is always applied from the direct parent but only from outer
11288/// classes when the #pragma code_seg stack is empty. See:
11289/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11290/// available since MS has removed the page.
11292 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11293 if (!Method)
11294 return nullptr;
11295 const CXXRecordDecl *Parent = Method->getParent();
11296 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11297 Attr *NewAttr = SAttr->clone(S.getASTContext());
11298 NewAttr->setImplicit(true);
11299 return NewAttr;
11300 }
11301
11302 // The Microsoft compiler won't check outer classes for the CodeSeg
11303 // when the #pragma code_seg stack is active.
11304 if (S.CodeSegStack.CurrentValue)
11305 return nullptr;
11306
11307 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11308 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11309 Attr *NewAttr = SAttr->clone(S.getASTContext());
11310 NewAttr->setImplicit(true);
11311 return NewAttr;
11312 }
11313 }
11314 return nullptr;
11315}
11316
11318 bool IsDefinition) {
11319 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11320 return A;
11321 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11322 CodeSegStack.CurrentValue)
11323 return SectionAttr::CreateImplicit(
11324 getASTContext(), CodeSegStack.CurrentValue->getString(),
11325 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11326 return nullptr;
11327}
11328
11330 QualType NewT, QualType OldT) {
11332 return true;
11333
11334 // For dependently-typed local extern declarations and friends, we can't
11335 // perform a correct type check in general until instantiation:
11336 //
11337 // int f();
11338 // template<typename T> void g() { T f(); }
11339 //
11340 // (valid if g() is only instantiated with T = int).
11341 if (NewT->isDependentType() &&
11342 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11343 return false;
11344
11345 // Similarly, if the previous declaration was a dependent local extern
11346 // declaration, we don't really know its type yet.
11347 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11348 return false;
11349
11350 return true;
11351}
11352
11355 return true;
11356
11357 // Don't chain dependent friend function definitions until instantiation, to
11358 // permit cases like
11359 //
11360 // void func();
11361 // template<typename T> class C1 { friend void func() {} };
11362 // template<typename T> class C2 { friend void func() {} };
11363 //
11364 // ... which is valid if only one of C1 and C2 is ever instantiated.
11365 //
11366 // FIXME: This need only apply to function definitions. For now, we proxy
11367 // this by checking for a file-scope function. We do not want this to apply
11368 // to friend declarations nominating member functions, because that gets in
11369 // the way of access checks.
11371 return false;
11372
11373 auto *VD = dyn_cast<ValueDecl>(D);
11374 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11375 return !VD || !PrevVD ||
11376 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11377 PrevVD->getType());
11378}
11379
11380/// Check the target or target_version attribute of the function for
11381/// MultiVersion validity.
11382///
11383/// Returns true if there was an error, false otherwise.
11384static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11385 const auto *TA = FD->getAttr<TargetAttr>();
11386 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11387
11388 assert((TA || TVA) && "Expecting target or target_version attribute");
11389
11391 enum ErrType { Feature = 0, Architecture = 1 };
11392
11393 if (TA) {
11394 ParsedTargetAttr ParseInfo =
11395 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11396 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11397 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11398 << Architecture << ParseInfo.CPU;
11399 return true;
11400 }
11401 for (const auto &Feat : ParseInfo.Features) {
11402 auto BareFeat = StringRef{Feat}.substr(1);
11403 if (Feat[0] == '-') {
11404 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11405 << Feature << ("no-" + BareFeat).str();
11406 return true;
11407 }
11408
11409 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11410 !TargetInfo.isValidFeatureName(BareFeat) ||
11411 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11412 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11413 << Feature << BareFeat;
11414 return true;
11415 }
11416 }
11417 }
11418
11419 if (TVA) {
11421 ParsedTargetAttr ParseInfo;
11422 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11423 ParseInfo =
11424 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11425 for (auto &Feat : ParseInfo.Features)
11426 Feats.push_back(StringRef{Feat}.substr(1));
11427 } else {
11428 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11429 TVA->getFeatures(Feats);
11430 }
11431 for (const auto &Feat : Feats) {
11432 if (!TargetInfo.validateCpuSupports(Feat)) {
11433 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11434 << Feature << Feat;
11435 return true;
11436 }
11437 }
11438 }
11439 return false;
11440}
11441
11442// Provide a white-list of attributes that are allowed to be combined with
11443// multiversion functions.
11445 MultiVersionKind MVKind) {
11446 // Note: this list/diagnosis must match the list in
11447 // checkMultiversionAttributesAllSame.
11448 switch (Kind) {
11449 default:
11450 return false;
11451 case attr::ArmLocallyStreaming:
11452 return MVKind == MultiVersionKind::TargetVersion ||
11454 case attr::Used:
11455 return MVKind == MultiVersionKind::Target;
11456 case attr::NonNull:
11457 case attr::NoThrow:
11458 return true;
11459 }
11460}
11461
11463 const FunctionDecl *FD,
11464 const FunctionDecl *CausedFD,
11465 MultiVersionKind MVKind) {
11466 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11467 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11468 << static_cast<unsigned>(MVKind) << A;
11469 if (CausedFD)
11470 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11471 return true;
11472 };
11473
11474 for (const Attr *A : FD->attrs()) {
11475 switch (A->getKind()) {
11476 case attr::CPUDispatch:
11477 case attr::CPUSpecific:
11478 if (MVKind != MultiVersionKind::CPUDispatch &&
11480 return Diagnose(S, A);
11481 break;
11482 case attr::Target:
11483 if (MVKind != MultiVersionKind::Target)
11484 return Diagnose(S, A);
11485 break;
11486 case attr::TargetVersion:
11487 if (MVKind != MultiVersionKind::TargetVersion &&
11489 return Diagnose(S, A);
11490 break;
11491 case attr::TargetClones:
11492 if (MVKind != MultiVersionKind::TargetClones &&
11494 return Diagnose(S, A);
11495 break;
11496 default:
11497 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11498 return Diagnose(S, A);
11499 break;
11500 }
11501 }
11502 return false;
11503}
11504
11506 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11507 const PartialDiagnostic &NoProtoDiagID,
11508 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11509 const PartialDiagnosticAt &NoSupportDiagIDAt,
11510 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11511 bool ConstexprSupported, bool CLinkageMayDiffer) {
11512 enum DoesntSupport {
11513 FuncTemplates = 0,
11514 VirtFuncs = 1,
11515 DeducedReturn = 2,
11516 Constructors = 3,
11517 Destructors = 4,
11518 DeletedFuncs = 5,
11519 DefaultedFuncs = 6,
11520 ConstexprFuncs = 7,
11521 ConstevalFuncs = 8,
11522 Lambda = 9,
11523 };
11524 enum Different {
11525 CallingConv = 0,
11526 ReturnType = 1,
11527 ConstexprSpec = 2,
11528 InlineSpec = 3,
11529 Linkage = 4,
11530 LanguageLinkage = 5,
11531 };
11532
11533 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11534 !OldFD->getType()->getAs<FunctionProtoType>()) {
11535 Diag(OldFD->getLocation(), NoProtoDiagID);
11536 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11537 return true;
11538 }
11539
11540 if (NoProtoDiagID.getDiagID() != 0 &&
11541 !NewFD->getType()->getAs<FunctionProtoType>())
11542 return Diag(NewFD->getLocation(), NoProtoDiagID);
11543
11544 if (!TemplatesSupported &&
11546 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11547 << FuncTemplates;
11548
11549 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11550 if (NewCXXFD->isVirtual())
11551 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11552 << VirtFuncs;
11553
11554 if (isa<CXXConstructorDecl>(NewCXXFD))
11555 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11556 << Constructors;
11557
11558 if (isa<CXXDestructorDecl>(NewCXXFD))
11559 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11560 << Destructors;
11561 }
11562
11563 if (NewFD->isDeleted())
11564 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11565 << DeletedFuncs;
11566
11567 if (NewFD->isDefaulted())
11568 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11569 << DefaultedFuncs;
11570
11571 if (!ConstexprSupported && NewFD->isConstexpr())
11572 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11573 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11574
11575 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11576 const auto *NewType = cast<FunctionType>(NewQType);
11577 QualType NewReturnType = NewType->getReturnType();
11578
11579 if (NewReturnType->isUndeducedType())
11580 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11581 << DeducedReturn;
11582
11583 // Ensure the return type is identical.
11584 if (OldFD) {
11585 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11586 const auto *OldType = cast<FunctionType>(OldQType);
11587 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11588 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11589
11590 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11591 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11592
11593 bool ArmStreamingCCMismatched = false;
11594 if (OldFPT && NewFPT) {
11595 unsigned Diff =
11596 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11597 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11598 // cannot be mixed.
11601 ArmStreamingCCMismatched = true;
11602 }
11603
11604 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11605 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11606
11607 QualType OldReturnType = OldType->getReturnType();
11608
11609 if (OldReturnType != NewReturnType)
11610 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11611
11612 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11613 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11614
11615 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11616 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11617
11618 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11619 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11620
11621 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11622 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11623
11624 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11625 NewFD->getLocation()))
11626 return true;
11627 }
11628 return false;
11629}
11630
11632 const FunctionDecl *NewFD,
11633 bool CausesMV,
11634 MultiVersionKind MVKind) {
11636 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11637 if (OldFD)
11638 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11639 return true;
11640 }
11641
11642 bool IsCPUSpecificCPUDispatchMVKind =
11645
11646 if (CausesMV && OldFD &&
11647 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11648 return true;
11649
11650 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11651 return true;
11652
11653 // Only allow transition to MultiVersion if it hasn't been used.
11654 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11655 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11656 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11657 return true;
11658 }
11659
11661 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11663 S.PDiag(diag::note_multiversioning_caused_here)),
11665 S.PDiag(diag::err_multiversion_doesnt_support)
11666 << static_cast<unsigned>(MVKind)),
11668 S.PDiag(diag::err_multiversion_diff)),
11669 /*TemplatesSupported=*/false,
11670 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11671 /*CLinkageMayDiffer=*/false);
11672}
11673
11674/// Check the validity of a multiversion function declaration that is the
11675/// first of its kind. Also sets the multiversion'ness' of the function itself.
11676///
11677/// This sets NewFD->isInvalidDecl() to true if there was an error.
11678///
11679/// Returns true if there was an error, false otherwise.
11682 assert(MVKind != MultiVersionKind::None &&
11683 "Function lacks multiversion attribute");
11684 const auto *TA = FD->getAttr<TargetAttr>();
11685 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11686 // The target attribute only causes MV if this declaration is the default,
11687 // otherwise it is treated as a normal function.
11688 if (TA && !TA->isDefaultVersion())
11689 return false;
11690
11691 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11692 FD->setInvalidDecl();
11693 return true;
11694 }
11695
11696 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11697 FD->setInvalidDecl();
11698 return true;
11699 }
11700
11701 FD->setIsMultiVersion();
11702 return false;
11703}
11704
11706 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11708 return true;
11709 }
11710
11711 return false;
11712}
11713
11715 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11716 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11717 return;
11718
11719 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11720 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11721
11722 if (MVKindTo == MultiVersionKind::None &&
11723 (MVKindFrom == MultiVersionKind::TargetVersion ||
11724 MVKindFrom == MultiVersionKind::TargetClones))
11725 To->addAttr(TargetVersionAttr::CreateImplicit(
11726 To->getASTContext(), "default", To->getSourceRange()));
11727}
11728
11730 FunctionDecl *NewFD,
11731 bool &Redeclaration,
11732 NamedDecl *&OldDecl,
11734 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11735
11736 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11737 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11738 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11739 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11740
11741 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11742
11743 // The definitions should be allowed in any order. If we have discovered
11744 // a new target version and the preceeding was the default, then add the
11745 // corresponding attribute to it.
11746 patchDefaultTargetVersion(NewFD, OldFD);
11747
11748 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11749 // to change, this is a simple redeclaration.
11750 if (NewTA && !NewTA->isDefaultVersion() &&
11751 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11752 return false;
11753
11754 // Otherwise, this decl causes MultiVersioning.
11755 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11758 NewFD->setInvalidDecl();
11759 return true;
11760 }
11761
11762 if (CheckMultiVersionValue(S, NewFD)) {
11763 NewFD->setInvalidDecl();
11764 return true;
11765 }
11766
11767 // If this is 'default', permit the forward declaration.
11768 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11769 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11770 Redeclaration = true;
11771 OldDecl = OldFD;
11772 OldFD->setIsMultiVersion();
11773 NewFD->setIsMultiVersion();
11774 return false;
11775 }
11776
11777 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11778 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11779 NewFD->setInvalidDecl();
11780 return true;
11781 }
11782
11783 if (NewTA) {
11784 ParsedTargetAttr OldParsed =
11786 OldTA->getFeaturesStr());
11787 llvm::sort(OldParsed.Features);
11788 ParsedTargetAttr NewParsed =
11790 NewTA->getFeaturesStr());
11791 // Sort order doesn't matter, it just needs to be consistent.
11792 llvm::sort(NewParsed.Features);
11793 if (OldParsed == NewParsed) {
11794 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11795 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11796 NewFD->setInvalidDecl();
11797 return true;
11798 }
11799 }
11800
11801 for (const auto *FD : OldFD->redecls()) {
11802 const auto *CurTA = FD->getAttr<TargetAttr>();
11803 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11804 // We allow forward declarations before ANY multiversioning attributes, but
11805 // nothing after the fact.
11807 ((NewTA && (!CurTA || CurTA->isInherited())) ||
11808 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
11809 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
11810 << (NewTA ? 0 : 2);
11811 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11812 NewFD->setInvalidDecl();
11813 return true;
11814 }
11815 }
11816
11817 OldFD->setIsMultiVersion();
11818 NewFD->setIsMultiVersion();
11819 Redeclaration = false;
11820 OldDecl = nullptr;
11821 Previous.clear();
11822 return false;
11823}
11824
11826 MultiVersionKind OldKind = Old->getMultiVersionKind();
11827 MultiVersionKind NewKind = New->getMultiVersionKind();
11828
11829 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
11830 NewKind == MultiVersionKind::None)
11831 return true;
11832
11833 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
11834 switch (OldKind) {
11836 return NewKind == MultiVersionKind::TargetClones;
11838 return NewKind == MultiVersionKind::TargetVersion;
11839 default:
11840 return false;
11841 }
11842 } else {
11843 switch (OldKind) {
11845 return NewKind == MultiVersionKind::CPUSpecific;
11847 return NewKind == MultiVersionKind::CPUDispatch;
11848 default:
11849 return false;
11850 }
11851 }
11852}
11853
11854/// Check the validity of a new function declaration being added to an existing
11855/// multiversioned declaration collection.
11857 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
11858 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
11859 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
11861
11862 // Disallow mixing of multiversioning types.
11863 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
11864 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
11865 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11866 NewFD->setInvalidDecl();
11867 return true;
11868 }
11869
11870 // Add the default target_version attribute if it's missing.
11871 patchDefaultTargetVersion(OldFD, NewFD);
11872 patchDefaultTargetVersion(NewFD, OldFD);
11873
11874 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11875 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11876 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
11877 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
11878
11879 ParsedTargetAttr NewParsed;
11880 if (NewTA) {
11882 NewTA->getFeaturesStr());
11883 llvm::sort(NewParsed.Features);
11884 }
11886 if (NewTVA) {
11887 NewTVA->getFeatures(NewFeats);
11888 llvm::sort(NewFeats);
11889 }
11890
11891 bool UseMemberUsingDeclRules =
11892 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
11893
11894 bool MayNeedOverloadableChecks =
11896
11897 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
11898 // of a previous member of the MultiVersion set.
11899 for (NamedDecl *ND : Previous) {
11900 FunctionDecl *CurFD = ND->getAsFunction();
11901 if (!CurFD || CurFD->isInvalidDecl())
11902 continue;
11903 if (MayNeedOverloadableChecks &&
11904 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
11905 continue;
11906
11907 switch (NewMVKind) {
11909 assert(OldMVKind == MultiVersionKind::TargetClones &&
11910 "Only target_clones can be omitted in subsequent declarations");
11911 break;
11913 const auto *CurTA = CurFD->getAttr<TargetAttr>();
11914 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
11915 NewFD->setIsMultiVersion();
11916 Redeclaration = true;
11917 OldDecl = ND;
11918 return false;
11919 }
11920
11921 ParsedTargetAttr CurParsed =
11923 CurTA->getFeaturesStr());
11924 llvm::sort(CurParsed.Features);
11925 if (CurParsed == NewParsed) {
11926 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11927 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11928 NewFD->setInvalidDecl();
11929 return true;
11930 }
11931 break;
11932 }
11934 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11935 if (CurTVA->getName() == NewTVA->getName()) {
11936 NewFD->setIsMultiVersion();
11937 Redeclaration = true;
11938 OldDecl = ND;
11939 return false;
11940 }
11942 CurTVA->getFeatures(CurFeats);
11943 llvm::sort(CurFeats);
11944
11945 if (CurFeats == NewFeats) {
11946 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11947 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11948 NewFD->setInvalidDecl();
11949 return true;
11950 }
11951 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11952 // Default
11953 if (NewFeats.empty())
11954 break;
11955
11956 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
11958 CurClones->getFeatures(CurFeats, I);
11959 llvm::sort(CurFeats);
11960
11961 if (CurFeats == NewFeats) {
11962 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11963 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11964 NewFD->setInvalidDecl();
11965 return true;
11966 }
11967 }
11968 }
11969 break;
11970 }
11972 assert(NewClones && "MultiVersionKind does not match attribute type");
11973 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
11974 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
11975 !std::equal(CurClones->featuresStrs_begin(),
11976 CurClones->featuresStrs_end(),
11977 NewClones->featuresStrs_begin())) {
11978 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
11979 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
11980 NewFD->setInvalidDecl();
11981 return true;
11982 }
11983 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
11985 CurTVA->getFeatures(CurFeats);
11986 llvm::sort(CurFeats);
11987
11988 // Default
11989 if (CurFeats.empty())
11990 break;
11991
11992 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
11993 NewFeats.clear();
11994 NewClones->getFeatures(NewFeats, I);
11995 llvm::sort(NewFeats);
11996
11997 if (CurFeats == NewFeats) {
11998 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11999 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12000 NewFD->setInvalidDecl();
12001 return true;
12002 }
12003 }
12004 break;
12005 }
12006 Redeclaration = true;
12007 OldDecl = CurFD;
12008 NewFD->setIsMultiVersion();
12009 return false;
12010 }
12013 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12014 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12015 // Handle CPUDispatch/CPUSpecific versions.
12016 // Only 1 CPUDispatch function is allowed, this will make it go through
12017 // the redeclaration errors.
12018 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12019 CurFD->hasAttr<CPUDispatchAttr>()) {
12020 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12021 std::equal(
12022 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
12023 NewCPUDisp->cpus_begin(),
12024 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12025 return Cur->getName() == New->getName();
12026 })) {
12027 NewFD->setIsMultiVersion();
12028 Redeclaration = true;
12029 OldDecl = ND;
12030 return false;
12031 }
12032
12033 // If the declarations don't match, this is an error condition.
12034 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
12035 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12036 NewFD->setInvalidDecl();
12037 return true;
12038 }
12039 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12040 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12041 std::equal(
12042 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
12043 NewCPUSpec->cpus_begin(),
12044 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12045 return Cur->getName() == New->getName();
12046 })) {
12047 NewFD->setIsMultiVersion();
12048 Redeclaration = true;
12049 OldDecl = ND;
12050 return false;
12051 }
12052
12053 // Only 1 version of CPUSpecific is allowed for each CPU.
12054 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12055 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12056 if (CurII == NewII) {
12057 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12058 << NewII;
12059 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12060 NewFD->setInvalidDecl();
12061 return true;
12062 }
12063 }
12064 }
12065 }
12066 break;
12067 }
12068 }
12069 }
12070
12071 // Redeclarations of a target_clones function may omit the attribute, in which
12072 // case it will be inherited during declaration merging.
12073 if (NewMVKind == MultiVersionKind::None &&
12074 OldMVKind == MultiVersionKind::TargetClones) {
12075 NewFD->setIsMultiVersion();
12076 Redeclaration = true;
12077 OldDecl = OldFD;
12078 return false;
12079 }
12080
12081 // Else, this is simply a non-redecl case. Checking the 'value' is only
12082 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12083 // handled in the attribute adding step.
12084 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12085 NewFD->setInvalidDecl();
12086 return true;
12087 }
12088
12089 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12090 !OldFD->isMultiVersion(), NewMVKind)) {
12091 NewFD->setInvalidDecl();
12092 return true;
12093 }
12094
12095 // Permit forward declarations in the case where these two are compatible.
12096 if (!OldFD->isMultiVersion()) {
12097 OldFD->setIsMultiVersion();
12098 NewFD->setIsMultiVersion();
12099 Redeclaration = true;
12100 OldDecl = OldFD;
12101 return false;
12102 }
12103
12104 NewFD->setIsMultiVersion();
12105 Redeclaration = false;
12106 OldDecl = nullptr;
12107 Previous.clear();
12108 return false;
12109}
12110
12111/// Check the validity of a mulitversion function declaration.
12112/// Also sets the multiversion'ness' of the function itself.
12113///
12114/// This sets NewFD->isInvalidDecl() to true if there was an error.
12115///
12116/// Returns true if there was an error, false otherwise.
12118 bool &Redeclaration, NamedDecl *&OldDecl,
12120 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12121
12122 // Check if FMV is disabled.
12123 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12124 return false;
12125
12126 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12127 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12128 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12129 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12130 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12131 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12132
12133 // Main isn't allowed to become a multiversion function, however it IS
12134 // permitted to have 'main' be marked with the 'target' optimization hint,
12135 // for 'target_version' only default is allowed.
12136 if (NewFD->isMain()) {
12137 if (MVKind != MultiVersionKind::None &&
12138 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12139 !(MVKind == MultiVersionKind::TargetVersion &&
12140 NewTVA->isDefaultVersion())) {
12141 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12142 NewFD->setInvalidDecl();
12143 return true;
12144 }
12145 return false;
12146 }
12147
12148 // Target attribute on AArch64 is not used for multiversioning
12149 if (NewTA && TI.getTriple().isAArch64())
12150 return false;
12151
12152 // Target attribute on RISCV is not used for multiversioning
12153 if (NewTA && TI.getTriple().isRISCV())
12154 return false;
12155
12156 if (!OldDecl || !OldDecl->getAsFunction() ||
12157 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12158 NewFD->getDeclContext()->getRedeclContext())) {
12159 // If there's no previous declaration, AND this isn't attempting to cause
12160 // multiversioning, this isn't an error condition.
12161 if (MVKind == MultiVersionKind::None)
12162 return false;
12163 return CheckMultiVersionFirstFunction(S, NewFD);
12164 }
12165
12166 FunctionDecl *OldFD = OldDecl->getAsFunction();
12167
12168 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12169 return false;
12170
12171 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12172 // for target_clones and target_version.
12173 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12176 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12178 NewFD->setInvalidDecl();
12179 return true;
12180 }
12181
12182 if (!OldFD->isMultiVersion()) {
12183 switch (MVKind) {
12187 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12189 if (OldFD->isUsed(false)) {
12190 NewFD->setInvalidDecl();
12191 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12192 }
12193 OldFD->setIsMultiVersion();
12194 break;
12195
12199 break;
12200 }
12201 }
12202
12203 // At this point, we have a multiversion function decl (in OldFD) AND an
12204 // appropriate attribute in the current function decl (unless it's allowed to
12205 // omit the attribute). Resolve that these are still compatible with previous
12206 // declarations.
12207 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12208 NewCPUSpec, NewClones, Redeclaration,
12209 OldDecl, Previous);
12210}
12211
12213 bool IsPure = NewFD->hasAttr<PureAttr>();
12214 bool IsConst = NewFD->hasAttr<ConstAttr>();
12215
12216 // If there are no pure or const attributes, there's nothing to check.
12217 if (!IsPure && !IsConst)
12218 return;
12219
12220 // If the function is marked both pure and const, we retain the const
12221 // attribute because it makes stronger guarantees than the pure attribute, and
12222 // we drop the pure attribute explicitly to prevent later confusion about
12223 // semantics.
12224 if (IsPure && IsConst) {
12225 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12226 NewFD->dropAttrs<PureAttr>();
12227 }
12228
12229 // Constructors and destructors are functions which return void, so are
12230 // handled here as well.
12231 if (NewFD->getReturnType()->isVoidType()) {
12232 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12233 << IsConst;
12234 NewFD->dropAttrs<PureAttr, ConstAttr>();
12235 }
12236}
12237
12240 bool IsMemberSpecialization,
12241 bool DeclIsDefn) {
12242 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12243 "Variably modified return types are not handled here");
12244
12245 // Determine whether the type of this function should be merged with
12246 // a previous visible declaration. This never happens for functions in C++,
12247 // and always happens in C if the previous declaration was visible.
12248 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12249 !Previous.isShadowed();
12250
12251 bool Redeclaration = false;
12252 NamedDecl *OldDecl = nullptr;
12253 bool MayNeedOverloadableChecks = false;
12254
12256 // Merge or overload the declaration with an existing declaration of
12257 // the same name, if appropriate.
12258 if (!Previous.empty()) {
12259 // Determine whether NewFD is an overload of PrevDecl or
12260 // a declaration that requires merging. If it's an overload,
12261 // there's no more work to do here; we'll just add the new
12262 // function to the scope.
12264 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12265 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12266 Redeclaration = true;
12267 OldDecl = Candidate;
12268 }
12269 } else {
12270 MayNeedOverloadableChecks = true;
12271 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12272 /*NewIsUsingDecl*/ false)) {
12274 Redeclaration = true;
12275 break;
12276
12278 Redeclaration = true;
12279 break;
12280
12282 Redeclaration = false;
12283 break;
12284 }
12285 }
12286 }
12287
12288 // Check for a previous extern "C" declaration with this name.
12289 if (!Redeclaration &&
12291 if (!Previous.empty()) {
12292 // This is an extern "C" declaration with the same name as a previous
12293 // declaration, and thus redeclares that entity...
12294 Redeclaration = true;
12295 OldDecl = Previous.getFoundDecl();
12296 MergeTypeWithPrevious = false;
12297
12298 // ... except in the presence of __attribute__((overloadable)).
12299 if (OldDecl->hasAttr<OverloadableAttr>() ||
12300 NewFD->hasAttr<OverloadableAttr>()) {
12301 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12302 MayNeedOverloadableChecks = true;
12303 Redeclaration = false;
12304 OldDecl = nullptr;
12305 }
12306 }
12307 }
12308 }
12309
12310 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12311 return Redeclaration;
12312
12313 // PPC MMA non-pointer types are not allowed as function return types.
12314 if (Context.getTargetInfo().getTriple().isPPC64() &&
12315 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12316 NewFD->setInvalidDecl();
12317 }
12318
12319 CheckConstPureAttributesUsage(*this, NewFD);
12320
12321 // C++ [dcl.spec.auto.general]p12:
12322 // Return type deduction for a templated function with a placeholder in its
12323 // declared type occurs when the definition is instantiated even if the
12324 // function body contains a return statement with a non-type-dependent
12325 // operand.
12326 //
12327 // C++ [temp.dep.expr]p3:
12328 // An id-expression is type-dependent if it is a template-id that is not a
12329 // concept-id and is dependent; or if its terminal name is:
12330 // - [...]
12331 // - associated by name lookup with one or more declarations of member
12332 // functions of a class that is the current instantiation declared with a
12333 // return type that contains a placeholder type,
12334 // - [...]
12335 //
12336 // If this is a templated function with a placeholder in its return type,
12337 // make the placeholder type dependent since it won't be deduced until the
12338 // definition is instantiated. We do this here because it needs to happen
12339 // for implicitly instantiated member functions/member function templates.
12340 if (getLangOpts().CPlusPlus14 &&
12341 (NewFD->isDependentContext() &&
12342 NewFD->getReturnType()->isUndeducedType())) {
12343 const FunctionProtoType *FPT =
12344 NewFD->getType()->castAs<FunctionProtoType>();
12345 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12346 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12347 FPT->getExtProtoInfo()));
12348 }
12349
12350 // C++11 [dcl.constexpr]p8:
12351 // A constexpr specifier for a non-static member function that is not
12352 // a constructor declares that member function to be const.
12353 //
12354 // This needs to be delayed until we know whether this is an out-of-line
12355 // definition of a static member function.
12356 //
12357 // This rule is not present in C++1y, so we produce a backwards
12358 // compatibility warning whenever it happens in C++11.
12359 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12360 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12361 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12363 CXXMethodDecl *OldMD = nullptr;
12364 if (OldDecl)
12365 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12366 if (!OldMD || !OldMD->isStatic()) {
12367 const FunctionProtoType *FPT =
12370 EPI.TypeQuals.addConst();
12371 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12372 FPT->getParamTypes(), EPI));
12373
12374 // Warn that we did this, if we're not performing template instantiation.
12375 // In that case, we'll have warned already when the template was defined.
12376 if (!inTemplateInstantiation()) {
12377 SourceLocation AddConstLoc;
12380 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12381
12382 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12383 << FixItHint::CreateInsertion(AddConstLoc, " const");
12384 }
12385 }
12386 }
12387
12388 if (Redeclaration) {
12389 // NewFD and OldDecl represent declarations that need to be
12390 // merged.
12391 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12392 DeclIsDefn)) {
12393 NewFD->setInvalidDecl();
12394 return Redeclaration;
12395 }
12396
12397 Previous.clear();
12398 Previous.addDecl(OldDecl);
12399
12400 if (FunctionTemplateDecl *OldTemplateDecl =
12401 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12402 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12403 FunctionTemplateDecl *NewTemplateDecl
12405 assert(NewTemplateDecl && "Template/non-template mismatch");
12406
12407 // The call to MergeFunctionDecl above may have created some state in
12408 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12409 // can add it as a redeclaration.
12410 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12411
12412 NewFD->setPreviousDeclaration(OldFD);
12413 if (NewFD->isCXXClassMember()) {
12414 NewFD->setAccess(OldTemplateDecl->getAccess());
12415 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12416 }
12417
12418 // If this is an explicit specialization of a member that is a function
12419 // template, mark it as a member specialization.
12420 if (IsMemberSpecialization &&
12421 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12422 NewTemplateDecl->setMemberSpecialization();
12423 assert(OldTemplateDecl->isMemberSpecialization());
12424 // Explicit specializations of a member template do not inherit deleted
12425 // status from the parent member template that they are specializing.
12426 if (OldFD->isDeleted()) {
12427 // FIXME: This assert will not hold in the presence of modules.
12428 assert(OldFD->getCanonicalDecl() == OldFD);
12429 // FIXME: We need an update record for this AST mutation.
12430 OldFD->setDeletedAsWritten(false);
12431 }
12432 }
12433
12434 } else {
12435 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12436 auto *OldFD = cast<FunctionDecl>(OldDecl);
12437 // This needs to happen first so that 'inline' propagates.
12438 NewFD->setPreviousDeclaration(OldFD);
12439 if (NewFD->isCXXClassMember())
12440 NewFD->setAccess(OldFD->getAccess());
12441 }
12442 }
12443 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12444 !NewFD->getAttr<OverloadableAttr>()) {
12445 assert((Previous.empty() ||
12446 llvm::any_of(Previous,
12447 [](const NamedDecl *ND) {
12448 return ND->hasAttr<OverloadableAttr>();
12449 })) &&
12450 "Non-redecls shouldn't happen without overloadable present");
12451
12452 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12453 const auto *FD = dyn_cast<FunctionDecl>(ND);
12454 return FD && !FD->hasAttr<OverloadableAttr>();
12455 });
12456
12457 if (OtherUnmarkedIter != Previous.end()) {
12458 Diag(NewFD->getLocation(),
12459 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12460 Diag((*OtherUnmarkedIter)->getLocation(),
12461 diag::note_attribute_overloadable_prev_overload)
12462 << false;
12463
12464 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12465 }
12466 }
12467
12468 if (LangOpts.OpenMP)
12470
12471 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12473
12474 if (NewFD->hasAttr<SYCLExternalAttr>())
12476
12477 // Semantic checking for this function declaration (in isolation).
12478
12479 if (getLangOpts().CPlusPlus) {
12480 // C++-specific checks.
12481 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12483 } else if (CXXDestructorDecl *Destructor =
12484 dyn_cast<CXXDestructorDecl>(NewFD)) {
12485 // We check here for invalid destructor names.
12486 // If we have a friend destructor declaration that is dependent, we can't
12487 // diagnose right away because cases like this are still valid:
12488 // template <class T> struct A { friend T::X::~Y(); };
12489 // struct B { struct Y { ~Y(); }; using X = Y; };
12490 // template struct A<B>;
12492 !Destructor->getFunctionObjectParameterType()->isDependentType()) {
12493 CanQualType ClassType =
12494 Context.getCanonicalTagType(Destructor->getParent());
12495
12496 DeclarationName Name =
12497 Context.DeclarationNames.getCXXDestructorName(ClassType);
12498 if (NewFD->getDeclName() != Name) {
12499 Diag(NewFD->getLocation(), diag::err_destructor_name);
12500 NewFD->setInvalidDecl();
12501 return Redeclaration;
12502 }
12503 }
12504 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12505 if (auto *TD = Guide->getDescribedFunctionTemplate())
12507
12508 // A deduction guide is not on the list of entities that can be
12509 // explicitly specialized.
12510 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12511 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12512 << /*explicit specialization*/ 1;
12513 }
12514
12515 // Find any virtual functions that this function overrides.
12516 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12517 if (!Method->isFunctionTemplateSpecialization() &&
12518 !Method->getDescribedFunctionTemplate() &&
12519 Method->isCanonicalDecl()) {
12520 AddOverriddenMethods(Method->getParent(), Method);
12521 }
12522 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12523 // C++2a [class.virtual]p6
12524 // A virtual method shall not have a requires-clause.
12526 diag::err_constrained_virtual_method);
12527
12528 if (Method->isStatic())
12530 }
12531
12532 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12533 ActOnConversionDeclarator(Conversion);
12534
12535 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12536 if (NewFD->isOverloadedOperator() &&
12538 NewFD->setInvalidDecl();
12539 return Redeclaration;
12540 }
12541
12542 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12543 if (NewFD->getLiteralIdentifier() &&
12545 NewFD->setInvalidDecl();
12546 return Redeclaration;
12547 }
12548
12549 // In C++, check default arguments now that we have merged decls. Unless
12550 // the lexical context is the class, because in this case this is done
12551 // during delayed parsing anyway.
12552 if (!CurContext->isRecord())
12554
12555 // If this function is declared as being extern "C", then check to see if
12556 // the function returns a UDT (class, struct, or union type) that is not C
12557 // compatible, and if it does, warn the user.
12558 // But, issue any diagnostic on the first declaration only.
12559 if (Previous.empty() && NewFD->isExternC()) {
12560 QualType R = NewFD->getReturnType();
12561 if (R->isIncompleteType() && !R->isVoidType())
12562 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12563 << NewFD << R;
12564 else if (!R.isPODType(Context) && !R->isVoidType() &&
12565 !R->isObjCObjectPointerType())
12566 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12567 }
12568
12569 // C++1z [dcl.fct]p6:
12570 // [...] whether the function has a non-throwing exception-specification
12571 // [is] part of the function type
12572 //
12573 // This results in an ABI break between C++14 and C++17 for functions whose
12574 // declared type includes an exception-specification in a parameter or
12575 // return type. (Exception specifications on the function itself are OK in
12576 // most cases, and exception specifications are not permitted in most other
12577 // contexts where they could make it into a mangling.)
12578 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12579 auto HasNoexcept = [&](QualType T) -> bool {
12580 // Strip off declarator chunks that could be between us and a function
12581 // type. We don't need to look far, exception specifications are very
12582 // restricted prior to C++17.
12583 if (auto *RT = T->getAs<ReferenceType>())
12584 T = RT->getPointeeType();
12585 else if (T->isAnyPointerType())
12586 T = T->getPointeeType();
12587 else if (auto *MPT = T->getAs<MemberPointerType>())
12588 T = MPT->getPointeeType();
12589 if (auto *FPT = T->getAs<FunctionProtoType>())
12590 if (FPT->isNothrow())
12591 return true;
12592 return false;
12593 };
12594
12595 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12596 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12597 for (QualType T : FPT->param_types())
12598 AnyNoexcept |= HasNoexcept(T);
12599 if (AnyNoexcept)
12600 Diag(NewFD->getLocation(),
12601 diag::warn_cxx17_compat_exception_spec_in_signature)
12602 << NewFD;
12603 }
12604
12605 if (!Redeclaration && LangOpts.CUDA) {
12606 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12607 for (auto *Parm : NewFD->parameters()) {
12608 if (!Parm->getType()->isDependentType() &&
12609 Parm->hasAttr<CUDAGridConstantAttr>() &&
12610 !(IsKernel && Parm->getType().isConstQualified()))
12611 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12612 diag::err_cuda_grid_constant_not_allowed);
12613 }
12615 }
12616 }
12617
12618 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12620
12621 return Redeclaration;
12622}
12623
12625 // [basic.start.main]p3
12626 // The main function shall not be declared with C linkage-specification.
12627 if (FD->isExternCContext())
12628 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12629
12630 // C++11 [basic.start.main]p3:
12631 // A program that [...] declares main to be inline, static or
12632 // constexpr is ill-formed.
12633 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12634 // appear in a declaration of main.
12635 // static main is not an error under C99, but we should warn about it.
12636 // We accept _Noreturn main as an extension.
12637 if (FD->getStorageClass() == SC_Static)
12639 ? diag::err_static_main : diag::warn_static_main)
12641 if (FD->isInlineSpecified())
12642 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12644 if (DS.isNoreturnSpecified()) {
12645 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12646 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12647 Diag(NoreturnLoc, diag::ext_noreturn_main);
12648 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12649 << FixItHint::CreateRemoval(NoreturnRange);
12650 }
12651 if (FD->isConstexpr()) {
12652 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12653 << FD->isConsteval()
12656 }
12657
12658 if (getLangOpts().OpenCL) {
12659 Diag(FD->getLocation(), diag::err_opencl_no_main)
12660 << FD->hasAttr<DeviceKernelAttr>();
12661 FD->setInvalidDecl();
12662 return;
12663 }
12664
12665 if (FD->hasAttr<SYCLExternalAttr>()) {
12666 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12667 << FD->getAttr<SYCLExternalAttr>();
12668 FD->setInvalidDecl();
12669 return;
12670 }
12671
12672 // Functions named main in hlsl are default entries, but don't have specific
12673 // signatures they are required to conform to.
12674 if (getLangOpts().HLSL)
12675 return;
12676
12677 QualType T = FD->getType();
12678 assert(T->isFunctionType() && "function decl is not of function type");
12679 const FunctionType* FT = T->castAs<FunctionType>();
12680
12681 // Set default calling convention for main()
12682 if (FT->getCallConv() != CC_C) {
12683 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12684 FD->setType(QualType(FT, 0));
12685 T = Context.getCanonicalType(FD->getType());
12686 }
12687
12689 // In C with GNU extensions we allow main() to have non-integer return
12690 // type, but we should warn about the extension, and we disable the
12691 // implicit-return-zero rule.
12692
12693 // GCC in C mode accepts qualified 'int'.
12694 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12695 FD->setHasImplicitReturnZero(true);
12696 else {
12697 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12698 SourceRange RTRange = FD->getReturnTypeSourceRange();
12699 if (RTRange.isValid())
12700 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12701 << FixItHint::CreateReplacement(RTRange, "int");
12702 }
12703 } else {
12704 // In C and C++, main magically returns 0 if you fall off the end;
12705 // set the flag which tells us that.
12706 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12707
12708 // All the standards say that main() should return 'int'.
12709 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12710 FD->setHasImplicitReturnZero(true);
12711 else {
12712 // Otherwise, this is just a flat-out error.
12713 SourceRange RTRange = FD->getReturnTypeSourceRange();
12714 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12715 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12716 : FixItHint());
12717 FD->setInvalidDecl(true);
12718 }
12719
12720 // [basic.start.main]p3:
12721 // A program that declares a function main that belongs to the global scope
12722 // and is attached to a named module is ill-formed.
12723 if (FD->isInNamedModule()) {
12724 const SourceLocation start = FD->getTypeSpecStartLoc();
12725 Diag(start, diag::warn_main_in_named_module)
12726 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12727 }
12728 }
12729
12730 // Treat protoless main() as nullary.
12731 if (isa<FunctionNoProtoType>(FT)) return;
12732
12734 unsigned nparams = FTP->getNumParams();
12735 assert(FD->getNumParams() == nparams);
12736
12737 bool HasExtraParameters = (nparams > 3);
12738
12739 if (FTP->isVariadic()) {
12740 Diag(FD->getLocation(), diag::ext_variadic_main);
12741 // FIXME: if we had information about the location of the ellipsis, we
12742 // could add a FixIt hint to remove it as a parameter.
12743 }
12744
12745 // Darwin passes an undocumented fourth argument of type char**. If
12746 // other platforms start sprouting these, the logic below will start
12747 // getting shifty.
12748 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12749 HasExtraParameters = false;
12750
12751 if (HasExtraParameters) {
12752 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12753 FD->setInvalidDecl(true);
12754 nparams = 3;
12755 }
12756
12757 // FIXME: a lot of the following diagnostics would be improved
12758 // if we had some location information about types.
12759
12760 QualType CharPP =
12761 Context.getPointerType(Context.getPointerType(Context.CharTy));
12762 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12763
12764 for (unsigned i = 0; i < nparams; ++i) {
12765 QualType AT = FTP->getParamType(i);
12766
12767 bool mismatch = true;
12768
12769 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12770 mismatch = false;
12771 else if (Expected[i] == CharPP) {
12772 // As an extension, the following forms are okay:
12773 // char const **
12774 // char const * const *
12775 // char * const *
12776
12778 const PointerType* PT;
12779 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12780 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12781 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12782 Context.CharTy)) {
12783 qs.removeConst();
12784 mismatch = !qs.empty();
12785 }
12786 }
12787
12788 if (mismatch) {
12789 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12790 // TODO: suggest replacing given type with expected type
12791 FD->setInvalidDecl(true);
12792 }
12793 }
12794
12795 if (nparams == 1 && !FD->isInvalidDecl()) {
12796 Diag(FD->getLocation(), diag::warn_main_one_arg);
12797 }
12798
12799 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12800 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12801 FD->setInvalidDecl();
12802 }
12803}
12804
12805static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12806
12807 // Default calling convention for main and wmain is __cdecl
12808 if (FD->getName() == "main" || FD->getName() == "wmain")
12809 return false;
12810
12811 // Default calling convention for MinGW and Cygwin is __cdecl
12812 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
12813 if (T.isOSCygMing())
12814 return false;
12815
12816 // Default calling convention for WinMain, wWinMain and DllMain
12817 // is __stdcall on 32 bit Windows
12818 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
12819 return true;
12820
12821 return false;
12822}
12823
12825 QualType T = FD->getType();
12826 assert(T->isFunctionType() && "function decl is not of function type");
12827 const FunctionType *FT = T->castAs<FunctionType>();
12828
12829 // Set an implicit return of 'zero' if the function can return some integral,
12830 // enumeration, pointer or nullptr type.
12834 // DllMain is exempt because a return value of zero means it failed.
12835 if (FD->getName() != "DllMain")
12836 FD->setHasImplicitReturnZero(true);
12837
12838 // Explicitly specified calling conventions are applied to MSVC entry points
12839 if (!hasExplicitCallingConv(T)) {
12840 if (isDefaultStdCall(FD, *this)) {
12841 if (FT->getCallConv() != CC_X86StdCall) {
12842 FT = Context.adjustFunctionType(
12844 FD->setType(QualType(FT, 0));
12845 }
12846 } else if (FT->getCallConv() != CC_C) {
12847 FT = Context.adjustFunctionType(FT,
12849 FD->setType(QualType(FT, 0));
12850 }
12851 }
12852
12853 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12854 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12855 FD->setInvalidDecl();
12856 }
12857}
12858
12860 // FIXME: Need strict checking. In C89, we need to check for
12861 // any assignment, increment, decrement, function-calls, or
12862 // commas outside of a sizeof. In C99, it's the same list,
12863 // except that the aforementioned are allowed in unevaluated
12864 // expressions. Everything else falls under the
12865 // "may accept other forms of constant expressions" exception.
12866 //
12867 // Regular C++ code will not end up here (exceptions: language extensions,
12868 // OpenCL C++ etc), so the constant expression rules there don't matter.
12869 if (Init->isValueDependent()) {
12870 assert(Init->containsErrors() &&
12871 "Dependent code should only occur in error-recovery path.");
12872 return true;
12873 }
12874 const Expr *Culprit;
12875 if (Init->isConstantInitializer(Context, false, &Culprit))
12876 return false;
12877 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
12878 return true;
12879}
12880
12881namespace {
12882 // Visits an initialization expression to see if OrigDecl is evaluated in
12883 // its own initialization and throws a warning if it does.
12884 class SelfReferenceChecker
12885 : public EvaluatedExprVisitor<SelfReferenceChecker> {
12886 Sema &S;
12887 Decl *OrigDecl;
12888 bool isRecordType;
12889 bool isPODType;
12890 bool isReferenceType;
12891 bool isInCXXOperatorCall;
12892
12893 bool isInitList;
12894 llvm::SmallVector<unsigned, 4> InitFieldIndex;
12895
12896 public:
12898
12899 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
12900 S(S), OrigDecl(OrigDecl) {
12901 isPODType = false;
12902 isRecordType = false;
12903 isReferenceType = false;
12904 isInCXXOperatorCall = false;
12905 isInitList = false;
12906 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
12907 isPODType = VD->getType().isPODType(S.Context);
12908 isRecordType = VD->getType()->isRecordType();
12909 isReferenceType = VD->getType()->isReferenceType();
12910 }
12911 }
12912
12913 // For most expressions, just call the visitor. For initializer lists,
12914 // track the index of the field being initialized since fields are
12915 // initialized in order allowing use of previously initialized fields.
12916 void CheckExpr(Expr *E) {
12917 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
12918 if (!InitList) {
12919 Visit(E);
12920 return;
12921 }
12922
12923 // Track and increment the index here.
12924 isInitList = true;
12925 InitFieldIndex.push_back(0);
12926 for (auto *Child : InitList->children()) {
12927 CheckExpr(cast<Expr>(Child));
12928 ++InitFieldIndex.back();
12929 }
12930 InitFieldIndex.pop_back();
12931 }
12932
12933 // Returns true if MemberExpr is checked and no further checking is needed.
12934 // Returns false if additional checking is required.
12935 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
12936 llvm::SmallVector<FieldDecl*, 4> Fields;
12937 Expr *Base = E;
12938 bool ReferenceField = false;
12939
12940 // Get the field members used.
12941 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
12942 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
12943 if (!FD)
12944 return false;
12945 Fields.push_back(FD);
12946 if (FD->getType()->isReferenceType())
12947 ReferenceField = true;
12948 Base = ME->getBase()->IgnoreParenImpCasts();
12949 }
12950
12951 // Keep checking only if the base Decl is the same.
12952 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
12953 if (!DRE || DRE->getDecl() != OrigDecl)
12954 return false;
12955
12956 // A reference field can be bound to an unininitialized field.
12957 if (CheckReference && !ReferenceField)
12958 return true;
12959
12960 // Convert FieldDecls to their index number.
12961 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
12962 for (const FieldDecl *I : llvm::reverse(Fields))
12963 UsedFieldIndex.push_back(I->getFieldIndex());
12964
12965 // See if a warning is needed by checking the first difference in index
12966 // numbers. If field being used has index less than the field being
12967 // initialized, then the use is safe.
12968 for (auto UsedIter = UsedFieldIndex.begin(),
12969 UsedEnd = UsedFieldIndex.end(),
12970 OrigIter = InitFieldIndex.begin(),
12971 OrigEnd = InitFieldIndex.end();
12972 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
12973 if (*UsedIter < *OrigIter)
12974 return true;
12975 if (*UsedIter > *OrigIter)
12976 break;
12977 }
12978
12979 // TODO: Add a different warning which will print the field names.
12980 HandleDeclRefExpr(DRE);
12981 return true;
12982 }
12983
12984 // For most expressions, the cast is directly above the DeclRefExpr.
12985 // For conditional operators, the cast can be outside the conditional
12986 // operator if both expressions are DeclRefExpr's.
12987 void HandleValue(Expr *E) {
12988 E = E->IgnoreParens();
12989 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
12990 HandleDeclRefExpr(DRE);
12991 return;
12992 }
12993
12994 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
12995 Visit(CO->getCond());
12996 HandleValue(CO->getTrueExpr());
12997 HandleValue(CO->getFalseExpr());
12998 return;
12999 }
13000
13001 if (BinaryConditionalOperator *BCO =
13002 dyn_cast<BinaryConditionalOperator>(E)) {
13003 Visit(BCO->getCond());
13004 HandleValue(BCO->getFalseExpr());
13005 return;
13006 }
13007
13008 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
13009 if (Expr *SE = OVE->getSourceExpr())
13010 HandleValue(SE);
13011 return;
13012 }
13013
13014 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13015 if (BO->getOpcode() == BO_Comma) {
13016 Visit(BO->getLHS());
13017 HandleValue(BO->getRHS());
13018 return;
13019 }
13020 }
13021
13022 if (isa<MemberExpr>(E)) {
13023 if (isInitList) {
13024 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
13025 false /*CheckReference*/))
13026 return;
13027 }
13028
13029 Expr *Base = E->IgnoreParenImpCasts();
13030 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13031 // Check for static member variables and don't warn on them.
13032 if (!isa<FieldDecl>(ME->getMemberDecl()))
13033 return;
13034 Base = ME->getBase()->IgnoreParenImpCasts();
13035 }
13036 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
13037 HandleDeclRefExpr(DRE);
13038 return;
13039 }
13040
13041 Visit(E);
13042 }
13043
13044 // Reference types not handled in HandleValue are handled here since all
13045 // uses of references are bad, not just r-value uses.
13046 void VisitDeclRefExpr(DeclRefExpr *E) {
13047 if (isReferenceType)
13048 HandleDeclRefExpr(E);
13049 }
13050
13051 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13052 if (E->getCastKind() == CK_LValueToRValue) {
13053 HandleValue(E->getSubExpr());
13054 return;
13055 }
13056
13057 Inherited::VisitImplicitCastExpr(E);
13058 }
13059
13060 void VisitMemberExpr(MemberExpr *E) {
13061 if (isInitList) {
13062 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13063 return;
13064 }
13065
13066 // Don't warn on arrays since they can be treated as pointers.
13067 if (E->getType()->canDecayToPointerType()) return;
13068
13069 // Warn when a non-static method call is followed by non-static member
13070 // field accesses, which is followed by a DeclRefExpr.
13071 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13072 bool Warn = (MD && !MD->isStatic());
13073 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13074 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13075 if (!isa<FieldDecl>(ME->getMemberDecl()))
13076 Warn = false;
13077 Base = ME->getBase()->IgnoreParenImpCasts();
13078 }
13079
13080 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13081 if (Warn)
13082 HandleDeclRefExpr(DRE);
13083 return;
13084 }
13085
13086 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13087 // Visit that expression.
13088 Visit(Base);
13089 }
13090
13091 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13092 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13093 Expr *Callee = E->getCallee();
13094
13095 if (isa<UnresolvedLookupExpr>(Callee))
13096 return Inherited::VisitCXXOperatorCallExpr(E);
13097
13098 Visit(Callee);
13099 for (auto Arg: E->arguments())
13100 HandleValue(Arg->IgnoreParenImpCasts());
13101 }
13102
13103 void VisitLambdaExpr(LambdaExpr *E) {
13104 if (!isInCXXOperatorCall) {
13105 Inherited::VisitLambdaExpr(E);
13106 return;
13107 }
13108
13109 for (Expr *Init : E->capture_inits())
13110 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13111 HandleDeclRefExpr(DRE);
13112 else if (Init)
13113 Visit(Init);
13114 }
13115
13116 void VisitUnaryOperator(UnaryOperator *E) {
13117 // For POD record types, addresses of its own members are well-defined.
13118 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13120 if (!isPODType)
13121 HandleValue(E->getSubExpr());
13122 return;
13123 }
13124
13125 if (E->isIncrementDecrementOp()) {
13126 HandleValue(E->getSubExpr());
13127 return;
13128 }
13129
13130 Inherited::VisitUnaryOperator(E);
13131 }
13132
13133 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13134
13135 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13136 if (E->getConstructor()->isCopyConstructor()) {
13137 Expr *ArgExpr = E->getArg(0);
13138 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13139 if (ILE->getNumInits() == 1)
13140 ArgExpr = ILE->getInit(0);
13141 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13142 if (ICE->getCastKind() == CK_NoOp)
13143 ArgExpr = ICE->getSubExpr();
13144 HandleValue(ArgExpr);
13145 return;
13146 }
13147 Inherited::VisitCXXConstructExpr(E);
13148 }
13149
13150 void VisitCallExpr(CallExpr *E) {
13151 // Treat std::move as a use.
13152 if (E->isCallToStdMove()) {
13153 HandleValue(E->getArg(0));
13154 return;
13155 }
13156
13157 Inherited::VisitCallExpr(E);
13158 }
13159
13160 void VisitBinaryOperator(BinaryOperator *E) {
13161 if (E->isCompoundAssignmentOp()) {
13162 HandleValue(E->getLHS());
13163 Visit(E->getRHS());
13164 return;
13165 }
13166
13167 Inherited::VisitBinaryOperator(E);
13168 }
13169
13170 // A custom visitor for BinaryConditionalOperator is needed because the
13171 // regular visitor would check the condition and true expression separately
13172 // but both point to the same place giving duplicate diagnostics.
13173 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13174 Visit(E->getCond());
13175 Visit(E->getFalseExpr());
13176 }
13177
13178 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13179 Decl* ReferenceDecl = DRE->getDecl();
13180 if (OrigDecl != ReferenceDecl) return;
13181 unsigned diag;
13182 if (isReferenceType) {
13183 diag = diag::warn_uninit_self_reference_in_reference_init;
13184 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13185 diag = diag::warn_static_self_reference_in_init;
13186 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13187 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13188 DRE->getDecl()->getType()->isRecordType()) {
13189 diag = diag::warn_uninit_self_reference_in_init;
13190 } else {
13191 // Local variables will be handled by the CFG analysis.
13192 return;
13193 }
13194
13195 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13196 S.PDiag(diag)
13197 << DRE->getDecl() << OrigDecl->getLocation()
13198 << DRE->getSourceRange());
13199 }
13200 };
13201
13202 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13203 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13204 bool DirectInit) {
13205 // Parameters arguments are occassionially constructed with itself,
13206 // for instance, in recursive functions. Skip them.
13207 if (isa<ParmVarDecl>(OrigDecl))
13208 return;
13209
13210 // Skip checking for file-scope constexpr variables - constant evaluation
13211 // will produce appropriate errors without needing runtime diagnostics.
13212 // Local constexpr should still emit runtime warnings.
13213 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13214 VD && VD->isConstexpr() && VD->isFileVarDecl())
13215 return;
13216
13217 E = E->IgnoreParens();
13218
13219 // Skip checking T a = a where T is not a record or reference type.
13220 // Doing so is a way to silence uninitialized warnings.
13221 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13222 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13223 if (ICE->getCastKind() == CK_LValueToRValue)
13224 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13225 if (DRE->getDecl() == OrigDecl)
13226 return;
13227
13228 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13229 }
13230} // end anonymous namespace
13231
13232namespace {
13233 // Simple wrapper to add the name of a variable or (if no variable is
13234 // available) a DeclarationName into a diagnostic.
13235 struct VarDeclOrName {
13236 VarDecl *VDecl;
13237 DeclarationName Name;
13238
13239 friend const Sema::SemaDiagnosticBuilder &
13240 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13241 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13242 }
13243 };
13244} // end anonymous namespace
13245
13248 TypeSourceInfo *TSI,
13249 SourceRange Range, bool DirectInit,
13250 Expr *Init) {
13251 bool IsInitCapture = !VDecl;
13252 assert((!VDecl || !VDecl->isInitCapture()) &&
13253 "init captures are expected to be deduced prior to initialization");
13254
13255 VarDeclOrName VN{VDecl, Name};
13256
13257 DeducedType *Deduced = Type->getContainedDeducedType();
13258 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13259
13260 // Diagnose auto array declarations in C23, unless it's a supported extension.
13261 if (getLangOpts().C23 && Type->isArrayType() &&
13262 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13263 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13264 << (int)Deduced->getContainedAutoType()->getKeyword()
13265 << /*in array decl*/ 23 << Range;
13266 return QualType();
13267 }
13268
13269 // C++11 [dcl.spec.auto]p3
13270 if (!Init) {
13271 assert(VDecl && "no init for init capture deduction?");
13272
13273 // Except for class argument deduction, and then for an initializing
13274 // declaration only, i.e. no static at class scope or extern.
13276 VDecl->hasExternalStorage() ||
13277 VDecl->isStaticDataMember()) {
13278 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13279 << VDecl->getDeclName() << Type;
13280 return QualType();
13281 }
13282 }
13283
13284 ArrayRef<Expr*> DeduceInits;
13285 if (Init)
13286 DeduceInits = Init;
13287
13288 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13289 if (DirectInit && PL)
13290 DeduceInits = PL->exprs();
13291
13293 assert(VDecl && "non-auto type for init capture deduction?");
13296 VDecl->getLocation(), DirectInit, Init);
13297 // FIXME: Initialization should not be taking a mutable list of inits.
13298 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13299 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13300 InitsCopy);
13301 }
13302
13303 if (DirectInit) {
13304 if (auto *IL = dyn_cast<InitListExpr>(Init))
13305 DeduceInits = IL->inits();
13306 }
13307
13308 // Deduction only works if we have exactly one source expression.
13309 if (DeduceInits.empty()) {
13310 // It isn't possible to write this directly, but it is possible to
13311 // end up in this situation with "auto x(some_pack...);"
13312 Diag(Init->getBeginLoc(), IsInitCapture
13313 ? diag::err_init_capture_no_expression
13314 : diag::err_auto_var_init_no_expression)
13315 << VN << Type << Range;
13316 return QualType();
13317 }
13318
13319 if (DeduceInits.size() > 1) {
13320 Diag(DeduceInits[1]->getBeginLoc(),
13321 IsInitCapture ? diag::err_init_capture_multiple_expressions
13322 : diag::err_auto_var_init_multiple_expressions)
13323 << VN << Type << Range;
13324 return QualType();
13325 }
13326
13327 Expr *DeduceInit = DeduceInits[0];
13328 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13329 Diag(Init->getBeginLoc(), IsInitCapture
13330 ? diag::err_init_capture_paren_braces
13331 : diag::err_auto_var_init_paren_braces)
13332 << isa<InitListExpr>(Init) << VN << Type << Range;
13333 return QualType();
13334 }
13335
13336 // Expressions default to 'id' when we're in a debugger.
13337 bool DefaultedAnyToId = false;
13338 if (getLangOpts().DebuggerCastResultToId &&
13339 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13341 if (Result.isInvalid()) {
13342 return QualType();
13343 }
13344 Init = Result.get();
13345 DefaultedAnyToId = true;
13346 }
13347
13348 // C++ [dcl.decomp]p1:
13349 // If the assignment-expression [...] has array type A and no ref-qualifier
13350 // is present, e has type cv A
13351 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13352 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13353 DeduceInit->getType()->isConstantArrayType())
13354 return Context.getQualifiedType(DeduceInit->getType(),
13355 Type.getQualifiers());
13356
13357 QualType DeducedType;
13358 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13360 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13363 if (!IsInitCapture)
13364 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13365 else if (isa<InitListExpr>(Init))
13366 Diag(Range.getBegin(),
13367 diag::err_init_capture_deduction_failure_from_init_list)
13368 << VN
13369 << (DeduceInit->getType().isNull() ? TSI->getType()
13370 : DeduceInit->getType())
13371 << DeduceInit->getSourceRange();
13372 else
13373 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13374 << VN << TSI->getType()
13375 << (DeduceInit->getType().isNull() ? TSI->getType()
13376 : DeduceInit->getType())
13377 << DeduceInit->getSourceRange();
13378 }
13379
13380 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13381 // 'id' instead of a specific object type prevents most of our usual
13382 // checks.
13383 // We only want to warn outside of template instantiations, though:
13384 // inside a template, the 'id' could have come from a parameter.
13385 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13386 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13387 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13388 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13389 }
13390
13391 return DeducedType;
13392}
13393
13395 Expr *Init) {
13396 assert(!Init || !Init->containsErrors());
13398 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13399 VDecl->getSourceRange(), DirectInit, Init);
13400 if (DeducedType.isNull()) {
13401 VDecl->setInvalidDecl();
13402 return true;
13403 }
13404
13405 VDecl->setType(DeducedType);
13406 assert(VDecl->isLinkageValid());
13407
13408 // In ARC, infer lifetime.
13409 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13410 VDecl->setInvalidDecl();
13411
13412 if (getLangOpts().OpenCL)
13414
13415 if (getLangOpts().HLSL)
13416 HLSL().deduceAddressSpace(VDecl);
13417
13418 // If this is a redeclaration, check that the type we just deduced matches
13419 // the previously declared type.
13420 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13421 // We never need to merge the type, because we cannot form an incomplete
13422 // array of auto, nor deduce such a type.
13423 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13424 }
13425
13426 // Check the deduced type is valid for a variable declaration.
13428 return VDecl->isInvalidDecl();
13429}
13430
13432 SourceLocation Loc) {
13433 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13434 Init = EWC->getSubExpr();
13435
13436 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13437 Init = CE->getSubExpr();
13438
13439 QualType InitType = Init->getType();
13442 "shouldn't be called if type doesn't have a non-trivial C struct");
13443 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13444 for (auto *I : ILE->inits()) {
13445 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13446 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13447 continue;
13448 SourceLocation SL = I->getExprLoc();
13449 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13450 }
13451 return;
13452 }
13453
13456 checkNonTrivialCUnion(InitType, Loc,
13458 NTCUK_Init);
13459 } else {
13460 // Assume all other explicit initializers involving copying some existing
13461 // object.
13462 // TODO: ignore any explicit initializers where we can guarantee
13463 // copy-elision.
13466 NTCUK_Copy);
13467 }
13468}
13469
13470namespace {
13471
13472bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13473 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13474 // in the source code or implicitly by the compiler if it is in a union
13475 // defined in a system header and has non-trivial ObjC ownership
13476 // qualifications. We don't want those fields to participate in determining
13477 // whether the containing union is non-trivial.
13478 return FD->hasAttr<UnavailableAttr>();
13479}
13480
13481struct DiagNonTrivalCUnionDefaultInitializeVisitor
13482 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13483 void> {
13484 using Super =
13485 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13486 void>;
13487
13488 DiagNonTrivalCUnionDefaultInitializeVisitor(
13489 QualType OrigTy, SourceLocation OrigLoc,
13490 NonTrivialCUnionContext UseContext, Sema &S)
13491 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13492
13493 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13494 const FieldDecl *FD, bool InNonTrivialUnion) {
13495 if (const auto *AT = S.Context.getAsArrayType(QT))
13496 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13497 InNonTrivialUnion);
13498 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13499 }
13500
13501 void visitARCStrong(QualType QT, const FieldDecl *FD,
13502 bool InNonTrivialUnion) {
13503 if (InNonTrivialUnion)
13504 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13505 << 1 << 0 << QT << FD->getName();
13506 }
13507
13508 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13509 if (InNonTrivialUnion)
13510 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13511 << 1 << 0 << QT << FD->getName();
13512 }
13513
13514 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13515 const auto *RD = QT->castAsRecordDecl();
13516 if (RD->isUnion()) {
13517 if (OrigLoc.isValid()) {
13518 bool IsUnion = false;
13519 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13520 IsUnion = OrigRD->isUnion();
13521 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13522 << 0 << OrigTy << IsUnion << UseContext;
13523 // Reset OrigLoc so that this diagnostic is emitted only once.
13524 OrigLoc = SourceLocation();
13525 }
13526 InNonTrivialUnion = true;
13527 }
13528
13529 if (InNonTrivialUnion)
13530 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13531 << 0 << 0 << QT.getUnqualifiedType() << "";
13532
13533 for (const FieldDecl *FD : RD->fields())
13534 if (!shouldIgnoreForRecordTriviality(FD))
13535 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13536 }
13537
13538 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13539
13540 // The non-trivial C union type or the struct/union type that contains a
13541 // non-trivial C union.
13542 QualType OrigTy;
13543 SourceLocation OrigLoc;
13544 NonTrivialCUnionContext UseContext;
13545 Sema &S;
13546};
13547
13548struct DiagNonTrivalCUnionDestructedTypeVisitor
13549 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13550 using Super =
13551 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13552
13553 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13554 SourceLocation OrigLoc,
13555 NonTrivialCUnionContext UseContext,
13556 Sema &S)
13557 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13558
13559 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13560 const FieldDecl *FD, bool InNonTrivialUnion) {
13561 if (const auto *AT = S.Context.getAsArrayType(QT))
13562 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13563 InNonTrivialUnion);
13564 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13565 }
13566
13567 void visitARCStrong(QualType QT, const FieldDecl *FD,
13568 bool InNonTrivialUnion) {
13569 if (InNonTrivialUnion)
13570 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13571 << 1 << 1 << QT << FD->getName();
13572 }
13573
13574 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13575 if (InNonTrivialUnion)
13576 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13577 << 1 << 1 << QT << FD->getName();
13578 }
13579
13580 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13581 const auto *RD = QT->castAsRecordDecl();
13582 if (RD->isUnion()) {
13583 if (OrigLoc.isValid()) {
13584 bool IsUnion = false;
13585 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13586 IsUnion = OrigRD->isUnion();
13587 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13588 << 1 << OrigTy << IsUnion << UseContext;
13589 // Reset OrigLoc so that this diagnostic is emitted only once.
13590 OrigLoc = SourceLocation();
13591 }
13592 InNonTrivialUnion = true;
13593 }
13594
13595 if (InNonTrivialUnion)
13596 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13597 << 0 << 1 << QT.getUnqualifiedType() << "";
13598
13599 for (const FieldDecl *FD : RD->fields())
13600 if (!shouldIgnoreForRecordTriviality(FD))
13601 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13602 }
13603
13604 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13605 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13606 bool InNonTrivialUnion) {}
13607
13608 // The non-trivial C union type or the struct/union type that contains a
13609 // non-trivial C union.
13610 QualType OrigTy;
13611 SourceLocation OrigLoc;
13612 NonTrivialCUnionContext UseContext;
13613 Sema &S;
13614};
13615
13616struct DiagNonTrivalCUnionCopyVisitor
13617 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13618 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13619
13620 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13621 NonTrivialCUnionContext UseContext, Sema &S)
13622 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13623
13624 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13625 const FieldDecl *FD, bool InNonTrivialUnion) {
13626 if (const auto *AT = S.Context.getAsArrayType(QT))
13627 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13628 InNonTrivialUnion);
13629 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13630 }
13631
13632 void visitARCStrong(QualType QT, const FieldDecl *FD,
13633 bool InNonTrivialUnion) {
13634 if (InNonTrivialUnion)
13635 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13636 << 1 << 2 << QT << FD->getName();
13637 }
13638
13639 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13640 if (InNonTrivialUnion)
13641 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13642 << 1 << 2 << QT << FD->getName();
13643 }
13644
13645 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13646 const auto *RD = QT->castAsRecordDecl();
13647 if (RD->isUnion()) {
13648 if (OrigLoc.isValid()) {
13649 bool IsUnion = false;
13650 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13651 IsUnion = OrigRD->isUnion();
13652 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13653 << 2 << OrigTy << IsUnion << UseContext;
13654 // Reset OrigLoc so that this diagnostic is emitted only once.
13655 OrigLoc = SourceLocation();
13656 }
13657 InNonTrivialUnion = true;
13658 }
13659
13660 if (InNonTrivialUnion)
13661 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13662 << 0 << 2 << QT.getUnqualifiedType() << "";
13663
13664 for (const FieldDecl *FD : RD->fields())
13665 if (!shouldIgnoreForRecordTriviality(FD))
13666 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13667 }
13668
13669 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13670 if (InNonTrivialUnion)
13671 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13672 << 1 << 2 << QT << FD->getName();
13673 }
13674
13675 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13676 const FieldDecl *FD, bool InNonTrivialUnion) {}
13677 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13678 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13679 bool InNonTrivialUnion) {}
13680
13681 // The non-trivial C union type or the struct/union type that contains a
13682 // non-trivial C union.
13683 QualType OrigTy;
13684 SourceLocation OrigLoc;
13685 NonTrivialCUnionContext UseContext;
13686 Sema &S;
13687};
13688
13689} // namespace
13690
13692 NonTrivialCUnionContext UseContext,
13693 unsigned NonTrivialKind) {
13697 "shouldn't be called if type doesn't have a non-trivial C union");
13698
13699 if ((NonTrivialKind & NTCUK_Init) &&
13701 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13702 .visit(QT, nullptr, false);
13703 if ((NonTrivialKind & NTCUK_Destruct) &&
13705 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13706 .visit(QT, nullptr, false);
13707 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13708 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13709 .visit(QT, nullptr, false);
13710}
13711
13713 const VarDecl *Dcl) {
13714 if (!getLangOpts().CPlusPlus)
13715 return false;
13716
13717 // We only need to warn if the definition is in a header file, so wait to
13718 // diagnose until we've seen the definition.
13719 if (!Dcl->isThisDeclarationADefinition())
13720 return false;
13721
13722 // If an object is defined in a source file, its definition can't get
13723 // duplicated since it will never appear in more than one TU.
13725 return false;
13726
13727 // If the variable we're looking at is a static local, then we actually care
13728 // about the properties of the function containing it.
13729 const ValueDecl *Target = Dcl;
13730 // VarDecls and FunctionDecls have different functions for checking
13731 // inline-ness, and whether they were originally templated, so we have to
13732 // call the appropriate functions manually.
13733 bool TargetIsInline = Dcl->isInline();
13734 bool TargetWasTemplated =
13736
13737 // Update the Target and TargetIsInline property if necessary
13738 if (Dcl->isStaticLocal()) {
13739 const DeclContext *Ctx = Dcl->getDeclContext();
13740 if (!Ctx)
13741 return false;
13742
13743 const FunctionDecl *FunDcl =
13744 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
13745 if (!FunDcl)
13746 return false;
13747
13748 Target = FunDcl;
13749 // IsInlined() checks for the C++ inline property
13750 TargetIsInline = FunDcl->isInlined();
13751 TargetWasTemplated =
13753 }
13754
13755 // Non-inline functions/variables can only legally appear in one TU
13756 // unless they were part of a template. Unfortunately, making complex
13757 // template instantiations visible is infeasible in practice, since
13758 // everything the template depends on also has to be visible. To avoid
13759 // giving impractical-to-fix warnings, don't warn if we're inside
13760 // something that was templated, even on inline stuff.
13761 if (!TargetIsInline || TargetWasTemplated)
13762 return false;
13763
13764 // If the object isn't hidden, the dynamic linker will prevent duplication.
13765 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
13766
13767 // The target is "hidden" (from the dynamic linker) if:
13768 // 1. On posix, it has hidden visibility, or
13769 // 2. On windows, it has no import/export annotation, and neither does the
13770 // class which directly contains it.
13771 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
13772 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
13773 return false;
13774
13775 // If the variable isn't directly annotated, check to see if it's a member
13776 // of an annotated class.
13777 const CXXRecordDecl *Ctx =
13778 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
13779 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
13780 return false;
13781
13782 } else if (Lnk.getVisibility() != HiddenVisibility) {
13783 // Posix case
13784 return false;
13785 }
13786
13787 // If the obj doesn't have external linkage, it's supposed to be duplicated.
13789 return false;
13790
13791 return true;
13792}
13793
13794// Determine whether the object seems mutable for the purpose of diagnosing
13795// possible unique object duplication, i.e. non-const-qualified, and
13796// not an always-constant type like a function.
13797// Not perfect: doesn't account for mutable members, for example, or
13798// elements of container types.
13799// For nested pointers, any individual level being non-const is sufficient.
13800static bool looksMutable(QualType T, const ASTContext &Ctx) {
13801 T = T.getNonReferenceType();
13802 if (T->isFunctionType())
13803 return false;
13804 if (!T.isConstant(Ctx))
13805 return true;
13806 if (T->isPointerType())
13807 return looksMutable(T->getPointeeType(), Ctx);
13808 return false;
13809}
13810
13812 // If this object has external linkage and hidden visibility, it might be
13813 // duplicated when built into a shared library, which causes problems if it's
13814 // mutable (since the copies won't be in sync) or its initialization has side
13815 // effects (since it will run once per copy instead of once globally).
13816
13817 // Don't diagnose if we're inside a template, because it's not practical to
13818 // fix the warning in most cases.
13819 if (!VD->isTemplated() &&
13821
13822 QualType Type = VD->getType();
13823 if (looksMutable(Type, VD->getASTContext())) {
13824 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
13825 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13826 }
13827
13828 // To keep false positives low, only warn if we're certain that the
13829 // initializer has side effects. Don't warn on operator new, since a mutable
13830 // pointer will trigger the previous warning, and an immutable pointer
13831 // getting duplicated just results in a little extra memory usage.
13832 const Expr *Init = VD->getAnyInitializer();
13833 if (Init &&
13834 Init->HasSideEffects(VD->getASTContext(),
13835 /*IncludePossibleEffects=*/false) &&
13836 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
13837 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
13838 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
13839 }
13840 }
13841}
13842
13844 llvm::scope_exit ResetDeclForInitializer([this]() {
13845 if (!this->ExprEvalContexts.empty())
13846 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
13847 });
13848
13849 // If there is no declaration, there was an error parsing it. Just ignore
13850 // the initializer.
13851 if (!RealDecl) {
13852 return;
13853 }
13854
13855 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
13856 if (!Method->isInvalidDecl()) {
13857 // Pure-specifiers are handled in ActOnPureSpecifier.
13858 Diag(Method->getLocation(), diag::err_member_function_initialization)
13859 << Method->getDeclName() << Init->getSourceRange();
13860 Method->setInvalidDecl();
13861 }
13862 return;
13863 }
13864
13865 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
13866 if (!VDecl) {
13867 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
13868 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
13869 RealDecl->setInvalidDecl();
13870 return;
13871 }
13872
13873 if (VDecl->isInvalidDecl()) {
13874 ExprResult Recovery =
13875 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
13876 if (Expr *E = Recovery.get())
13877 VDecl->setInit(E);
13878 return;
13879 }
13880
13881 // WebAssembly tables can't be used to initialise a variable.
13882 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
13883 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
13884 VDecl->setInvalidDecl();
13885 return;
13886 }
13887
13888 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
13889 if (VDecl->getType()->isUndeducedType()) {
13890 if (Init->containsErrors()) {
13891 // Invalidate the decl as we don't know the type for recovery-expr yet.
13892 RealDecl->setInvalidDecl();
13893 VDecl->setInit(Init);
13894 return;
13895 }
13896
13898 assert(VDecl->isInvalidDecl() &&
13899 "decl should be invalidated when deduce fails");
13900 if (auto *RecoveryExpr =
13901 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init})
13902 .get())
13903 VDecl->setInit(RecoveryExpr);
13904 return;
13905 }
13906 }
13907
13908 this->CheckAttributesOnDeducedType(RealDecl);
13909
13910 // we don't initialize groupshared variables so warn and return
13911 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
13912 Diag(VDecl->getLocation(), diag::warn_hlsl_groupshared_init);
13913 return;
13914 }
13915
13916 // dllimport cannot be used on variable definitions.
13917 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
13918 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
13919 VDecl->setInvalidDecl();
13920 return;
13921 }
13922
13923 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
13924 // the identifier has external or internal linkage, the declaration shall
13925 // have no initializer for the identifier.
13926 // C++14 [dcl.init]p5 is the same restriction for C++.
13927 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
13928 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
13929 VDecl->setInvalidDecl();
13930 return;
13931 }
13932
13933 if (!VDecl->getType()->isDependentType()) {
13934 // A definition must end up with a complete type, which means it must be
13935 // complete with the restriction that an array type might be completed by
13936 // the initializer; note that later code assumes this restriction.
13937 QualType BaseDeclType = VDecl->getType();
13938 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
13939 BaseDeclType = Array->getElementType();
13940 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
13941 diag::err_typecheck_decl_incomplete_type)) {
13942 RealDecl->setInvalidDecl();
13943 return;
13944 }
13945
13946 // The variable can not have an abstract class type.
13947 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
13948 diag::err_abstract_type_in_decl,
13950 VDecl->setInvalidDecl();
13951 }
13952
13953 // C++ [module.import/6]
13954 // ...
13955 // A header unit shall not contain a definition of a non-inline function or
13956 // variable whose name has external linkage.
13957 //
13958 // We choose to allow weak & selectany definitions, as they are common in
13959 // headers, and have semantics similar to inline definitions which are allowed
13960 // in header units.
13961 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
13962 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
13963 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
13964 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
13966 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
13967 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
13968 VDecl->setInvalidDecl();
13969 }
13970
13971 // If adding the initializer will turn this declaration into a definition,
13972 // and we already have a definition for this variable, diagnose or otherwise
13973 // handle the situation.
13974 if (VarDecl *Def = VDecl->getDefinition())
13975 if (Def != VDecl &&
13976 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
13978 checkVarDeclRedefinition(Def, VDecl))
13979 return;
13980
13981 if (getLangOpts().CPlusPlus) {
13982 // C++ [class.static.data]p4
13983 // If a static data member is of const integral or const
13984 // enumeration type, its declaration in the class definition can
13985 // specify a constant-initializer which shall be an integral
13986 // constant expression (5.19). In that case, the member can appear
13987 // in integral constant expressions. The member shall still be
13988 // defined in a namespace scope if it is used in the program and the
13989 // namespace scope definition shall not contain an initializer.
13990 //
13991 // We already performed a redefinition check above, but for static
13992 // data members we also need to check whether there was an in-class
13993 // declaration with an initializer.
13994 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
13995 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
13996 << VDecl->getDeclName();
13997 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
13998 diag::note_previous_initializer)
13999 << 0;
14000 return;
14001 }
14002
14004 VDecl->setInvalidDecl();
14005 return;
14006 }
14007 }
14008
14009 // If the variable has an initializer and local storage, check whether
14010 // anything jumps over the initialization.
14011 if (VDecl->hasLocalStorage())
14013
14014 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14015 // a kernel function cannot be initialized."
14016 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14017 Diag(VDecl->getLocation(), diag::err_local_cant_init);
14018 VDecl->setInvalidDecl();
14019 return;
14020 }
14021
14022 // The LoaderUninitialized attribute acts as a definition (of undef).
14023 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14024 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
14025 VDecl->setInvalidDecl();
14026 return;
14027 }
14028
14029 if (getLangOpts().HLSL)
14030 if (!HLSL().handleInitialization(VDecl, Init))
14031 return;
14032
14033 // Get the decls type and save a reference for later, since
14034 // CheckInitializerTypes may change it.
14035 QualType DclT = VDecl->getType(), SavT = DclT;
14036
14037 // Expressions default to 'id' when we're in a debugger
14038 // and we are assigning it to a variable of Objective-C pointer type.
14039 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14040 Init->getType() == Context.UnknownAnyTy) {
14042 if (!Result.isUsable()) {
14043 VDecl->setInvalidDecl();
14044 return;
14045 }
14046 Init = Result.get();
14047 }
14048
14049 // Perform the initialization.
14050 bool InitializedFromParenListExpr = false;
14051 bool IsParenListInit = false;
14052 if (!VDecl->isInvalidDecl()) {
14055 VDecl->getLocation(), DirectInit, Init);
14056
14057 MultiExprArg Args = Init;
14058 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
14059 Args =
14060 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14061 InitializedFromParenListExpr = true;
14062 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
14063 Args = CXXDirectInit->getInitExprs();
14064 InitializedFromParenListExpr = true;
14065 }
14066
14067 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14068 /*TopLevelOfInitList=*/false,
14069 /*TreatUnavailableAsInvalid=*/false);
14070 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14071 if (!Result.isUsable()) {
14072 // If the provided initializer fails to initialize the var decl,
14073 // we attach a recovery expr for better recovery.
14074 auto RecoveryExpr =
14075 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14076 if (RecoveryExpr.get())
14077 VDecl->setInit(RecoveryExpr.get());
14078 // In general, for error recovery purposes, the initializer doesn't play
14079 // part in the valid bit of the declaration. There are a few exceptions:
14080 // 1) if the var decl has a deduced auto type, and the type cannot be
14081 // deduced by an invalid initializer;
14082 // 2) if the var decl is a decomposition decl with a non-deduced type,
14083 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14084 // Case 1) was already handled elsewhere.
14085 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14086 VDecl->setInvalidDecl();
14087 return;
14088 }
14089
14090 Init = Result.getAs<Expr>();
14091 IsParenListInit = !InitSeq.steps().empty() &&
14092 InitSeq.step_begin()->Kind ==
14094 QualType VDeclType = VDecl->getType();
14095 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14096 !VDeclType->isDependentType() &&
14097 Context.getAsIncompleteArrayType(VDeclType) &&
14098 Context.getAsIncompleteArrayType(Init->getType())) {
14099 // Bail out if it is not possible to deduce array size from the
14100 // initializer.
14101 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14102 << VDeclType;
14103 VDecl->setInvalidDecl();
14104 return;
14105 }
14106 }
14107
14108 // Check for self-references within variable initializers.
14109 // Variables declared within a function/method body (except for references)
14110 // are handled by a dataflow analysis.
14111 // This is undefined behavior in C++, but valid in C.
14112 if (getLangOpts().CPlusPlus)
14113 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14114 VDecl->getType()->isReferenceType())
14115 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14116
14117 // If the type changed, it means we had an incomplete type that was
14118 // completed by the initializer. For example:
14119 // int ary[] = { 1, 3, 5 };
14120 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14121 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14122 VDecl->setType(DclT);
14123
14124 if (!VDecl->isInvalidDecl()) {
14125 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14126
14127 if (VDecl->hasAttr<BlocksAttr>())
14128 ObjC().checkRetainCycles(VDecl, Init);
14129
14130 // It is safe to assign a weak reference into a strong variable.
14131 // Although this code can still have problems:
14132 // id x = self.weakProp;
14133 // id y = self.weakProp;
14134 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14135 // paths through the function. This should be revisited if
14136 // -Wrepeated-use-of-weak is made flow-sensitive.
14137 if (FunctionScopeInfo *FSI = getCurFunction())
14138 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14140 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14141 Init->getBeginLoc()))
14142 FSI->markSafeWeakUse(Init);
14143 }
14144
14145 // The initialization is usually a full-expression.
14146 //
14147 // FIXME: If this is a braced initialization of an aggregate, it is not
14148 // an expression, and each individual field initializer is a separate
14149 // full-expression. For instance, in:
14150 //
14151 // struct Temp { ~Temp(); };
14152 // struct S { S(Temp); };
14153 // struct T { S a, b; } t = { Temp(), Temp() }
14154 //
14155 // we should destroy the first Temp before constructing the second.
14156
14157 // Set context flag for OverflowBehaviorType initialization analysis
14159 true);
14162 /*DiscardedValue*/ false, VDecl->isConstexpr());
14163 if (!Result.isUsable()) {
14164 VDecl->setInvalidDecl();
14165 return;
14166 }
14167 Init = Result.get();
14168
14169 // Attach the initializer to the decl.
14170 VDecl->setInit(Init);
14171
14172 if (VDecl->isLocalVarDecl()) {
14173 // Don't check the initializer if the declaration is malformed.
14174 if (VDecl->isInvalidDecl()) {
14175 // do nothing
14176
14177 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14178 // This is true even in C++ for OpenCL.
14179 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14181
14182 // Otherwise, C++ does not restrict the initializer.
14183 } else if (getLangOpts().CPlusPlus) {
14184 // do nothing
14185
14186 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14187 // static storage duration shall be constant expressions or string literals.
14188 } else if (VDecl->getStorageClass() == SC_Static) {
14189 // Avoid evaluating the initializer twice for constexpr variables. It will
14190 // be evaluated later.
14191 if (!VDecl->isConstexpr())
14193
14194 // C89 is stricter than C99 for aggregate initializers.
14195 // C89 6.5.7p3: All the expressions [...] in an initializer list
14196 // for an object that has aggregate or union type shall be
14197 // constant expressions.
14198 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14200 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14201 }
14202
14203 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14204 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14205 if (VDecl->hasLocalStorage())
14206 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14207 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14208 VDecl->getLexicalDeclContext()->isRecord()) {
14209 // This is an in-class initialization for a static data member, e.g.,
14210 //
14211 // struct S {
14212 // static const int value = 17;
14213 // };
14214
14215 // C++ [class.mem]p4:
14216 // A member-declarator can contain a constant-initializer only
14217 // if it declares a static member (9.4) of const integral or
14218 // const enumeration type, see 9.4.2.
14219 //
14220 // C++11 [class.static.data]p3:
14221 // If a non-volatile non-inline const static data member is of integral
14222 // or enumeration type, its declaration in the class definition can
14223 // specify a brace-or-equal-initializer in which every initializer-clause
14224 // that is an assignment-expression is a constant expression. A static
14225 // data member of literal type can be declared in the class definition
14226 // with the constexpr specifier; if so, its declaration shall specify a
14227 // brace-or-equal-initializer in which every initializer-clause that is
14228 // an assignment-expression is a constant expression.
14229
14230 // Do nothing on dependent types.
14231 if (DclT->isDependentType()) {
14232
14233 // Allow any 'static constexpr' members, whether or not they are of literal
14234 // type. We separately check that every constexpr variable is of literal
14235 // type.
14236 } else if (VDecl->isConstexpr()) {
14237
14238 // Require constness.
14239 } else if (!DclT.isConstQualified()) {
14240 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14241 << Init->getSourceRange();
14242 VDecl->setInvalidDecl();
14243
14244 // We allow integer constant expressions in all cases.
14245 } else if (DclT->isIntegralOrEnumerationType()) {
14247 // In C++11, a non-constexpr const static data member with an
14248 // in-class initializer cannot be volatile.
14249 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14250
14251 // We allow foldable floating-point constants as an extension.
14252 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14253 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14254 // it anyway and provide a fixit to add the 'constexpr'.
14255 if (getLangOpts().CPlusPlus11) {
14256 Diag(VDecl->getLocation(),
14257 diag::ext_in_class_initializer_float_type_cxx11)
14258 << DclT << Init->getSourceRange();
14259 Diag(VDecl->getBeginLoc(),
14260 diag::note_in_class_initializer_float_type_cxx11)
14261 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14262 } else {
14263 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14264 << DclT << Init->getSourceRange();
14265
14266 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14267 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14268 << Init->getSourceRange();
14269 VDecl->setInvalidDecl();
14270 }
14271 }
14272
14273 // Suggest adding 'constexpr' in C++11 for literal types.
14274 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14275 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14276 << DclT << Init->getSourceRange()
14277 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14278 VDecl->setConstexpr(true);
14279
14280 } else {
14281 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14282 << DclT << Init->getSourceRange();
14283 VDecl->setInvalidDecl();
14284 }
14285 } else if (VDecl->isFileVarDecl()) {
14286 // In C, extern is typically used to avoid tentative definitions when
14287 // declaring variables in headers, but adding an initializer makes it a
14288 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14289 // In C++, extern is often used to give implicitly static const variables
14290 // external linkage, so don't warn in that case. If selectany is present,
14291 // this might be header code intended for C and C++ inclusion, so apply the
14292 // C++ rules.
14293 if (VDecl->getStorageClass() == SC_Extern &&
14294 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14295 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14296 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14298 Diag(VDecl->getLocation(), diag::warn_extern_init);
14299
14300 // In Microsoft C++ mode, a const variable defined in namespace scope has
14301 // external linkage by default if the variable is declared with
14302 // __declspec(dllexport).
14303 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14305 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14306 VDecl->setStorageClass(SC_Extern);
14307
14308 // C99 6.7.8p4. All file scoped initializers need to be constant.
14309 // Avoid duplicate diagnostics for constexpr variables.
14310 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14311 !VDecl->isConstexpr())
14313 }
14314
14315 QualType InitType = Init->getType();
14316 if (!InitType.isNull() &&
14320
14321 // We will represent direct-initialization similarly to copy-initialization:
14322 // int x(1); -as-> int x = 1;
14323 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14324 //
14325 // Clients that want to distinguish between the two forms, can check for
14326 // direct initializer using VarDecl::getInitStyle().
14327 // A major benefit is that clients that don't particularly care about which
14328 // exactly form was it (like the CodeGen) can handle both cases without
14329 // special case code.
14330
14331 // C++ 8.5p11:
14332 // The form of initialization (using parentheses or '=') matters
14333 // when the entity being initialized has class type.
14334 if (InitializedFromParenListExpr) {
14335 assert(DirectInit && "Call-style initializer must be direct init.");
14336 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14338 } else if (DirectInit) {
14339 // This must be list-initialization. No other way is direct-initialization.
14341 }
14342
14343 if (LangOpts.OpenMP &&
14344 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14345 VDecl->isFileVarDecl())
14346 DeclsToCheckForDeferredDiags.insert(VDecl);
14348
14349 if (LangOpts.OpenACC && !InitType.isNull())
14350 OpenACC().ActOnVariableInit(VDecl, InitType);
14351}
14352
14354 // Our main concern here is re-establishing invariants like "a
14355 // variable's type is either dependent or complete".
14356 if (!D || D->isInvalidDecl()) return;
14357
14358 VarDecl *VD = dyn_cast<VarDecl>(D);
14359 if (!VD) return;
14360
14361 // Bindings are not usable if we can't make sense of the initializer.
14362 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14363 for (auto *BD : DD->bindings())
14364 BD->setInvalidDecl();
14365
14366 // Auto types are meaningless if we can't make sense of the initializer.
14367 if (VD->getType()->isUndeducedType()) {
14368 D->setInvalidDecl();
14369 return;
14370 }
14371
14372 QualType Ty = VD->getType();
14373 if (Ty->isDependentType()) return;
14374
14375 // Require a complete type.
14377 Context.getBaseElementType(Ty),
14378 diag::err_typecheck_decl_incomplete_type)) {
14379 VD->setInvalidDecl();
14380 return;
14381 }
14382
14383 // Require a non-abstract type.
14384 if (RequireNonAbstractType(VD->getLocation(), Ty,
14385 diag::err_abstract_type_in_decl,
14387 VD->setInvalidDecl();
14388 return;
14389 }
14390
14391 // Don't bother complaining about constructors or destructors,
14392 // though.
14393}
14394
14396 // If there is no declaration, there was an error parsing it. Just ignore it.
14397 if (!RealDecl)
14398 return;
14399
14400 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14401 QualType Type = Var->getType();
14402
14403 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14404 if (isa<DecompositionDecl>(RealDecl)) {
14405 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
14406 Var->setInvalidDecl();
14407 return;
14408 }
14409
14410 if (Type->isUndeducedType() &&
14411 DeduceVariableDeclarationType(Var, false, nullptr))
14412 return;
14413
14414 this->CheckAttributesOnDeducedType(RealDecl);
14415
14416 // C++11 [class.static.data]p3: A static data member can be declared with
14417 // the constexpr specifier; if so, its declaration shall specify
14418 // a brace-or-equal-initializer.
14419 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14420 // the definition of a variable [...] or the declaration of a static data
14421 // member.
14422 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14423 !Var->isThisDeclarationADemotedDefinition()) {
14424 if (Var->isStaticDataMember()) {
14425 // C++1z removes the relevant rule; the in-class declaration is always
14426 // a definition there.
14427 if (!getLangOpts().CPlusPlus17 &&
14428 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14429 Diag(Var->getLocation(),
14430 diag::err_constexpr_static_mem_var_requires_init)
14431 << Var;
14432 Var->setInvalidDecl();
14433 return;
14434 }
14435 } else {
14436 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14437 Var->setInvalidDecl();
14438 return;
14439 }
14440 }
14441
14442 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14443 // be initialized.
14444 if (!Var->isInvalidDecl() &&
14445 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14446 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14447 bool HasConstExprDefaultConstructor = false;
14448 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14449 for (auto *Ctor : RD->ctors()) {
14450 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14451 Ctor->getMethodQualifiers().getAddressSpace() ==
14453 HasConstExprDefaultConstructor = true;
14454 }
14455 }
14456 }
14457 if (!HasConstExprDefaultConstructor) {
14458 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14459 Var->setInvalidDecl();
14460 return;
14461 }
14462 }
14463
14464 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14465 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14466 Diag(Var->getLocation(), diag::err_specialization_const);
14467 Var->setInvalidDecl();
14468 return;
14469 }
14470
14471 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14472 if (Var->getStorageClass() == SC_Extern) {
14473 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14474 << Var;
14475 Var->setInvalidDecl();
14476 return;
14477 }
14478 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14479 diag::err_typecheck_decl_incomplete_type)) {
14480 Var->setInvalidDecl();
14481 return;
14482 }
14483 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14484 if (!RD->hasTrivialDefaultConstructor()) {
14485 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14486 Var->setInvalidDecl();
14487 return;
14488 }
14489 }
14490 // The declaration is uninitialized, no need for further checks.
14491 return;
14492 }
14493
14494 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14495 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14496 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14497 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14499 NTCUK_Init);
14500
14501 switch (DefKind) {
14503 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14504 break;
14505
14506 // We have an out-of-line definition of a static data member
14507 // that has an in-class initializer, so we type-check this like
14508 // a declaration.
14509 //
14510 [[fallthrough]];
14511
14513 // It's only a declaration.
14514
14515 // Block scope. C99 6.7p7: If an identifier for an object is
14516 // declared with no linkage (C99 6.2.2p6), the type for the
14517 // object shall be complete.
14518 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14519 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14520 RequireCompleteType(Var->getLocation(), Type,
14521 diag::err_typecheck_decl_incomplete_type))
14522 Var->setInvalidDecl();
14523
14524 // Make sure that the type is not abstract.
14525 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14526 RequireNonAbstractType(Var->getLocation(), Type,
14527 diag::err_abstract_type_in_decl,
14529 Var->setInvalidDecl();
14530 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14531 Var->getStorageClass() == SC_PrivateExtern) {
14532 Diag(Var->getLocation(), diag::warn_private_extern);
14533 Diag(Var->getLocation(), diag::note_private_extern);
14534 }
14535
14536 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14537 !Var->isInvalidDecl())
14538 ExternalDeclarations.push_back(Var);
14539
14540 return;
14541
14543 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14544 // object that has file scope without an initializer, and without a
14545 // storage-class specifier or with the storage-class specifier "static",
14546 // constitutes a tentative definition. Note: A tentative definition with
14547 // external linkage is valid (C99 6.2.2p5).
14548 if (!Var->isInvalidDecl()) {
14549 if (const IncompleteArrayType *ArrayT
14550 = Context.getAsIncompleteArrayType(Type)) {
14552 Var->getLocation(), ArrayT->getElementType(),
14553 diag::err_array_incomplete_or_sizeless_type))
14554 Var->setInvalidDecl();
14555 }
14556 if (Var->getStorageClass() == SC_Static) {
14557 // C99 6.9.2p3: If the declaration of an identifier for an object is
14558 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14559 // declared type shall not be an incomplete type.
14560 // NOTE: code such as the following
14561 // static struct s;
14562 // struct s { int a; };
14563 // is accepted by gcc. Hence here we issue a warning instead of
14564 // an error and we do not invalidate the static declaration.
14565 // NOTE: to avoid multiple warnings, only check the first declaration.
14566 if (Var->isFirstDecl())
14567 RequireCompleteType(Var->getLocation(), Type,
14568 diag::ext_typecheck_decl_incomplete_type,
14569 Type->isArrayType());
14570 }
14571 }
14572
14573 // Record the tentative definition; we're done.
14574 if (!Var->isInvalidDecl())
14575 TentativeDefinitions.push_back(Var);
14576 return;
14577 }
14578
14579 // Provide a specific diagnostic for uninitialized variable definitions
14580 // with incomplete array type, unless it is a global unbounded HLSL resource
14581 // array.
14582 if (Type->isIncompleteArrayType() &&
14583 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14585 if (Var->isConstexpr())
14586 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14587 << Var;
14588 else
14589 Diag(Var->getLocation(),
14590 diag::err_typecheck_incomplete_array_needs_initializer);
14591 Var->setInvalidDecl();
14592 return;
14593 }
14594
14595 // Provide a specific diagnostic for uninitialized variable
14596 // definitions with reference type.
14597 if (Type->isReferenceType()) {
14598 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14599 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14600 return;
14601 }
14602
14603 // Do not attempt to type-check the default initializer for a
14604 // variable with dependent type.
14605 if (Type->isDependentType())
14606 return;
14607
14608 if (Var->isInvalidDecl())
14609 return;
14610
14611 if (!Var->hasAttr<AliasAttr>()) {
14612 if (RequireCompleteType(Var->getLocation(),
14613 Context.getBaseElementType(Type),
14614 diag::err_typecheck_decl_incomplete_type)) {
14615 Var->setInvalidDecl();
14616 return;
14617 }
14618 } else {
14619 return;
14620 }
14621
14622 // The variable can not have an abstract class type.
14623 if (RequireNonAbstractType(Var->getLocation(), Type,
14624 diag::err_abstract_type_in_decl,
14626 Var->setInvalidDecl();
14627 return;
14628 }
14629
14630 // In C, if the definition is const-qualified and has no initializer, it
14631 // is left uninitialized unless it has static or thread storage duration.
14632 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14633 unsigned DiagID = diag::warn_default_init_const_unsafe;
14634 if (Var->getStorageDuration() == SD_Static ||
14635 Var->getStorageDuration() == SD_Thread)
14636 DiagID = diag::warn_default_init_const;
14637
14638 bool EmitCppCompat = !Diags.isIgnored(
14639 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14640 Var->getLocation());
14641
14642 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14643 }
14644
14645 // Check for jumps past the implicit initializer. C++0x
14646 // clarifies that this applies to a "variable with automatic
14647 // storage duration", not a "local variable".
14648 // C++11 [stmt.dcl]p3
14649 // A program that jumps from a point where a variable with automatic
14650 // storage duration is not in scope to a point where it is in scope is
14651 // ill-formed unless the variable has scalar type, class type with a
14652 // trivial default constructor and a trivial destructor, a cv-qualified
14653 // version of one of these types, or an array of one of the preceding
14654 // types and is declared without an initializer.
14655 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14656 if (const auto *CXXRecord =
14657 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14658 // Mark the function (if we're in one) for further checking even if the
14659 // looser rules of C++11 do not require such checks, so that we can
14660 // diagnose incompatibilities with C++98.
14661 if (!CXXRecord->isPOD())
14663 }
14664 }
14665 // In OpenCL, we can't initialize objects in the __local address space,
14666 // even implicitly, so don't synthesize an implicit initializer.
14667 if (getLangOpts().OpenCL &&
14668 Var->getType().getAddressSpace() == LangAS::opencl_local)
14669 return;
14670
14671 // Handle HLSL uninitialized decls
14672 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14673 return;
14674
14675 // HLSL input & push-constant variables are expected to be externally
14676 // initialized, even when marked `static`.
14677 if (getLangOpts().HLSL &&
14678 hlsl::isInitializedByPipeline(Var->getType().getAddressSpace()))
14679 return;
14680
14681 // C++03 [dcl.init]p9:
14682 // If no initializer is specified for an object, and the
14683 // object is of (possibly cv-qualified) non-POD class type (or
14684 // array thereof), the object shall be default-initialized; if
14685 // the object is of const-qualified type, the underlying class
14686 // type shall have a user-declared default
14687 // constructor. Otherwise, if no initializer is specified for
14688 // a non- static object, the object and its subobjects, if
14689 // any, have an indeterminate initial value); if the object
14690 // or any of its subobjects are of const-qualified type, the
14691 // program is ill-formed.
14692 // C++0x [dcl.init]p11:
14693 // If no initializer is specified for an object, the object is
14694 // default-initialized; [...].
14697 = InitializationKind::CreateDefault(Var->getLocation());
14698
14699 InitializationSequence InitSeq(*this, Entity, Kind, {});
14700 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14701
14702 if (Init.get()) {
14703 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14704 // This is important for template substitution.
14705 Var->setInitStyle(VarDecl::CallInit);
14706 } else if (Init.isInvalid()) {
14707 // If default-init fails, attach a recovery-expr initializer to track
14708 // that initialization was attempted and failed.
14709 auto RecoveryExpr =
14710 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14711 if (RecoveryExpr.get())
14712 Var->setInit(RecoveryExpr.get());
14713 }
14714
14716 }
14717}
14718
14720 // If there is no declaration, there was an error parsing it. Ignore it.
14721 if (!D)
14722 return;
14723
14724 VarDecl *VD = dyn_cast<VarDecl>(D);
14725 if (!VD) {
14726 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
14727 D->setInvalidDecl();
14728 return;
14729 }
14730
14731 VD->setCXXForRangeDecl(true);
14732
14733 // for-range-declaration cannot be given a storage class specifier.
14734 int Error = -1;
14735 switch (VD->getStorageClass()) {
14736 case SC_None:
14737 break;
14738 case SC_Extern:
14739 Error = 0;
14740 break;
14741 case SC_Static:
14742 Error = 1;
14743 break;
14744 case SC_PrivateExtern:
14745 Error = 2;
14746 break;
14747 case SC_Auto:
14748 Error = 3;
14749 break;
14750 case SC_Register:
14751 Error = 4;
14752 break;
14753 }
14754
14755 // for-range-declaration cannot be given a storage class specifier con't.
14756 switch (VD->getTSCSpec()) {
14757 case TSCS_thread_local:
14758 Error = 6;
14759 break;
14760 case TSCS___thread:
14761 case TSCS__Thread_local:
14762 case TSCS_unspecified:
14763 break;
14764 }
14765
14766 if (Error != -1) {
14767 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
14768 << VD << Error;
14769 D->setInvalidDecl();
14770 }
14771}
14772
14774 IdentifierInfo *Ident,
14775 ParsedAttributes &Attrs) {
14776 // C++1y [stmt.iter]p1:
14777 // A range-based for statement of the form
14778 // for ( for-range-identifier : for-range-initializer ) statement
14779 // is equivalent to
14780 // for ( auto&& for-range-identifier : for-range-initializer ) statement
14781 DeclSpec DS(Attrs.getPool().getFactory());
14782
14783 const char *PrevSpec;
14784 unsigned DiagID;
14785 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
14787
14789 D.SetIdentifier(Ident, IdentLoc);
14790 D.takeAttributesAppending(Attrs);
14791
14792 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
14793 IdentLoc);
14794 Decl *Var = ActOnDeclarator(S, D);
14795 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
14797 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
14798 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
14799 : IdentLoc);
14800}
14801
14804 return;
14805 auto *Attr = LifetimeBoundAttr::CreateImplicit(Context, MD->getLocation());
14806 QualType MethodType = MD->getType();
14807 QualType AttributedType =
14808 Context.getAttributedType(Attr, MethodType, MethodType);
14809 TypeLocBuilder TLB;
14810 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
14811 TLB.pushFullCopy(TSI->getTypeLoc());
14812 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(AttributedType);
14813 TyLoc.setAttr(Attr);
14814 MD->setType(AttributedType);
14815 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, AttributedType));
14816}
14817
14819 if (var->isInvalidDecl()) return;
14820
14822
14823 if (getLangOpts().OpenCL) {
14824 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
14825 // initialiser
14826 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
14827 !var->hasInit()) {
14828 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
14829 << 1 /*Init*/;
14830 var->setInvalidDecl();
14831 return;
14832 }
14833 }
14834
14835 // In Objective-C, don't allow jumps past the implicit initialization of a
14836 // local retaining variable.
14837 if (getLangOpts().ObjC &&
14838 var->hasLocalStorage()) {
14839 switch (var->getType().getObjCLifetime()) {
14843 break;
14844
14848 break;
14849 }
14850 }
14851
14852 if (var->hasLocalStorage() &&
14853 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
14855
14856 // Warn about externally-visible variables being defined without a
14857 // prior declaration. We only want to do this for global
14858 // declarations, but we also specifically need to avoid doing it for
14859 // class members because the linkage of an anonymous class can
14860 // change if it's later given a typedef name.
14861 if (var->isThisDeclarationADefinition() &&
14862 var->getDeclContext()->getRedeclContext()->isFileContext() &&
14863 var->isExternallyVisible() && var->hasLinkage() &&
14864 !var->isInline() && !var->getDescribedVarTemplate() &&
14865 var->getStorageClass() != SC_Register &&
14867 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
14868 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
14869 var->getLocation())) {
14870 // Find a previous declaration that's not a definition.
14871 VarDecl *prev = var->getPreviousDecl();
14872 while (prev && prev->isThisDeclarationADefinition())
14873 prev = prev->getPreviousDecl();
14874
14875 if (!prev) {
14876 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
14877 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14878 << /* variable */ 0;
14879 }
14880 }
14881
14882 // Cache the result of checking for constant initialization.
14883 std::optional<bool> CacheHasConstInit;
14884 const Expr *CacheCulprit = nullptr;
14885 auto checkConstInit = [&]() mutable {
14886 const Expr *Init = var->getInit();
14887 if (Init->isInstantiationDependent())
14888 return true;
14889
14890 if (!CacheHasConstInit)
14891 CacheHasConstInit = var->getInit()->isConstantInitializer(
14892 Context, var->getType()->isReferenceType(), &CacheCulprit);
14893 return *CacheHasConstInit;
14894 };
14895
14896 if (var->getTLSKind() == VarDecl::TLS_Static) {
14897 if (var->getType().isDestructedType()) {
14898 // GNU C++98 edits for __thread, [basic.start.term]p3:
14899 // The type of an object with thread storage duration shall not
14900 // have a non-trivial destructor.
14901 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
14903 Diag(var->getLocation(), diag::note_use_thread_local);
14904 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
14905 if (!checkConstInit()) {
14906 // GNU C++98 edits for __thread, [basic.start.init]p4:
14907 // An object of thread storage duration shall not require dynamic
14908 // initialization.
14909 // FIXME: Need strict checking here.
14910 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
14911 << CacheCulprit->getSourceRange();
14913 Diag(var->getLocation(), diag::note_use_thread_local);
14914 }
14915 }
14916 }
14917
14918
14919 if (!var->getType()->isStructureType() && var->hasInit() &&
14920 isa<InitListExpr>(var->getInit())) {
14921 const auto *ILE = cast<InitListExpr>(var->getInit());
14922 unsigned NumInits = ILE->getNumInits();
14923 if (NumInits > 2)
14924 for (unsigned I = 0; I < NumInits; ++I) {
14925 const auto *Init = ILE->getInit(I);
14926 if (!Init)
14927 break;
14928 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14929 if (!SL)
14930 break;
14931
14932 unsigned NumConcat = SL->getNumConcatenated();
14933 // Diagnose missing comma in string array initialization.
14934 // Do not warn when all the elements in the initializer are concatenated
14935 // together. Do not warn for macros too.
14936 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
14937 bool OnlyOneMissingComma = true;
14938 for (unsigned J = I + 1; J < NumInits; ++J) {
14939 const auto *Init = ILE->getInit(J);
14940 if (!Init)
14941 break;
14942 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
14943 if (!SLJ || SLJ->getNumConcatenated() > 1) {
14944 OnlyOneMissingComma = false;
14945 break;
14946 }
14947 }
14948
14949 if (OnlyOneMissingComma) {
14951 for (unsigned i = 0; i < NumConcat - 1; ++i)
14952 Hints.push_back(FixItHint::CreateInsertion(
14953 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
14954
14955 Diag(SL->getStrTokenLoc(1),
14956 diag::warn_concatenated_literal_array_init)
14957 << Hints;
14958 Diag(SL->getBeginLoc(),
14959 diag::note_concatenated_string_literal_silence);
14960 }
14961 // In any case, stop now.
14962 break;
14963 }
14964 }
14965 }
14966
14967
14968 QualType type = var->getType();
14969
14970 if (var->hasAttr<BlocksAttr>())
14972
14973 Expr *Init = var->getInit();
14974 bool GlobalStorage = var->hasGlobalStorage();
14975 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
14976 QualType baseType = Context.getBaseElementType(type);
14977 bool HasConstInit = true;
14978
14979 if (getLangOpts().C23 && var->isConstexpr() && !Init)
14980 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
14981 << var;
14982
14983 // Check whether the initializer is sufficiently constant.
14984 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
14985 !type->isDependentType() && Init && !Init->isValueDependent() &&
14986 (GlobalStorage || var->isConstexpr() ||
14987 var->mightBeUsableInConstantExpressions(Context))) {
14988 // If this variable might have a constant initializer or might be usable in
14989 // constant expressions, check whether or not it actually is now. We can't
14990 // do this lazily, because the result might depend on things that change
14991 // later, such as which constexpr functions happen to be defined.
14993 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
14994 // Prior to C++11, in contexts where a constant initializer is required,
14995 // the set of valid constant initializers is described by syntactic rules
14996 // in [expr.const]p2-6.
14997 // FIXME: Stricter checking for these rules would be useful for constinit /
14998 // -Wglobal-constructors.
14999 HasConstInit = checkConstInit();
15000
15001 // Compute and cache the constant value, and remember that we have a
15002 // constant initializer.
15003 if (HasConstInit) {
15004 if (var->isStaticDataMember() && !var->isInline() &&
15005 var->getLexicalDeclContext()->isRecord() &&
15006 type->isIntegralOrEnumerationType()) {
15007 // In C++98, in-class initialization for a static data member must
15008 // be an integer constant expression.
15009 if (!Init->isIntegerConstantExpr(Context)) {
15010 Diag(Init->getExprLoc(),
15011 diag::ext_in_class_initializer_non_constant)
15012 << Init->getSourceRange();
15013 }
15014 }
15015 (void)var->checkForConstantInitialization(Notes);
15016 Notes.clear();
15017 } else if (CacheCulprit) {
15018 Notes.emplace_back(CacheCulprit->getExprLoc(),
15019 PDiag(diag::note_invalid_subexpr_in_const_expr));
15020 Notes.back().second << CacheCulprit->getSourceRange();
15021 }
15022 } else {
15023 // Evaluate the initializer to see if it's a constant initializer.
15024 HasConstInit = var->checkForConstantInitialization(Notes);
15025 }
15026
15027 if (HasConstInit) {
15028 // FIXME: Consider replacing the initializer with a ConstantExpr.
15029 } else if (var->isConstexpr()) {
15030 SourceLocation DiagLoc = var->getLocation();
15031 // If the note doesn't add any useful information other than a source
15032 // location, fold it into the primary diagnostic.
15033 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15034 diag::note_invalid_subexpr_in_const_expr) {
15035 DiagLoc = Notes[0].first;
15036 Notes.clear();
15037 }
15038 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
15039 << var << Init->getSourceRange();
15040 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15041 Diag(Notes[I].first, Notes[I].second);
15042 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15043 auto *Attr = var->getAttr<ConstInitAttr>();
15044 Diag(var->getLocation(), diag::err_require_constant_init_failed)
15045 << Init->getSourceRange();
15046 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
15047 << Attr->getRange() << Attr->isConstinit();
15048 for (auto &it : Notes)
15049 Diag(it.first, it.second);
15050 } else if (var->isStaticDataMember() && !var->isInline() &&
15051 var->getLexicalDeclContext()->isRecord()) {
15052 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
15053 << Init->getSourceRange();
15054 for (auto &it : Notes)
15055 Diag(it.first, it.second);
15056 var->setInvalidDecl();
15057 } else if (IsGlobal &&
15058 !getDiagnostics().isIgnored(diag::warn_global_constructor,
15059 var->getLocation())) {
15060 // Warn about globals which don't have a constant initializer. Don't
15061 // warn about globals with a non-trivial destructor because we already
15062 // warned about them.
15063 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15064 if (!(RD && !RD->hasTrivialDestructor())) {
15065 // checkConstInit() here permits trivial default initialization even in
15066 // C++11 onwards, where such an initializer is not a constant initializer
15067 // but nonetheless doesn't require a global constructor.
15068 if (!checkConstInit())
15069 Diag(var->getLocation(), diag::warn_global_constructor)
15070 << Init->getSourceRange();
15071 }
15072 }
15073 }
15074
15075 // Apply section attributes and pragmas to global variables.
15076 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15078 PragmaStack<StringLiteral *> *Stack = nullptr;
15079 int SectionFlags = ASTContext::PSF_Read;
15080 bool MSVCEnv =
15081 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15082 std::optional<QualType::NonConstantStorageReason> Reason;
15083 if (HasConstInit &&
15084 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
15085 Stack = &ConstSegStack;
15086 } else {
15087 SectionFlags |= ASTContext::PSF_Write;
15088 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15089 }
15090 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15091 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15092 SectionFlags |= ASTContext::PSF_Implicit;
15093 UnifySection(SA->getName(), SectionFlags, var);
15094 } else if (Stack->CurrentValue) {
15095 if (Stack != &ConstSegStack && MSVCEnv &&
15096 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15097 var->getType().isConstQualified()) {
15098 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15099 NonConstNonReferenceType) &&
15100 "This case should've already been handled elsewhere");
15101 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15102 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15104 : *Reason);
15105 }
15106 SectionFlags |= ASTContext::PSF_Implicit;
15107 auto SectionName = Stack->CurrentValue->getString();
15108 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15109 Stack->CurrentPragmaLocation,
15110 SectionAttr::Declspec_allocate));
15111 if (UnifySection(SectionName, SectionFlags, var))
15112 var->dropAttr<SectionAttr>();
15113 }
15114
15115 // Apply the init_seg attribute if this has an initializer. If the
15116 // initializer turns out to not be dynamic, we'll end up ignoring this
15117 // attribute.
15118 if (CurInitSeg && var->getInit())
15119 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15120 CurInitSegLoc));
15121 }
15122
15123 // All the following checks are C++ only.
15124 if (!getLangOpts().CPlusPlus) {
15125 // If this variable must be emitted, add it as an initializer for the
15126 // current module.
15127 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15128 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15129 return;
15130 }
15131
15133
15134 // Require the destructor.
15135 if (!type->isDependentType())
15136 if (auto *RD = baseType->getAsCXXRecordDecl())
15138
15139 // If this variable must be emitted, add it as an initializer for the current
15140 // module.
15141 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15142 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15143
15144 // Build the bindings if this is a structured binding declaration.
15145 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15147}
15148
15150 assert(VD->isStaticLocal());
15151
15152 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15153
15154 // Find outermost function when VD is in lambda function.
15155 while (FD && !getDLLAttr(FD) &&
15156 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15157 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15158 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15159 }
15160
15161 if (!FD)
15162 return;
15163
15164 // Static locals inherit dll attributes from their function.
15165 if (Attr *A = getDLLAttr(FD)) {
15166 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15167 NewAttr->setInherited(true);
15168 VD->addAttr(NewAttr);
15169 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15170 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15171 NewAttr->setInherited(true);
15172 VD->addAttr(NewAttr);
15173
15174 // Export this function to enforce exporting this static variable even
15175 // if it is not used in this compilation unit.
15176 if (!FD->hasAttr<DLLExportAttr>())
15177 FD->addAttr(NewAttr);
15178
15179 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15180 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15181 NewAttr->setInherited(true);
15182 VD->addAttr(NewAttr);
15183 }
15184}
15185
15187 assert(VD->getTLSKind());
15188
15189 // Perform TLS alignment check here after attributes attached to the variable
15190 // which may affect the alignment have been processed. Only perform the check
15191 // if the target has a maximum TLS alignment (zero means no constraints).
15192 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15193 // Protect the check so that it's not performed on dependent types and
15194 // dependent alignments (we can't determine the alignment in that case).
15195 if (!VD->hasDependentAlignment()) {
15196 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15197 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15198 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15199 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15200 << (unsigned)MaxAlignChars.getQuantity();
15201 }
15202 }
15203 }
15204}
15205
15207 // Note that we are no longer parsing the initializer for this declaration.
15208 ParsingInitForAutoVars.erase(ThisDecl);
15209
15210 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15211 if (!VD)
15212 return;
15213
15214 // Emit any deferred warnings for the variable's initializer, even if the
15215 // variable is invalid
15216 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15217
15218 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15220 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15221 if (PragmaClangBSSSection.Valid)
15222 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15223 Context, PragmaClangBSSSection.SectionName,
15224 PragmaClangBSSSection.PragmaLocation));
15225 if (PragmaClangDataSection.Valid)
15226 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15227 Context, PragmaClangDataSection.SectionName,
15228 PragmaClangDataSection.PragmaLocation));
15229 if (PragmaClangRodataSection.Valid)
15230 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15231 Context, PragmaClangRodataSection.SectionName,
15232 PragmaClangRodataSection.PragmaLocation));
15233 if (PragmaClangRelroSection.Valid)
15234 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15235 Context, PragmaClangRelroSection.SectionName,
15236 PragmaClangRelroSection.PragmaLocation));
15237 }
15238
15239 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15240 for (auto *BD : DD->bindings()) {
15242 }
15243 }
15244
15245 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15247
15248 checkAttributesAfterMerging(*this, *VD);
15249
15250 if (VD->isStaticLocal())
15252
15253 if (VD->getTLSKind())
15255
15256 // Perform check for initializers of device-side global variables.
15257 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15258 // 7.5). We must also apply the same checks to all __shared__
15259 // variables whether they are local or not. CUDA also allows
15260 // constant initializers for __constant__ and __device__ variables.
15261 if (getLangOpts().CUDA)
15263
15264 // Grab the dllimport or dllexport attribute off of the VarDecl.
15265 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15266
15267 // Imported static data members cannot be defined out-of-line.
15268 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15269 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15271 // We allow definitions of dllimport class template static data members
15272 // with a warning.
15275 bool IsClassTemplateMember =
15277 Context->getDescribedClassTemplate();
15278
15279 Diag(VD->getLocation(),
15280 IsClassTemplateMember
15281 ? diag::warn_attribute_dllimport_static_field_definition
15282 : diag::err_attribute_dllimport_static_field_definition);
15283 Diag(IA->getLocation(), diag::note_attribute);
15284 if (!IsClassTemplateMember)
15285 VD->setInvalidDecl();
15286 }
15287 }
15288
15289 // dllimport/dllexport variables cannot be thread local, their TLS index
15290 // isn't exported with the variable.
15291 if (DLLAttr && VD->getTLSKind()) {
15292 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15293 if (F && getDLLAttr(F)) {
15294 assert(VD->isStaticLocal());
15295 // But if this is a static local in a dlimport/dllexport function, the
15296 // function will never be inlined, which means the var would never be
15297 // imported, so having it marked import/export is safe.
15298 } else {
15299 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15300 << DLLAttr;
15301 VD->setInvalidDecl();
15302 }
15303 }
15304
15305 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15306 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15307 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15308 << Attr;
15309 VD->dropAttr<UsedAttr>();
15310 }
15311 }
15312 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15313 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
15314 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15315 << Attr;
15316 VD->dropAttr<RetainAttr>();
15317 }
15318 }
15319
15320 const DeclContext *DC = VD->getDeclContext();
15321 // If there's a #pragma GCC visibility in scope, and this isn't a class
15322 // member, set the visibility of this variable.
15325
15326 // FIXME: Warn on unused var template partial specializations.
15329
15330 // Now we have parsed the initializer and can update the table of magic
15331 // tag values.
15332 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15334 return;
15335
15336 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15337 const Expr *MagicValueExpr = VD->getInit();
15338 if (!MagicValueExpr) {
15339 continue;
15340 }
15341 std::optional<llvm::APSInt> MagicValueInt;
15342 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15343 Diag(I->getRange().getBegin(),
15344 diag::err_type_tag_for_datatype_not_ice)
15345 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15346 continue;
15347 }
15348 if (MagicValueInt->getActiveBits() > 64) {
15349 Diag(I->getRange().getBegin(),
15350 diag::err_type_tag_for_datatype_too_large)
15351 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15352 continue;
15353 }
15354 uint64_t MagicValue = MagicValueInt->getZExtValue();
15355 RegisterTypeTagForDatatype(I->getArgumentKind(),
15356 MagicValue,
15357 I->getMatchingCType(),
15358 I->getLayoutCompatible(),
15359 I->getMustBeNull());
15360 }
15361}
15362
15364 auto *VD = dyn_cast<VarDecl>(DD);
15365 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15366}
15367
15369 ArrayRef<Decl *> Group) {
15371
15372 if (DS.isTypeSpecOwned())
15373 Decls.push_back(DS.getRepAsDecl());
15374
15375 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15376 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15377 bool DiagnosedMultipleDecomps = false;
15378 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15379 bool DiagnosedNonDeducedAuto = false;
15380
15381 for (Decl *D : Group) {
15382 if (!D)
15383 continue;
15384 // Check if the Decl has been declared in '#pragma omp declare target'
15385 // directive and has static storage duration.
15386 if (auto *VD = dyn_cast<VarDecl>(D);
15387 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15388 VD->hasGlobalStorage())
15390 // For declarators, there are some additional syntactic-ish checks we need
15391 // to perform.
15392 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15393 if (!FirstDeclaratorInGroup)
15394 FirstDeclaratorInGroup = DD;
15395 if (!FirstDecompDeclaratorInGroup)
15396 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15397 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15398 !hasDeducedAuto(DD))
15399 FirstNonDeducedAutoInGroup = DD;
15400
15401 if (FirstDeclaratorInGroup != DD) {
15402 // A decomposition declaration cannot be combined with any other
15403 // declaration in the same group.
15404 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15405 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15406 diag::err_decomp_decl_not_alone)
15407 << FirstDeclaratorInGroup->getSourceRange()
15408 << DD->getSourceRange();
15409 DiagnosedMultipleDecomps = true;
15410 }
15411
15412 // A declarator that uses 'auto' in any way other than to declare a
15413 // variable with a deduced type cannot be combined with any other
15414 // declarator in the same group.
15415 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15416 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15417 diag::err_auto_non_deduced_not_alone)
15418 << FirstNonDeducedAutoInGroup->getType()
15420 << FirstDeclaratorInGroup->getSourceRange()
15421 << DD->getSourceRange();
15422 DiagnosedNonDeducedAuto = true;
15423 }
15424 }
15425 }
15426
15427 Decls.push_back(D);
15428 }
15429
15431 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15432 handleTagNumbering(Tag, S);
15433 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15435 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15436 }
15437 }
15438
15439 return BuildDeclaratorGroup(Decls);
15440}
15441
15444 // C++14 [dcl.spec.auto]p7: (DR1347)
15445 // If the type that replaces the placeholder type is not the same in each
15446 // deduction, the program is ill-formed.
15447 if (Group.size() > 1) {
15448 QualType Deduced;
15449 VarDecl *DeducedDecl = nullptr;
15450 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15451 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15452 if (!D || D->isInvalidDecl())
15453 break;
15454 DeducedType *DT = D->getType()->getContainedDeducedType();
15455 if (!DT || DT->getDeducedType().isNull())
15456 continue;
15457 if (Deduced.isNull()) {
15458 Deduced = DT->getDeducedType();
15459 DeducedDecl = D;
15460 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15461 auto *AT = dyn_cast<AutoType>(DT);
15462 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15463 diag::err_auto_different_deductions)
15464 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15465 << DeducedDecl->getDeclName() << DT->getDeducedType()
15466 << D->getDeclName();
15467 if (DeducedDecl->hasInit())
15468 Dia << DeducedDecl->getInit()->getSourceRange();
15469 if (D->getInit())
15470 Dia << D->getInit()->getSourceRange();
15471 D->setInvalidDecl();
15472 break;
15473 }
15474 }
15475 }
15476
15478
15479 return DeclGroupPtrTy::make(
15480 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15481}
15482
15486
15488 // Don't parse the comment if Doxygen diagnostics are ignored.
15489 if (Group.empty() || !Group[0])
15490 return;
15491
15492 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15493 Group[0]->getLocation()) &&
15494 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15495 Group[0]->getLocation()))
15496 return;
15497
15498 if (Group.size() >= 2) {
15499 // This is a decl group. Normally it will contain only declarations
15500 // produced from declarator list. But in case we have any definitions or
15501 // additional declaration references:
15502 // 'typedef struct S {} S;'
15503 // 'typedef struct S *S;'
15504 // 'struct S *pS;'
15505 // FinalizeDeclaratorGroup adds these as separate declarations.
15506 Decl *MaybeTagDecl = Group[0];
15507 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15508 Group = Group.slice(1);
15509 }
15510 }
15511
15512 // FIXME: We assume every Decl in the group is in the same file.
15513 // This is false when preprocessor constructs the group from decls in
15514 // different files (e. g. macros or #include).
15515 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15516}
15517
15519 // Check that there are no default arguments inside the type of this
15520 // parameter.
15521 if (getLangOpts().CPlusPlus)
15523
15524 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15525 if (D.getCXXScopeSpec().isSet()) {
15526 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15527 << D.getCXXScopeSpec().getRange();
15528 }
15529
15530 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15531 // simple identifier except [...irrelevant cases...].
15532 switch (D.getName().getKind()) {
15534 break;
15535
15543 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15545 break;
15546
15549 // GetNameForDeclarator would not produce a useful name in this case.
15550 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15551 break;
15552 }
15553}
15554
15556 // This only matters in C.
15557 if (getLangOpts().CPlusPlus)
15558 return;
15559
15560 // This only matters if the declaration has a type.
15561 const auto *VD = dyn_cast<ValueDecl>(D);
15562 if (!VD)
15563 return;
15564
15565 // Get the type, this only matters for tag types.
15566 QualType QT = VD->getType();
15567 const auto *TD = QT->getAsTagDecl();
15568 if (!TD)
15569 return;
15570
15571 // Check if the tag declaration is lexically declared somewhere different
15572 // from the lexical declaration of the given object, then it will be hidden
15573 // in C++ and we should warn on it.
15574 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15575 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15576 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15577 Diag(TD->getLocation(), diag::note_declared_at);
15578 }
15579}
15580
15582 SourceLocation ExplicitThisLoc) {
15583 if (!ExplicitThisLoc.isValid())
15584 return;
15585 assert(S.getLangOpts().CPlusPlus &&
15586 "explicit parameter in non-cplusplus mode");
15587 if (!S.getLangOpts().CPlusPlus23)
15588 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15589 << P->getSourceRange();
15590
15591 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15592 // parameter pack.
15593 if (P->isParameterPack()) {
15594 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15595 << P->getSourceRange();
15596 return;
15597 }
15598 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15599 if (LambdaScopeInfo *LSI = S.getCurLambda())
15600 LSI->ExplicitObjectParameter = P;
15601}
15602
15604 SourceLocation ExplicitThisLoc) {
15605 const DeclSpec &DS = D.getDeclSpec();
15606
15607 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15608 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15609 // except for the special case of a single unnamed parameter of type void
15610 // with no storage class specifier, no type qualifier, and no following
15611 // ellipsis terminator.
15612 // Clang applies the C2y rules for 'register void' in all C language modes,
15613 // same as GCC, because it's questionable what that could possibly mean.
15614
15615 // C++03 [dcl.stc]p2 also permits 'auto'.
15616 StorageClass SC = SC_None;
15618 SC = SC_Register;
15619 // In C++11, the 'register' storage class specifier is deprecated.
15620 // In C++17, it is not allowed, but we tolerate it as an extension.
15621 if (getLangOpts().CPlusPlus11) {
15623 ? diag::ext_register_storage_class
15624 : diag::warn_deprecated_register)
15626 } else if (!getLangOpts().CPlusPlus &&
15628 D.getNumTypeObjects() == 0) {
15630 diag::err_invalid_storage_class_in_func_decl)
15633 }
15634 } else if (getLangOpts().CPlusPlus &&
15636 SC = SC_Auto;
15639 diag::err_invalid_storage_class_in_func_decl);
15641 }
15642
15644 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15646 if (DS.isInlineSpecified())
15647 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15648 << getLangOpts().CPlusPlus17;
15649 if (DS.hasConstexprSpecifier())
15650 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15651 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15652
15654
15656
15658 QualType parmDeclType = TInfo->getType();
15659
15660 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15661 const IdentifierInfo *II = D.getIdentifier();
15662 if (II) {
15665 LookupName(R, S);
15666 if (!R.empty()) {
15667 NamedDecl *PrevDecl = *R.begin();
15668 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15669 // Maybe we will complain about the shadowed template parameter.
15671 // Just pretend that we didn't see the previous declaration.
15672 PrevDecl = nullptr;
15673 }
15674 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15675 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15676 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15677 // Recover by removing the name
15678 II = nullptr;
15679 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15680 D.setInvalidType(true);
15681 }
15682 }
15683 }
15684
15685 // Incomplete resource arrays are not allowed as function parameters in HLSL
15686 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType() &&
15687 parmDeclType->isHLSLResourceRecordArray()) {
15689 diag::err_hlsl_incomplete_resource_array_in_function_param);
15690 D.setInvalidType(true);
15691 }
15692
15693 // Temporarily put parameter variables in the translation unit, not
15694 // the enclosing context. This prevents them from accidentally
15695 // looking like class members in C++.
15696 ParmVarDecl *New =
15697 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15698 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15699
15700 if (D.isInvalidType())
15701 New->setInvalidDecl();
15702
15703 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
15704
15705 assert(S->isFunctionPrototypeScope());
15706 assert(S->getFunctionPrototypeDepth() >= 1);
15707 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
15709
15711
15712 // Add the parameter declaration into this scope.
15713 S->AddDecl(New);
15714 if (II)
15715 IdResolver.AddDecl(New);
15716
15718
15720 Diag(New->getLocation(), diag::err_module_private_local)
15723
15724 if (New->hasAttr<BlocksAttr>()) {
15725 Diag(New->getLocation(), diag::err_block_on_nonlocal);
15726 }
15727
15728 if (getLangOpts().OpenCL)
15730
15731 return New;
15732}
15733
15735 SourceLocation Loc,
15736 QualType T) {
15737 /* FIXME: setting StartLoc == Loc.
15738 Would it be worth to modify callers so as to provide proper source
15739 location for the unnamed parameters, embedding the parameter's type? */
15740 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
15741 T, Context.getTrivialTypeSourceInfo(T, Loc),
15742 SC_None, nullptr);
15743 Param->setImplicit();
15744 return Param;
15745}
15746
15748 // Don't diagnose unused-parameter errors in template instantiations; we
15749 // will already have done so in the template itself.
15751 return;
15752
15753 for (const ParmVarDecl *Parameter : Parameters) {
15754 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
15755 !Parameter->hasAttr<UnusedAttr>() &&
15756 !Parameter->getIdentifier()->isPlaceholder()) {
15757 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
15758 << Parameter->getDeclName();
15759 }
15760 }
15761}
15762
15764 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
15765 if (LangOpts.NumLargeByValueCopy == 0) // No check.
15766 return;
15767
15768 // Warn if the return value is pass-by-value and larger than the specified
15769 // threshold.
15770 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
15771 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
15772 if (Size > LangOpts.NumLargeByValueCopy)
15773 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
15774 }
15775
15776 // Warn if any parameter is pass-by-value and larger than the specified
15777 // threshold.
15778 for (const ParmVarDecl *Parameter : Parameters) {
15779 QualType T = Parameter->getType();
15780 if (T->isDependentType() || !T.isPODType(Context))
15781 continue;
15782 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
15783 if (Size > LangOpts.NumLargeByValueCopy)
15784 Diag(Parameter->getLocation(), diag::warn_parameter_size)
15785 << Parameter << Size;
15786 }
15787}
15788
15790 SourceLocation NameLoc,
15791 const IdentifierInfo *Name, QualType T,
15792 TypeSourceInfo *TSInfo, StorageClass SC) {
15793 // In ARC, infer a lifetime qualifier for appropriate parameter types.
15794 if (getLangOpts().ObjCAutoRefCount &&
15795 T.getObjCLifetime() == Qualifiers::OCL_None &&
15796 T->isObjCLifetimeType()) {
15797
15798 Qualifiers::ObjCLifetime lifetime;
15799
15800 // Special cases for arrays:
15801 // - if it's const, use __unsafe_unretained
15802 // - otherwise, it's an error
15803 if (T->isArrayType()) {
15804 if (!T.isConstQualified()) {
15808 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
15809 else
15810 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
15811 << TSInfo->getTypeLoc().getSourceRange();
15812 }
15814 } else {
15815 lifetime = T->getObjCARCImplicitLifetime();
15816 }
15817 T = Context.getLifetimeQualifiedType(T, lifetime);
15818 }
15819
15820 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
15821 Context.getAdjustedParameterType(T),
15822 TSInfo, SC, nullptr);
15823
15824 // Make a note if we created a new pack in the scope of a lambda, so that
15825 // we know that references to that pack must also be expanded within the
15826 // lambda scope.
15827 if (New->isParameterPack())
15828 if (auto *CSI = getEnclosingLambdaOrBlock())
15829 CSI->LocalPacks.push_back(New);
15830
15831 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
15832 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
15833 checkNonTrivialCUnion(New->getType(), New->getLocation(),
15836
15837 // Parameter declarators cannot be interface types. All ObjC objects are
15838 // passed by reference.
15839 if (T->isObjCObjectType()) {
15840 SourceLocation TypeEndLoc =
15842 Diag(NameLoc,
15843 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
15844 << FixItHint::CreateInsertion(TypeEndLoc, "*");
15845 T = Context.getObjCObjectPointerType(T);
15846 New->setType(T);
15847 }
15848
15849 // __ptrauth is forbidden on parameters.
15850 if (T.getPointerAuth()) {
15851 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
15852 New->setInvalidDecl();
15853 }
15854
15855 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
15856 // duration shall not be qualified by an address-space qualifier."
15857 // Since all parameters have automatic store duration, they can not have
15858 // an address space.
15859 if (T.getAddressSpace() != LangAS::Default &&
15860 // OpenCL allows function arguments declared to be an array of a type
15861 // to be qualified with an address space.
15862 !(getLangOpts().OpenCL &&
15863 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
15864 // WebAssembly allows reference types as parameters. Funcref in particular
15865 // lives in a different address space.
15866 !(T->isFunctionPointerType() &&
15867 T.getAddressSpace() == LangAS::wasm_funcref) &&
15868 // HLSL allows function arguments to be qualified with an address space
15869 // if the groupshared annotation is used.
15870 !(getLangOpts().HLSL &&
15871 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
15872 Diag(NameLoc, diag::err_arg_with_address_space);
15873 New->setInvalidDecl();
15874 }
15875
15876 // PPC MMA non-pointer types are not allowed as function argument types.
15877 if (Context.getTargetInfo().getTriple().isPPC64() &&
15878 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
15879 New->setInvalidDecl();
15880 }
15881
15882 return New;
15883}
15884
15886 SourceLocation LocAfterDecls) {
15888
15889 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
15890 // in the declaration list shall have at least one declarator, those
15891 // declarators shall only declare identifiers from the identifier list, and
15892 // every identifier in the identifier list shall be declared.
15893 //
15894 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
15895 // identifiers it names shall be declared in the declaration list."
15896 //
15897 // This is why we only diagnose in C99 and later. Note, the other conditions
15898 // listed are checked elsewhere.
15899 if (!FTI.hasPrototype) {
15900 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
15901 --i;
15902 if (FTI.Params[i].Param == nullptr) {
15903 if (getLangOpts().C99) {
15904 SmallString<256> Code;
15905 llvm::raw_svector_ostream(Code)
15906 << " int " << FTI.Params[i].Ident->getName() << ";\n";
15907 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
15908 << FTI.Params[i].Ident
15909 << FixItHint::CreateInsertion(LocAfterDecls, Code);
15910 }
15911
15912 // Implicitly declare the argument as type 'int' for lack of a better
15913 // type.
15914 AttributeFactory attrs;
15915 DeclSpec DS(attrs);
15916 const char* PrevSpec; // unused
15917 unsigned DiagID; // unused
15918 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
15919 DiagID, Context.getPrintingPolicy());
15920 // Use the identifier location for the type source range.
15921 DS.SetRangeStart(FTI.Params[i].IdentLoc);
15922 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
15925 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
15926 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
15927 }
15928 }
15929 }
15930}
15931
15932Decl *
15934 MultiTemplateParamsArg TemplateParameterLists,
15935 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
15936 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
15937 assert(D.isFunctionDeclarator() && "Not a function declarator!");
15938 Scope *ParentScope = FnBodyScope->getParent();
15939
15940 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
15941 // we define a non-templated function definition, we will create a declaration
15942 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
15943 // The base function declaration will have the equivalent of an `omp declare
15944 // variant` annotation which specifies the mangled definition as a
15945 // specialization function under the OpenMP context defined as part of the
15946 // `omp begin declare variant`.
15948 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
15950 ParentScope, D, TemplateParameterLists, Bases);
15951
15953 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
15954 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
15955
15956 if (!Bases.empty())
15958 Bases);
15959
15960 return Dcl;
15961}
15962
15964 Consumer.HandleInlineFunctionDefinition(D);
15965}
15966
15968 const FunctionDecl *&PossiblePrototype) {
15969 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
15970 Prev = Prev->getPreviousDecl()) {
15971 // Ignore any declarations that occur in function or method
15972 // scope, because they aren't visible from the header.
15973 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
15974 continue;
15975
15976 PossiblePrototype = Prev;
15977 return Prev->getType()->isFunctionProtoType();
15978 }
15979 return false;
15980}
15981
15982static bool
15984 const FunctionDecl *&PossiblePrototype) {
15985 // Don't warn about invalid declarations.
15986 if (FD->isInvalidDecl())
15987 return false;
15988
15989 // Or declarations that aren't global.
15990 if (!FD->isGlobal())
15991 return false;
15992
15993 // Don't warn about C++ member functions.
15994 if (isa<CXXMethodDecl>(FD))
15995 return false;
15996
15997 // Don't warn about 'main'.
15999 if (IdentifierInfo *II = FD->getIdentifier())
16000 if (II->isStr("main") || II->isStr("efi_main"))
16001 return false;
16002
16003 if (FD->isMSVCRTEntryPoint())
16004 return false;
16005
16006 // Don't warn about inline functions.
16007 if (FD->isInlined())
16008 return false;
16009
16010 // Don't warn about function templates.
16012 return false;
16013
16014 // Don't warn about function template specializations.
16016 return false;
16017
16018 // Don't warn for OpenCL kernels.
16019 if (FD->hasAttr<DeviceKernelAttr>())
16020 return false;
16021
16022 // Don't warn on explicitly deleted functions.
16023 if (FD->isDeleted())
16024 return false;
16025
16026 // Don't warn on implicitly local functions (such as having local-typed
16027 // parameters).
16028 if (!FD->isExternallyVisible())
16029 return false;
16030
16031 // If we were able to find a potential prototype, don't warn.
16032 if (FindPossiblePrototype(FD, PossiblePrototype))
16033 return false;
16034
16035 return true;
16036}
16037
16038void
16040 const FunctionDecl *EffectiveDefinition,
16041 SkipBodyInfo *SkipBody) {
16042 const FunctionDecl *Definition = EffectiveDefinition;
16043 if (!Definition &&
16044 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16045 return;
16046
16047 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16048 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16049 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16050 // A merged copy of the same function, instantiated as a member of
16051 // the same class, is OK.
16052 if (declaresSameEntity(OrigFD, OrigDef) &&
16053 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
16055 return;
16056 }
16057 }
16058 }
16059
16061 return;
16062
16063 // Don't emit an error when this is redefinition of a typo-corrected
16064 // definition.
16066 return;
16067
16068 bool DefinitionVisible = false;
16069 if (SkipBody && isRedefinitionAllowedFor(Definition, DefinitionVisible) &&
16070 (Definition->getFormalLinkage() == Linkage::Internal ||
16071 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16072 Definition->getNumTemplateParameterLists())) {
16073 SkipBody->ShouldSkip = true;
16074 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16075 if (!DefinitionVisible) {
16076 if (auto *TD = Definition->getDescribedFunctionTemplate())
16079 }
16080 return;
16081 }
16082
16083 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16084 Definition->getStorageClass() == SC_Extern)
16085 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
16086 << FD << getLangOpts().CPlusPlus;
16087 else
16088 Diag(FD->getLocation(), diag::err_redefinition) << FD;
16089
16090 Diag(Definition->getLocation(), diag::note_previous_definition);
16091 FD->setInvalidDecl();
16092}
16093
16095 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16096
16098 LSI->CallOperator = CallOperator;
16099 LSI->Lambda = LambdaClass;
16100 LSI->ReturnType = CallOperator->getReturnType();
16101 // When this function is called in situation where the context of the call
16102 // operator is not entered, we set AfterParameterList to false, so that
16103 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16104 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16105 // where we would set the CurContext to the lambda operator before
16106 // substituting into it. In this case the flag needs to be true such that
16107 // tryCaptureVariable can correctly handle potential captures thereof.
16108 LSI->AfterParameterList = CurContext == CallOperator;
16109
16110 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16111 // used at the point of dealing with potential captures.
16112 //
16113 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16114 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16115 // associated. (Technically, we could recover that list from their
16116 // instantiation patterns, but for now, the GLTemplateParameterList seems
16117 // unnecessary in these cases.)
16118 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16119 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16120 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16121
16122 if (LCD == LCD_None)
16124 else if (LCD == LCD_ByCopy)
16126 else if (LCD == LCD_ByRef)
16128 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16129
16131 LSI->Mutable = !CallOperator->isConst();
16132 if (CallOperator->isExplicitObjectMemberFunction())
16133 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16134
16135 // Add the captures to the LSI so they can be noted as already
16136 // captured within tryCaptureVar.
16137 auto I = LambdaClass->field_begin();
16138 for (const auto &C : LambdaClass->captures()) {
16139 if (C.capturesVariable()) {
16140 ValueDecl *VD = C.getCapturedVar();
16141 if (VD->isInitCapture())
16142 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16143 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16144 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16145 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16146 /*EllipsisLoc*/C.isPackExpansion()
16147 ? C.getEllipsisLoc() : SourceLocation(),
16148 I->getType(), /*Invalid*/false);
16149
16150 } else if (C.capturesThis()) {
16151 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16152 C.getCaptureKind() == LCK_StarThis);
16153 } else {
16154 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16155 I->getType());
16156 }
16157 ++I;
16158 }
16159 return LSI;
16160}
16161
16163 SkipBodyInfo *SkipBody,
16164 FnBodyKind BodyKind) {
16165 if (!D) {
16166 // Parsing the function declaration failed in some way. Push on a fake scope
16167 // anyway so we can try to parse the function body.
16170 return D;
16171 }
16172
16173 FunctionDecl *FD = nullptr;
16174
16175 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16176 FD = FunTmpl->getTemplatedDecl();
16177 else
16178 FD = cast<FunctionDecl>(D);
16179
16180 // Do not push if it is a lambda because one is already pushed when building
16181 // the lambda in ActOnStartOfLambdaDefinition().
16182 if (!isLambdaCallOperator(FD))
16184 FD);
16185
16186 // Check for defining attributes before the check for redefinition.
16187 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16188 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16189 FD->dropAttr<AliasAttr>();
16190 FD->setInvalidDecl();
16191 }
16192 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16193 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16194 FD->dropAttr<IFuncAttr>();
16195 FD->setInvalidDecl();
16196 }
16197 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16198 if (Context.getTargetInfo().getTriple().isAArch64() &&
16199 !Context.getTargetInfo().hasFeature("fmv") &&
16200 !Attr->isDefaultVersion()) {
16201 // If function multi versioning disabled skip parsing function body
16202 // defined with non-default target_version attribute
16203 if (SkipBody)
16204 SkipBody->ShouldSkip = true;
16205 return nullptr;
16206 }
16207 }
16208
16209 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16210 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16211 Ctor->isDefaultConstructor() &&
16212 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16213 // If this is an MS ABI dllexport default constructor, instantiate any
16214 // default arguments.
16216 }
16217 }
16218
16219 // See if this is a redefinition. If 'will have body' (or similar) is already
16220 // set, then these checks were already performed when it was set.
16221 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16223 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16224
16225 // If we're skipping the body, we're done. Don't enter the scope.
16226 if (SkipBody && SkipBody->ShouldSkip)
16227 return D;
16228 }
16229
16230 // Mark this function as "will have a body eventually". This lets users to
16231 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16232 // this function.
16233 FD->setWillHaveBody();
16234
16235 // If we are instantiating a generic lambda call operator, push
16236 // a LambdaScopeInfo onto the function stack. But use the information
16237 // that's already been calculated (ActOnLambdaExpr) to prime the current
16238 // LambdaScopeInfo.
16239 // When the template operator is being specialized, the LambdaScopeInfo,
16240 // has to be properly restored so that tryCaptureVariable doesn't try
16241 // and capture any new variables. In addition when calculating potential
16242 // captures during transformation of nested lambdas, it is necessary to
16243 // have the LSI properly restored.
16245 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16246 // instantiated, explicitly specialized.
16249 Diag(FD->getLocation(), diag::err_lambda_explicit_spec);
16250 FD->setInvalidDecl();
16252 } else {
16253 assert(inTemplateInstantiation() &&
16254 "There should be an active template instantiation on the stack "
16255 "when instantiating a generic lambda!");
16257 }
16258 } else {
16259 // Enter a new function scope
16261 }
16262
16263 // Builtin functions cannot be defined.
16264 if (unsigned BuiltinID = FD->getBuiltinID()) {
16265 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16266 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16267 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16268 FD->setInvalidDecl();
16269 }
16270 }
16271
16272 // The return type of a function definition must be complete (C99 6.9.1p3).
16273 // C++23 [dcl.fct.def.general]/p2
16274 // The type of [...] the return for a function definition
16275 // shall not be a (possibly cv-qualified) class type that is incomplete
16276 // or abstract within the function body unless the function is deleted.
16277 QualType ResultType = FD->getReturnType();
16278 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16279 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16280 (RequireCompleteType(FD->getLocation(), ResultType,
16281 diag::err_func_def_incomplete_result) ||
16283 diag::err_abstract_type_in_decl,
16285 FD->setInvalidDecl();
16286
16287 if (FnBodyScope)
16288 PushDeclContext(FnBodyScope, FD);
16289
16290 // Check the validity of our function parameters
16291 if (BodyKind != FnBodyKind::Delete)
16293 /*CheckParameterNames=*/true);
16294
16295 // Add non-parameter declarations already in the function to the current
16296 // scope.
16297 if (FnBodyScope) {
16298 for (Decl *NPD : FD->decls()) {
16299 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16300 if (!NonParmDecl)
16301 continue;
16302 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16303 "parameters should not be in newly created FD yet");
16304
16305 // If the decl has a name, make it accessible in the current scope.
16306 if (NonParmDecl->getDeclName())
16307 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16308
16309 // Similarly, dive into enums and fish their constants out, making them
16310 // accessible in this scope.
16311 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16312 for (auto *EI : ED->enumerators())
16313 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16314 }
16315 }
16316 }
16317
16318 // Introduce our parameters into the function scope
16319 for (auto *Param : FD->parameters()) {
16320 Param->setOwningFunction(FD);
16321
16322 // If this has an identifier, add it to the scope stack.
16323 if (Param->getIdentifier() && FnBodyScope) {
16324 CheckShadow(FnBodyScope, Param);
16325
16326 PushOnScopeChains(Param, FnBodyScope);
16327 }
16328 }
16329
16330 // C++ [module.import/6]
16331 // ...
16332 // A header unit shall not contain a definition of a non-inline function or
16333 // variable whose name has external linkage.
16334 //
16335 // Deleted and Defaulted functions are implicitly inline (but the
16336 // inline state is not set at this point, so check the BodyKind explicitly).
16337 // We choose to allow weak & selectany definitions, as they are common in
16338 // headers, and have semantics similar to inline definitions which are allowed
16339 // in header units.
16340 // FIXME: Consider an alternate location for the test where the inlined()
16341 // state is complete.
16342 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16343 !FD->isInvalidDecl() && !FD->isInlined() &&
16344 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16345 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16346 !FD->isTemplateInstantiation() &&
16347 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16348 assert(FD->isThisDeclarationADefinition());
16349 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16350 FD->setInvalidDecl();
16351 }
16352
16353 // Ensure that the function's exception specification is instantiated.
16354 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16356
16357 // dllimport cannot be applied to non-inline function definitions.
16358 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16359 !FD->isTemplateInstantiation()) {
16360 assert(!FD->hasAttr<DLLExportAttr>());
16361 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16362 FD->setInvalidDecl();
16363 return D;
16364 }
16365
16366 // Some function attributes (like OptimizeNoneAttr) need actions before
16367 // parsing body started.
16369
16370 // We want to attach documentation to original Decl (which might be
16371 // a function template).
16373 if (getCurLexicalContext()->isObjCContainer() &&
16374 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16375 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16376 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16377
16379
16380 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16381 FnBodyScope) {
16382 // An implicit call expression is synthesized for functions declared with
16383 // the sycl_kernel_entry_point attribute. The call may resolve to a
16384 // function template, a member function template, or a call operator
16385 // of a variable template depending on the results of unqualified lookup
16386 // for 'sycl_kernel_launch' from the beginning of the function body.
16387 // Performing that lookup requires the stack of parsing scopes active
16388 // when the definition is parsed and is thus done here; the result is
16389 // cached in FunctionScopeInfo and used to synthesize the (possibly
16390 // unresolved) call expression after the function body has been parsed.
16391 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16392 if (!SKEPAttr->isInvalidAttr()) {
16393 ExprResult LaunchIdExpr =
16394 SYCL().BuildSYCLKernelLaunchIdExpr(FD, SKEPAttr->getKernelName());
16395 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16396 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16397 // treated as an error in the definition of 'FD'; treating it as an error
16398 // of the declaration would affect overload resolution which would
16399 // potentially result in additional errors. If construction of
16400 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16401 // a null pointer value below; that is expected.
16402 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16403 }
16404 }
16405
16406 return D;
16407}
16408
16410 if (!FD || FD->isInvalidDecl())
16411 return;
16412 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16413 FD = TD->getTemplatedDecl();
16414 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16417 CurFPFeatures.applyChanges(FPO);
16418 FpPragmaStack.CurrentValue =
16419 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16420 }
16421}
16422
16424 ReturnStmt **Returns = Scope->Returns.data();
16425
16426 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16427 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16428 if (!NRVOCandidate->isNRVOVariable()) {
16429 Diag(Returns[I]->getRetValue()->getExprLoc(),
16430 diag::warn_not_eliding_copy_on_return);
16431 Returns[I]->setNRVOCandidate(nullptr);
16432 }
16433 }
16434 }
16435}
16436
16438 // We can't delay parsing the body of a constexpr function template (yet).
16440 return false;
16441
16442 // We can't delay parsing the body of a function template with a deduced
16443 // return type (yet).
16444 if (D.getDeclSpec().hasAutoTypeSpec()) {
16445 // If the placeholder introduces a non-deduced trailing return type,
16446 // we can still delay parsing it.
16447 if (D.getNumTypeObjects()) {
16448 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16449 if (Outer.Kind == DeclaratorChunk::Function &&
16450 Outer.Fun.hasTrailingReturnType()) {
16451 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16452 return Ty.isNull() || !Ty->isUndeducedType();
16453 }
16454 }
16455 return false;
16456 }
16457
16458 return true;
16459}
16460
16462 // We cannot skip the body of a function (or function template) which is
16463 // constexpr, since we may need to evaluate its body in order to parse the
16464 // rest of the file.
16465 // We cannot skip the body of a function with an undeduced return type,
16466 // because any callers of that function need to know the type.
16467 if (const FunctionDecl *FD = D->getAsFunction()) {
16468 if (FD->isConstexpr())
16469 return false;
16470 // We can't simply call Type::isUndeducedType here, because inside template
16471 // auto can be deduced to a dependent type, which is not considered
16472 // "undeduced".
16473 if (FD->getReturnType()->getContainedDeducedType())
16474 return false;
16475 }
16476 return Consumer.shouldSkipFunctionBody(D);
16477}
16478
16480 if (!Decl)
16481 return nullptr;
16482 if (FunctionDecl *FD = Decl->getAsFunction())
16483 FD->setHasSkippedBody();
16484 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16485 MD->setHasSkippedBody();
16486 return Decl;
16487}
16488
16489/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16490/// body.
16492public:
16493 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16495 if (!IsLambda)
16496 S.PopExpressionEvaluationContext();
16497 }
16498
16499private:
16500 Sema &S;
16501 bool IsLambda = false;
16502};
16503
16505 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16506
16507 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16508 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16509 if (!Inserted)
16510 return It->second;
16511
16512 bool R = false;
16513 const BlockDecl *CurBD = BD;
16514
16515 do {
16516 R = !CurBD->doesNotEscape();
16517 if (R)
16518 break;
16519 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16520 } while (CurBD);
16521
16522 return It->second = R;
16523 };
16524
16525 // If the location where 'self' is implicitly retained is inside a escaping
16526 // block, emit a diagnostic.
16527 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16529 if (IsOrNestedInEscapingBlock(P.second))
16530 S.Diag(P.first, diag::warn_implicitly_retains_self)
16531 << FixItHint::CreateInsertion(P.first, "self->");
16532}
16533
16534static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16535 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16536 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16537}
16538
16540 return methodHasName(FD, "get_return_object");
16541}
16542
16544 return FD->isStatic() &&
16545 methodHasName(FD, "get_return_object_on_allocation_failure");
16546}
16547
16550 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16551 return;
16552 // Allow some_promise_type::get_return_object().
16554 return;
16555 if (!FD->hasAttr<CoroWrapperAttr>())
16556 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16557}
16558
16559Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16560 bool RetainFunctionScopeInfo) {
16562 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16563
16564 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16565 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16566
16567 SourceLocation AnalysisLoc;
16568 if (Body)
16569 AnalysisLoc = Body->getEndLoc();
16570 else if (FD)
16571 AnalysisLoc = FD->getEndLoc();
16573 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16574 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16575
16576 // If we skip function body, we can't tell if a function is a coroutine.
16577 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16578 if (FSI->isCoroutine())
16580 else
16582 }
16583
16584 // Diagnose invalid SYCL kernel entry point function declarations
16585 // and build SYCLKernelCallStmts for valid ones.
16586 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16587 SYCLKernelEntryPointAttr *SKEPAttr =
16588 FD->getAttr<SYCLKernelEntryPointAttr>();
16589 if (FD->isDefaulted()) {
16590 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16591 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16592 SKEPAttr->setInvalidAttr();
16593 } else if (FD->isDeleted()) {
16594 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16595 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16596 SKEPAttr->setInvalidAttr();
16597 } else if (FSI->isCoroutine()) {
16598 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16599 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16600 SKEPAttr->setInvalidAttr();
16601 } else if (Body && isa<CXXTryStmt>(Body)) {
16602 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16603 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16604 SKEPAttr->setInvalidAttr();
16605 }
16606
16607 // Build an unresolved SYCL kernel call statement for a function template,
16608 // validate that a SYCL kernel call statement was instantiated for an
16609 // (implicit or explicit) instantiation of a function template, or otherwise
16610 // build a (resolved) SYCL kernel call statement for a non-templated
16611 // function or an explicit specialization.
16612 if (Body && !SKEPAttr->isInvalidAttr()) {
16613 StmtResult SR;
16614 if (FD->isTemplateInstantiation()) {
16615 // The function body should already be a SYCLKernelCallStmt in this
16616 // case, but might not be if there were previous errors.
16617 SR = Body;
16618 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16619 // If name lookup for a template named sycl_kernel_launch failed
16620 // earlier, don't try to build a SYCL kernel call statement as that
16621 // would cause additional errors to be issued; just proceed with the
16622 // original function body.
16623 SR = Body;
16624 } else if (FD->isTemplated()) {
16626 cast<CompoundStmt>(Body), getCurFunction()->SYCLKernelLaunchIdExpr);
16627 } else {
16629 FD, cast<CompoundStmt>(Body),
16630 getCurFunction()->SYCLKernelLaunchIdExpr);
16631 }
16632 // If construction of the replacement body fails, just continue with the
16633 // original function body. An early error return here is not valid; the
16634 // current declaration context and function scopes must be popped before
16635 // returning.
16636 if (SR.isUsable())
16637 Body = SR.get();
16638 }
16639 }
16640
16641 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16642 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16643 if (FD->isDeletedAsWritten())
16644 Diag(SEAttr->getLocation(),
16645 diag::err_sycl_external_invalid_deleted_function)
16646 << SEAttr;
16647 }
16648
16649 {
16650 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16651 // one is already popped when finishing the lambda in BuildLambdaExpr().
16652 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16653 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16654 if (FD) {
16655 // The function body and the DefaultedOrDeletedInfo, if present, use
16656 // the same storage; don't overwrite the latter if the former is null
16657 // (the body is initialised to null anyway, so even if the latter isn't
16658 // present, this would still be a no-op).
16659 if (Body)
16660 FD->setBody(Body);
16661 FD->setWillHaveBody(false);
16662
16663 if (getLangOpts().CPlusPlus14) {
16664 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16665 FD->getReturnType()->isUndeducedType()) {
16666 // For a function with a deduced result type to return void,
16667 // the result type as written must be 'auto' or 'decltype(auto)',
16668 // possibly cv-qualified or constrained, but not ref-qualified.
16669 if (!FD->getReturnType()->getAs<AutoType>()) {
16670 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16671 << FD->getReturnType();
16672 FD->setInvalidDecl();
16673 } else {
16674 // Falling off the end of the function is the same as 'return;'.
16675 Expr *Dummy = nullptr;
16677 FD, dcl->getLocation(), Dummy,
16678 FD->getReturnType()->getAs<AutoType>()))
16679 FD->setInvalidDecl();
16680 }
16681 }
16682 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
16683 // In C++11, we don't use 'auto' deduction rules for lambda call
16684 // operators because we don't support return type deduction.
16685 auto *LSI = getCurLambda();
16686 if (LSI->HasImplicitReturnType) {
16688
16689 // C++11 [expr.prim.lambda]p4:
16690 // [...] if there are no return statements in the compound-statement
16691 // [the deduced type is] the type void
16692 QualType RetType =
16693 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
16694
16695 // Update the return type to the deduced type.
16696 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
16697 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
16698 Proto->getExtProtoInfo()));
16699 }
16700 }
16701
16702 // If the function implicitly returns zero (like 'main') or is naked,
16703 // don't complain about missing return statements.
16704 // Clang implicitly returns 0 in C89 mode, but that's considered an
16705 // extension. The check is necessary to ensure the expected extension
16706 // warning is emitted in C89 mode.
16707 if ((FD->hasImplicitReturnZero() &&
16708 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
16709 FD->hasAttr<NakedAttr>())
16711
16712 // MSVC permits the use of pure specifier (=0) on function definition,
16713 // defined at class scope, warn about this non-standard construct.
16714 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
16715 !FD->isOutOfLine())
16716 Diag(FD->getLocation(), diag::ext_pure_function_definition);
16717
16718 if (!FD->isInvalidDecl()) {
16719 // Don't diagnose unused parameters of defaulted, deleted or naked
16720 // functions.
16721 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
16722 !FD->hasAttr<NakedAttr>())
16725 FD->getReturnType(), FD);
16726
16727 // If this is a structor, we need a vtable.
16728 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
16729 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
16730 else if (CXXDestructorDecl *Destructor =
16731 dyn_cast<CXXDestructorDecl>(FD))
16732 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
16733
16734 // Try to apply the named return value optimization. We have to check
16735 // if we can do this here because lambdas keep return statements around
16736 // to deduce an implicit return type.
16737 if (FD->getReturnType()->isRecordType() &&
16739 computeNRVO(Body, FSI);
16740 }
16741
16742 // GNU warning -Wmissing-prototypes:
16743 // Warn if a global function is defined without a previous
16744 // prototype declaration. This warning is issued even if the
16745 // definition itself provides a prototype. The aim is to detect
16746 // global functions that fail to be declared in header files.
16747 const FunctionDecl *PossiblePrototype = nullptr;
16748 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
16749 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
16750
16751 if (PossiblePrototype) {
16752 // We found a declaration that is not a prototype,
16753 // but that could be a zero-parameter prototype
16754 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
16755 TypeLoc TL = TI->getTypeLoc();
16757 Diag(PossiblePrototype->getLocation(),
16758 diag::note_declaration_not_a_prototype)
16759 << (FD->getNumParams() != 0)
16761 FTL.getRParenLoc(), "void")
16762 : FixItHint{});
16763 }
16764 } else {
16765 // Returns true if the token beginning at this Loc is `const`.
16766 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
16767 const LangOptions &LangOpts) {
16768 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
16769 if (LocInfo.first.isInvalid())
16770 return false;
16771
16772 bool Invalid = false;
16773 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
16774 if (Invalid)
16775 return false;
16776
16777 if (LocInfo.second > Buffer.size())
16778 return false;
16779
16780 const char *LexStart = Buffer.data() + LocInfo.second;
16781 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
16782
16783 return StartTok.consume_front("const") &&
16784 (StartTok.empty() || isWhitespace(StartTok[0]) ||
16785 StartTok.starts_with("/*") || StartTok.starts_with("//"));
16786 };
16787
16788 auto findBeginLoc = [&]() {
16789 // If the return type has `const` qualifier, we want to insert
16790 // `static` before `const` (and not before the typename).
16791 if ((FD->getReturnType()->isAnyPointerType() &&
16794 // But only do this if we can determine where the `const` is.
16795
16796 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
16797 getLangOpts()))
16798
16799 return FD->getBeginLoc();
16800 }
16801 return FD->getTypeSpecStartLoc();
16802 };
16804 diag::note_static_for_internal_linkage)
16805 << /* function */ 1
16806 << (FD->getStorageClass() == SC_None
16807 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
16808 : FixItHint{});
16809 }
16810 }
16811
16812 // We might not have found a prototype because we didn't wish to warn on
16813 // the lack of a missing prototype. Try again without the checks for
16814 // whether we want to warn on the missing prototype.
16815 if (!PossiblePrototype)
16816 (void)FindPossiblePrototype(FD, PossiblePrototype);
16817
16818 // If the function being defined does not have a prototype, then we may
16819 // need to diagnose it as changing behavior in C23 because we now know
16820 // whether the function accepts arguments or not. This only handles the
16821 // case where the definition has no prototype but does have parameters
16822 // and either there is no previous potential prototype, or the previous
16823 // potential prototype also has no actual prototype. This handles cases
16824 // like:
16825 // void f(); void f(a) int a; {}
16826 // void g(a) int a; {}
16827 // See MergeFunctionDecl() for other cases of the behavior change
16828 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
16829 // type without a prototype.
16830 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
16831 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
16832 !PossiblePrototype->isImplicit()))) {
16833 // The function definition has parameters, so this will change behavior
16834 // in C23. If there is a possible prototype, it comes before the
16835 // function definition.
16836 // FIXME: The declaration may have already been diagnosed as being
16837 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
16838 // there's no way to test for the "changes behavior" condition in
16839 // SemaType.cpp when forming the declaration's function type. So, we do
16840 // this awkward dance instead.
16841 //
16842 // If we have a possible prototype and it declares a function with a
16843 // prototype, we don't want to diagnose it; if we have a possible
16844 // prototype and it has no prototype, it may have already been
16845 // diagnosed in SemaType.cpp as deprecated depending on whether
16846 // -Wstrict-prototypes is enabled. If we already warned about it being
16847 // deprecated, add a note that it also changes behavior. If we didn't
16848 // warn about it being deprecated (because the diagnostic is not
16849 // enabled), warn now that it is deprecated and changes behavior.
16850
16851 // This K&R C function definition definitely changes behavior in C23,
16852 // so diagnose it.
16853 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
16854 << /*definition*/ 1 << /* not supported in C23 */ 0;
16855
16856 // If we have a possible prototype for the function which is a user-
16857 // visible declaration, we already tested that it has no prototype.
16858 // This will change behavior in C23. This gets a warning rather than a
16859 // note because it's the same behavior-changing problem as with the
16860 // definition.
16861 if (PossiblePrototype)
16862 Diag(PossiblePrototype->getLocation(),
16863 diag::warn_non_prototype_changes_behavior)
16864 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
16865 << /*definition*/ 1;
16866 }
16867
16868 // Warn on CPUDispatch with an actual body.
16869 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
16870 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
16871 if (!CmpndBody->body_empty())
16872 Diag(CmpndBody->body_front()->getBeginLoc(),
16873 diag::warn_dispatch_body_ignored);
16874
16875 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
16876 const CXXMethodDecl *KeyFunction;
16877 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
16878 MD->isVirtual() &&
16879 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
16880 MD == KeyFunction->getCanonicalDecl()) {
16881 // Update the key-function state if necessary for this ABI.
16882 if (FD->isInlined() &&
16883 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
16884 Context.setNonKeyFunction(MD);
16885
16886 // If the newly-chosen key function is already defined, then we
16887 // need to mark the vtable as used retroactively.
16888 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
16889 const FunctionDecl *Definition;
16890 if (KeyFunction && KeyFunction->isDefined(Definition))
16891 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
16892 } else {
16893 // We just defined they key function; mark the vtable as used.
16894 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
16895 }
16896 }
16897 }
16898
16899 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
16900 "Function parsing confused");
16901 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
16902 assert(MD == getCurMethodDecl() && "Method parsing confused");
16903 MD->setBody(Body);
16904 if (!MD->isInvalidDecl()) {
16906 MD->getReturnType(), MD);
16907
16908 if (Body)
16909 computeNRVO(Body, FSI);
16910 }
16911 if (FSI->ObjCShouldCallSuper) {
16912 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
16913 << MD->getSelector().getAsString();
16914 FSI->ObjCShouldCallSuper = false;
16915 }
16917 const ObjCMethodDecl *InitMethod = nullptr;
16918 bool isDesignated =
16919 MD->isDesignatedInitializerForTheInterface(&InitMethod);
16920 assert(isDesignated && InitMethod);
16921 (void)isDesignated;
16922
16923 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
16924 auto IFace = MD->getClassInterface();
16925 if (!IFace)
16926 return false;
16927 auto SuperD = IFace->getSuperClass();
16928 if (!SuperD)
16929 return false;
16930 return SuperD->getIdentifier() ==
16931 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
16932 };
16933 // Don't issue this warning for unavailable inits or direct subclasses
16934 // of NSObject.
16935 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
16936 Diag(MD->getLocation(),
16937 diag::warn_objc_designated_init_missing_super_call);
16938 Diag(InitMethod->getLocation(),
16939 diag::note_objc_designated_init_marked_here);
16940 }
16942 }
16943 if (FSI->ObjCWarnForNoInitDelegation) {
16944 // Don't issue this warning for unavailable inits.
16945 if (!MD->isUnavailable())
16946 Diag(MD->getLocation(),
16947 diag::warn_objc_secondary_init_missing_init_call);
16948 FSI->ObjCWarnForNoInitDelegation = false;
16949 }
16950
16952 } else {
16953 // Parsing the function declaration failed in some way. Pop the fake scope
16954 // we pushed on.
16955 PopFunctionScopeInfo(ActivePolicy, dcl);
16956 return nullptr;
16957 }
16958
16959 if (Body && FSI->HasPotentialAvailabilityViolations)
16961
16962 assert(!FSI->ObjCShouldCallSuper &&
16963 "This should only be set for ObjC methods, which should have been "
16964 "handled in the block above.");
16965
16966 // Verify and clean out per-function state.
16967 if (Body && (!FD || !FD->isDefaulted())) {
16968 // C++ constructors that have function-try-blocks can't have return
16969 // statements in the handlers of that block. (C++ [except.handle]p14)
16970 // Verify this.
16971 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
16973
16974 // Verify that gotos and switch cases don't jump into scopes illegally.
16975 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
16977
16978 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
16979 if (!Destructor->getParent()->isDependentType())
16981
16983 Destructor->getParent());
16984 }
16985
16986 // If any errors have occurred, clear out any temporaries that may have
16987 // been leftover. This ensures that these temporaries won't be picked up
16988 // for deletion in some later function.
16991 getDiagnostics().getSuppressAllDiagnostics()) {
16993 }
16995 // Since the body is valid, issue any analysis-based warnings that are
16996 // enabled.
16997 ActivePolicy = &WP;
16998 }
16999
17000 if (!IsInstantiation && FD &&
17001 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17002 !FD->isInvalidDecl() &&
17004 FD->setInvalidDecl();
17005
17006 if (FD && FD->hasAttr<NakedAttr>()) {
17007 for (const Stmt *S : Body->children()) {
17008 // Allow local register variables without initializer as they don't
17009 // require prologue.
17010 bool RegisterVariables = false;
17011 if (auto *DS = dyn_cast<DeclStmt>(S)) {
17012 for (const auto *Decl : DS->decls()) {
17013 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
17014 RegisterVariables =
17015 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17016 if (!RegisterVariables)
17017 break;
17018 }
17019 }
17020 }
17021 if (RegisterVariables)
17022 continue;
17023 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
17024 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
17025 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
17026 FD->setInvalidDecl();
17027 break;
17028 }
17029 }
17030 }
17031
17032 assert(ExprCleanupObjects.size() ==
17033 ExprEvalContexts.back().NumCleanupObjects &&
17034 "Leftover temporaries in function");
17035 assert(!Cleanup.exprNeedsCleanups() &&
17036 "Unaccounted cleanups in function");
17037 assert(MaybeODRUseExprs.empty() &&
17038 "Leftover expressions for odr-use checking");
17039 }
17040 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17041 // the declaration context below. Otherwise, we're unable to transform
17042 // 'this' expressions when transforming immediate context functions.
17043
17044 if (FD)
17046
17047 if (!IsInstantiation)
17049
17050 if (!RetainFunctionScopeInfo)
17051 PopFunctionScopeInfo(ActivePolicy, dcl);
17052 // If any errors have occurred, clear out any temporaries that may have
17053 // been leftover. This ensures that these temporaries won't be picked up for
17054 // deletion in some later function.
17057 }
17058
17059 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17060 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17061 auto ES = getEmissionStatus(FD);
17065 }
17066
17067 if (FD && !FD->isDeleted())
17068 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
17069
17070 return dcl;
17071}
17072
17073/// When we finish delayed parsing of an attribute, we must attach it to the
17074/// relevant Decl.
17076 ParsedAttributes &Attrs) {
17077 // Always attach attributes to the underlying decl.
17078 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
17079 D = TD->getTemplatedDecl();
17080 ProcessDeclAttributeList(S, D, Attrs);
17081 ProcessAPINotes(D);
17082
17083 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
17084 if (Method->isStatic())
17086}
17087
17089 IdentifierInfo &II, Scope *S) {
17090 // It is not valid to implicitly define a function in C23.
17091 assert(LangOpts.implicitFunctionsAllowed() &&
17092 "Implicit function declarations aren't allowed in this language mode");
17093
17094 // Find the scope in which the identifier is injected and the corresponding
17095 // DeclContext.
17096 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17097 // In that case, we inject the declaration into the translation unit scope
17098 // instead.
17099 Scope *BlockScope = S;
17100 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17101 BlockScope = BlockScope->getParent();
17102
17103 // Loop until we find a DeclContext that is either a function/method or the
17104 // translation unit, which are the only two valid places to implicitly define
17105 // a function. This avoids accidentally defining the function within a tag
17106 // declaration, for example.
17107 Scope *ContextScope = BlockScope;
17108 while (!ContextScope->getEntity() ||
17109 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17110 !ContextScope->getEntity()->isTranslationUnit()))
17111 ContextScope = ContextScope->getParent();
17112 ContextRAII SavedContext(*this, ContextScope->getEntity());
17113
17114 // Before we produce a declaration for an implicitly defined
17115 // function, see whether there was a locally-scoped declaration of
17116 // this name as a function or variable. If so, use that
17117 // (non-visible) declaration, and complain about it.
17118 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
17119 if (ExternCPrev) {
17120 // We still need to inject the function into the enclosing block scope so
17121 // that later (non-call) uses can see it.
17122 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
17123
17124 // C89 footnote 38:
17125 // If in fact it is not defined as having type "function returning int",
17126 // the behavior is undefined.
17127 if (!isa<FunctionDecl>(ExternCPrev) ||
17128 !Context.typesAreCompatible(
17129 cast<FunctionDecl>(ExternCPrev)->getType(),
17130 Context.getFunctionNoProtoType(Context.IntTy))) {
17131 Diag(Loc, diag::ext_use_out_of_scope_declaration)
17132 << ExternCPrev << !getLangOpts().C99;
17133 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
17134 return ExternCPrev;
17135 }
17136 }
17137
17138 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17139 unsigned diag_id;
17140 if (II.getName().starts_with("__builtin_"))
17141 diag_id = diag::warn_builtin_unknown;
17142 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17143 else if (getLangOpts().C99)
17144 diag_id = diag::ext_implicit_function_decl_c99;
17145 else
17146 diag_id = diag::warn_implicit_function_decl;
17147
17148 TypoCorrection Corrected;
17149 // Because typo correction is expensive, only do it if the implicit
17150 // function declaration is going to be treated as an error.
17151 //
17152 // Perform the correction before issuing the main diagnostic, as some
17153 // consumers use typo-correction callbacks to enhance the main diagnostic.
17154 if (S && !ExternCPrev &&
17155 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17157 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17158 S, nullptr, CCC, CorrectTypoKind::NonError);
17159 }
17160
17161 Diag(Loc, diag_id) << &II;
17162 if (Corrected) {
17163 // If the correction is going to suggest an implicitly defined function,
17164 // skip the correction as not being a particularly good idea.
17165 bool Diagnose = true;
17166 if (const auto *D = Corrected.getCorrectionDecl())
17167 Diagnose = !D->isImplicit();
17168 if (Diagnose)
17169 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17170 /*ErrorRecovery*/ false);
17171 }
17172
17173 // If we found a prior declaration of this function, don't bother building
17174 // another one. We've already pushed that one into scope, so there's nothing
17175 // more to do.
17176 if (ExternCPrev)
17177 return ExternCPrev;
17178
17179 // Set a Declarator for the implicit definition: int foo();
17180 const char *Dummy;
17181 AttributeFactory attrFactory;
17182 DeclSpec DS(attrFactory);
17183 unsigned DiagID;
17184 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17185 Context.getPrintingPolicy());
17186 (void)Error; // Silence warning.
17187 assert(!Error && "Error setting up implicit decl!");
17188 SourceLocation NoLoc;
17190 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17191 /*IsAmbiguous=*/false,
17192 /*LParenLoc=*/NoLoc,
17193 /*Params=*/nullptr,
17194 /*NumParams=*/0,
17195 /*EllipsisLoc=*/NoLoc,
17196 /*RParenLoc=*/NoLoc,
17197 /*RefQualifierIsLvalueRef=*/true,
17198 /*RefQualifierLoc=*/NoLoc,
17199 /*MutableLoc=*/NoLoc, EST_None,
17200 /*ESpecRange=*/SourceRange(),
17201 /*Exceptions=*/nullptr,
17202 /*ExceptionRanges=*/nullptr,
17203 /*NumExceptions=*/0,
17204 /*NoexceptExpr=*/nullptr,
17205 /*ExceptionSpecTokens=*/nullptr,
17206 /*DeclsInPrototype=*/{}, Loc, Loc,
17207 D),
17208 std::move(DS.getAttributes()), SourceLocation());
17209 D.SetIdentifier(&II, Loc);
17210
17211 // Insert this function into the enclosing block scope.
17212 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17213 FD->setImplicit();
17214
17216
17217 return FD;
17218}
17219
17221 FunctionDecl *FD) {
17222 if (FD->isInvalidDecl())
17223 return;
17224
17225 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17226 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17227 return;
17228
17229 UnsignedOrNone AlignmentParam = std::nullopt;
17230 bool IsNothrow = false;
17231 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17232 return;
17233
17234 // C++2a [basic.stc.dynamic.allocation]p4:
17235 // An allocation function that has a non-throwing exception specification
17236 // indicates failure by returning a null pointer value. Any other allocation
17237 // function never returns a null pointer value and indicates failure only by
17238 // throwing an exception [...]
17239 //
17240 // However, -fcheck-new invalidates this possible assumption, so don't add
17241 // NonNull when that is enabled.
17242 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17243 !getLangOpts().CheckNew)
17244 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17245
17246 // C++2a [basic.stc.dynamic.allocation]p2:
17247 // An allocation function attempts to allocate the requested amount of
17248 // storage. [...] If the request succeeds, the value returned by a
17249 // replaceable allocation function is a [...] pointer value p0 different
17250 // from any previously returned value p1 [...]
17251 //
17252 // However, this particular information is being added in codegen,
17253 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17254
17255 // C++2a [basic.stc.dynamic.allocation]p2:
17256 // An allocation function attempts to allocate the requested amount of
17257 // storage. If it is successful, it returns the address of the start of a
17258 // block of storage whose length in bytes is at least as large as the
17259 // requested size.
17260 if (!FD->hasAttr<AllocSizeAttr>()) {
17261 FD->addAttr(AllocSizeAttr::CreateImplicit(
17262 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17263 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17264 }
17265
17266 // C++2a [basic.stc.dynamic.allocation]p3:
17267 // For an allocation function [...], the pointer returned on a successful
17268 // call shall represent the address of storage that is aligned as follows:
17269 // (3.1) If the allocation function takes an argument of type
17270 // std​::​align_­val_­t, the storage will have the alignment
17271 // specified by the value of this argument.
17272 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17273 FD->addAttr(AllocAlignAttr::CreateImplicit(
17274 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17275 }
17276
17277 // FIXME:
17278 // C++2a [basic.stc.dynamic.allocation]p3:
17279 // For an allocation function [...], the pointer returned on a successful
17280 // call shall represent the address of storage that is aligned as follows:
17281 // (3.2) Otherwise, if the allocation function is named operator new[],
17282 // the storage is aligned for any object that does not have
17283 // new-extended alignment ([basic.align]) and is no larger than the
17284 // requested size.
17285 // (3.3) Otherwise, the storage is aligned for any object that does not
17286 // have new-extended alignment and is of the requested size.
17287}
17288
17290 if (FD->isInvalidDecl())
17291 return;
17292
17293 // If this is a built-in function, map its builtin attributes to
17294 // actual attributes.
17295 if (unsigned BuiltinID = FD->getBuiltinID()) {
17296 // Handle printf-formatting attributes.
17297 unsigned FormatIdx;
17298 bool HasVAListArg;
17299 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17300 if (!FD->hasAttr<FormatAttr>()) {
17301 const char *fmt = "printf";
17302 unsigned int NumParams = FD->getNumParams();
17303 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17304 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17305 fmt = "NSString";
17306 FD->addAttr(FormatAttr::CreateImplicit(Context,
17307 &Context.Idents.get(fmt),
17308 FormatIdx+1,
17309 HasVAListArg ? 0 : FormatIdx+2,
17310 FD->getLocation()));
17311 }
17312 }
17313 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17314 HasVAListArg)) {
17315 if (!FD->hasAttr<FormatAttr>())
17316 FD->addAttr(FormatAttr::CreateImplicit(Context,
17317 &Context.Idents.get("scanf"),
17318 FormatIdx+1,
17319 HasVAListArg ? 0 : FormatIdx+2,
17320 FD->getLocation()));
17321 }
17322
17323 // Handle automatically recognized callbacks.
17324 SmallVector<int, 4> Encoding;
17325 if (!FD->hasAttr<CallbackAttr>() &&
17326 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17327 FD->addAttr(CallbackAttr::CreateImplicit(
17328 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17329
17330 // Mark const if we don't care about errno and/or floating point exceptions
17331 // that are the only thing preventing the function from being const. This
17332 // allows IRgen to use LLVM intrinsics for such functions.
17333 bool NoExceptions =
17335 bool ConstWithoutErrnoAndExceptions =
17336 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17337 bool ConstWithoutExceptions =
17338 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17339 if (!FD->hasAttr<ConstAttr>() &&
17340 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17341 (!ConstWithoutErrnoAndExceptions ||
17342 (!getLangOpts().MathErrno && NoExceptions)) &&
17343 (!ConstWithoutExceptions || NoExceptions))
17344 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17345
17346 // We make "fma" on GNU or Windows const because we know it does not set
17347 // errno in those environments even though it could set errno based on the
17348 // C standard.
17349 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17350 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17351 !FD->hasAttr<ConstAttr>()) {
17352 switch (BuiltinID) {
17353 case Builtin::BI__builtin_fma:
17354 case Builtin::BI__builtin_fmaf:
17355 case Builtin::BI__builtin_fmal:
17356 case Builtin::BIfma:
17357 case Builtin::BIfmaf:
17358 case Builtin::BIfmal:
17359 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17360 break;
17361 default:
17362 break;
17363 }
17364 }
17365
17366 SmallVector<int, 4> Indxs;
17368 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17369 !FD->hasAttr<NonNullAttr>()) {
17371 for (int I : Indxs) {
17372 ParmVarDecl *PVD = FD->getParamDecl(I);
17373 QualType T = PVD->getType();
17374 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17375 PVD->setType(T);
17376 }
17377 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17379 for (int I : Indxs)
17380 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17381 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17382 ParamIndxs.size()));
17383 }
17384 }
17385 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17386 !FD->hasAttr<ReturnsTwiceAttr>())
17387 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17388 FD->getLocation()));
17389 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17390 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17391 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17392 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17393 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17394 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17395 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17396 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17397 // Add the appropriate attribute, depending on the CUDA compilation mode
17398 // and which target the builtin belongs to. For example, during host
17399 // compilation, aux builtins are __device__, while the rest are __host__.
17400 if (getLangOpts().CUDAIsDevice !=
17401 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17402 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17403 else
17404 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17405 }
17406
17407 // Add known guaranteed alignment for allocation functions.
17408 switch (BuiltinID) {
17409 case Builtin::BImemalign:
17410 case Builtin::BIaligned_alloc:
17411 if (!FD->hasAttr<AllocAlignAttr>())
17412 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17413 FD->getLocation()));
17414 break;
17415 default:
17416 break;
17417 }
17418
17419 // Add allocsize attribute for allocation functions.
17420 switch (BuiltinID) {
17421 case Builtin::BIcalloc:
17422 FD->addAttr(AllocSizeAttr::CreateImplicit(
17423 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17424 break;
17425 case Builtin::BImemalign:
17426 case Builtin::BIaligned_alloc:
17427 case Builtin::BIrealloc:
17428 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17429 ParamIdx(), FD->getLocation()));
17430 break;
17431 case Builtin::BImalloc:
17432 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17433 ParamIdx(), FD->getLocation()));
17434 break;
17435 default:
17436 break;
17437 }
17438 }
17439
17444
17445 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17446 // throw, add an implicit nothrow attribute to any extern "C" function we come
17447 // across.
17448 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17449 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17450 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17451 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17452 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17453 }
17454
17455 IdentifierInfo *Name = FD->getIdentifier();
17456 if (!Name)
17457 return;
17460 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17462 // Okay: this could be a libc/libm/Objective-C function we know
17463 // about.
17464 } else
17465 return;
17466
17467 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17468 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17469 // target-specific builtins, perhaps?
17470 if (!FD->hasAttr<FormatAttr>())
17471 FD->addAttr(FormatAttr::CreateImplicit(Context,
17472 &Context.Idents.get("printf"), 2,
17473 Name->isStr("vasprintf") ? 0 : 3,
17474 FD->getLocation()));
17475 }
17476
17477 if (Name->isStr("__CFStringMakeConstantString")) {
17478 // We already have a __builtin___CFStringMakeConstantString,
17479 // but builds that use -fno-constant-cfstrings don't go through that.
17480 if (!FD->hasAttr<FormatArgAttr>())
17481 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17482 FD->getLocation()));
17483 }
17484}
17485
17487 TypeSourceInfo *TInfo) {
17488 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17489 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17490
17491 if (!TInfo) {
17492 assert(D.isInvalidType() && "no declarator info for valid type");
17493 TInfo = Context.getTrivialTypeSourceInfo(T);
17494 }
17495
17496 // Scope manipulation handled by caller.
17497 TypedefDecl *NewTD =
17499 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17500
17501 // Bail out immediately if we have an invalid declaration.
17502 if (D.isInvalidType()) {
17503 NewTD->setInvalidDecl();
17504 return NewTD;
17505 }
17506
17508 if (CurContext->isFunctionOrMethod())
17509 Diag(NewTD->getLocation(), diag::err_module_private_local)
17510 << 2 << NewTD
17514 else
17515 NewTD->setModulePrivate();
17516 }
17517
17518 // C++ [dcl.typedef]p8:
17519 // If the typedef declaration defines an unnamed class (or
17520 // enum), the first typedef-name declared by the declaration
17521 // to be that class type (or enum type) is used to denote the
17522 // class type (or enum type) for linkage purposes only.
17523 // We need to check whether the type was declared in the declaration.
17524 switch (D.getDeclSpec().getTypeSpecType()) {
17525 case TST_enum:
17526 case TST_struct:
17527 case TST_interface:
17528 case TST_union:
17529 case TST_class: {
17530 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17531 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17532 break;
17533 }
17534
17535 default:
17536 break;
17537 }
17538
17539 return NewTD;
17540}
17541
17543 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17544 QualType T = TI->getType();
17545
17546 if (T->isDependentType())
17547 return false;
17548
17549 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17550 // integral type; any cv-qualification is ignored.
17551 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17552 // non-atomic version of the type specified by the type specifiers in the
17553 // specifier qualifier list.
17554 // Because of how odd C's rule is, we'll let the user know that operations
17555 // involving the enumeration type will be non-atomic.
17556 if (T->isAtomicType())
17557 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17558
17559 Qualifiers Q = T.getQualifiers();
17560 std::optional<unsigned> QualSelect;
17561 if (Q.hasConst() && Q.hasVolatile())
17562 QualSelect = diag::CVQualList::Both;
17563 else if (Q.hasConst())
17564 QualSelect = diag::CVQualList::Const;
17565 else if (Q.hasVolatile())
17566 QualSelect = diag::CVQualList::Volatile;
17567
17568 if (QualSelect)
17569 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17570
17571 T = T.getAtomicUnqualifiedType();
17572
17573 // This doesn't use 'isIntegralType' despite the error message mentioning
17574 // integral type because isIntegralType would also allow enum types in C.
17575 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17576 if (BT->isInteger())
17577 return false;
17578
17579 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17580 << T << T->isBitIntType();
17581}
17582
17584 QualType EnumUnderlyingTy, bool IsFixed,
17585 const EnumDecl *Prev) {
17586 if (IsScoped != Prev->isScoped()) {
17587 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17588 << Prev->isScoped();
17589 Diag(Prev->getLocation(), diag::note_previous_declaration);
17590 return true;
17591 }
17592
17593 if (IsFixed && Prev->isFixed()) {
17594 if (!EnumUnderlyingTy->isDependentType() &&
17595 !Prev->getIntegerType()->isDependentType() &&
17596 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17597 Prev->getIntegerType())) {
17598 // TODO: Highlight the underlying type of the redeclaration.
17599 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17600 << EnumUnderlyingTy << Prev->getIntegerType();
17601 Diag(Prev->getLocation(), diag::note_previous_declaration)
17602 << Prev->getIntegerTypeRange();
17603 return true;
17604 }
17605 } else if (IsFixed != Prev->isFixed()) {
17606 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17607 << Prev->isFixed();
17608 Diag(Prev->getLocation(), diag::note_previous_declaration);
17609 return true;
17610 }
17611
17612 return false;
17613}
17614
17615/// Get diagnostic %select index for tag kind for
17616/// redeclaration diagnostic message.
17617/// WARNING: Indexes apply to particular diagnostics only!
17618///
17619/// \returns diagnostic %select index.
17621 switch (Tag) {
17623 return 0;
17625 return 1;
17626 case TagTypeKind::Class:
17627 return 2;
17628 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17629 }
17630}
17631
17632/// Determine if tag kind is a class-key compatible with
17633/// class for redeclaration (class, struct, or __interface).
17634///
17635/// \returns true iff the tag kind is compatible.
17637{
17638 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17640}
17641
17643 if (isa<TypedefDecl>(PrevDecl))
17644 return NonTagKind::Typedef;
17645 else if (isa<TypeAliasDecl>(PrevDecl))
17646 return NonTagKind::TypeAlias;
17647 else if (isa<ClassTemplateDecl>(PrevDecl))
17648 return NonTagKind::Template;
17649 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17651 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17653 switch (TTK) {
17656 case TagTypeKind::Class:
17657 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17659 case TagTypeKind::Union:
17660 return NonTagKind::NonUnion;
17661 case TagTypeKind::Enum:
17662 return NonTagKind::NonEnum;
17663 }
17664 llvm_unreachable("invalid TTK");
17665}
17666
17668 TagTypeKind NewTag, bool isDefinition,
17669 SourceLocation NewTagLoc,
17670 const IdentifierInfo *Name) {
17671 // C++ [dcl.type.elab]p3:
17672 // The class-key or enum keyword present in the
17673 // elaborated-type-specifier shall agree in kind with the
17674 // declaration to which the name in the elaborated-type-specifier
17675 // refers. This rule also applies to the form of
17676 // elaborated-type-specifier that declares a class-name or
17677 // friend class since it can be construed as referring to the
17678 // definition of the class. Thus, in any
17679 // elaborated-type-specifier, the enum keyword shall be used to
17680 // refer to an enumeration (7.2), the union class-key shall be
17681 // used to refer to a union (clause 9), and either the class or
17682 // struct class-key shall be used to refer to a class (clause 9)
17683 // declared using the class or struct class-key.
17684 TagTypeKind OldTag = Previous->getTagKind();
17685 if (OldTag != NewTag &&
17687 return false;
17688
17689 // Tags are compatible, but we might still want to warn on mismatched tags.
17690 // Non-class tags can't be mismatched at this point.
17692 return true;
17693
17694 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
17695 // by our warning analysis. We don't want to warn about mismatches with (eg)
17696 // declarations in system headers that are designed to be specialized, but if
17697 // a user asks us to warn, we should warn if their code contains mismatched
17698 // declarations.
17699 auto IsIgnoredLoc = [&](SourceLocation Loc) {
17700 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
17701 Loc);
17702 };
17703 if (IsIgnoredLoc(NewTagLoc))
17704 return true;
17705
17706 auto IsIgnored = [&](const TagDecl *Tag) {
17707 return IsIgnoredLoc(Tag->getLocation());
17708 };
17709 while (IsIgnored(Previous)) {
17710 Previous = Previous->getPreviousDecl();
17711 if (!Previous)
17712 return true;
17713 OldTag = Previous->getTagKind();
17714 }
17715
17716 bool isTemplate = false;
17717 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
17718 isTemplate = Record->getDescribedClassTemplate();
17719
17721 if (OldTag != NewTag) {
17722 // In a template instantiation, do not offer fix-its for tag mismatches
17723 // since they usually mess up the template instead of fixing the problem.
17724 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17726 << getRedeclDiagFromTagKind(OldTag);
17727 // FIXME: Note previous location?
17728 }
17729 return true;
17730 }
17731
17732 if (isDefinition) {
17733 // On definitions, check all previous tags and issue a fix-it for each
17734 // one that doesn't match the current tag.
17735 if (Previous->getDefinition()) {
17736 // Don't suggest fix-its for redefinitions.
17737 return true;
17738 }
17739
17740 bool previousMismatch = false;
17741 for (const TagDecl *I : Previous->redecls()) {
17742 if (I->getTagKind() != NewTag) {
17743 // Ignore previous declarations for which the warning was disabled.
17744 if (IsIgnored(I))
17745 continue;
17746
17747 if (!previousMismatch) {
17748 previousMismatch = true;
17749 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
17751 << getRedeclDiagFromTagKind(I->getTagKind());
17752 }
17753 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
17755 << FixItHint::CreateReplacement(I->getInnerLocStart(),
17757 }
17758 }
17759 return true;
17760 }
17761
17762 // Identify the prevailing tag kind: this is the kind of the definition (if
17763 // there is a non-ignored definition), or otherwise the kind of the prior
17764 // (non-ignored) declaration.
17765 const TagDecl *PrevDef = Previous->getDefinition();
17766 if (PrevDef && IsIgnored(PrevDef))
17767 PrevDef = nullptr;
17768 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
17769 if (Redecl->getTagKind() != NewTag) {
17770 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
17772 << getRedeclDiagFromTagKind(OldTag);
17773 Diag(Redecl->getLocation(), diag::note_previous_use);
17774
17775 // If there is a previous definition, suggest a fix-it.
17776 if (PrevDef) {
17777 Diag(NewTagLoc, diag::note_struct_class_suggestion)
17781 }
17782 }
17783
17784 return true;
17785}
17786
17787/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
17788/// from an outer enclosing namespace or file scope inside a friend declaration.
17789/// This should provide the commented out code in the following snippet:
17790/// namespace N {
17791/// struct X;
17792/// namespace M {
17793/// struct Y { friend struct /*N::*/ X; };
17794/// }
17795/// }
17797 SourceLocation NameLoc) {
17798 // While the decl is in a namespace, do repeated lookup of that name and see
17799 // if we get the same namespace back. If we do not, continue until
17800 // translation unit scope, at which point we have a fully qualified NNS.
17803 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
17804 // This tag should be declared in a namespace, which can only be enclosed by
17805 // other namespaces. Bail if there's an anonymous namespace in the chain.
17806 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
17807 if (!Namespace || Namespace->isAnonymousNamespace())
17808 return FixItHint();
17809 IdentifierInfo *II = Namespace->getIdentifier();
17810 Namespaces.push_back(II);
17811 NamedDecl *Lookup = SemaRef.LookupSingleName(
17812 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
17813 if (Lookup == Namespace)
17814 break;
17815 }
17816
17817 // Once we have all the namespaces, reverse them to go outermost first, and
17818 // build an NNS.
17819 SmallString<64> Insertion;
17820 llvm::raw_svector_ostream OS(Insertion);
17821 if (DC->isTranslationUnit())
17822 OS << "::";
17823 std::reverse(Namespaces.begin(), Namespaces.end());
17824 for (auto *II : Namespaces)
17825 OS << II->getName() << "::";
17826 return FixItHint::CreateInsertion(NameLoc, Insertion);
17827}
17828
17829/// Determine whether a tag originally declared in context \p OldDC can
17830/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
17831/// found a declaration in \p OldDC as a previous decl, perhaps through a
17832/// using-declaration).
17834 DeclContext *NewDC) {
17835 OldDC = OldDC->getRedeclContext();
17836 NewDC = NewDC->getRedeclContext();
17837
17838 if (OldDC->Equals(NewDC))
17839 return true;
17840
17841 // In MSVC mode, we allow a redeclaration if the contexts are related (either
17842 // encloses the other).
17843 if (S.getLangOpts().MSVCCompat &&
17844 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
17845 return true;
17846
17847 return false;
17848}
17849
17851Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
17852 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17853 const ParsedAttributesView &Attrs, AccessSpecifier AS,
17854 SourceLocation ModulePrivateLoc,
17855 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
17856 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
17857 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
17858 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
17859 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
17860 // If this is not a definition, it must have a name.
17861 IdentifierInfo *OrigName = Name;
17862 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
17863 "Nameless record must be a definition!");
17864 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
17865
17866 OwnedDecl = false;
17868 bool ScopedEnum = ScopedEnumKWLoc.isValid();
17869
17870 // FIXME: Check member specializations more carefully.
17871 bool isMemberSpecialization = false;
17872 bool IsInjectedClassName = false;
17873 bool Invalid = false;
17874
17875 // We only need to do this matching if we have template parameters
17876 // or a scope specifier, which also conveniently avoids this work
17877 // for non-C++ cases.
17878 if (TemplateParameterLists.size() > 0 ||
17879 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
17880 TemplateParameterList *TemplateParams =
17882 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
17883 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
17884
17885 // C++23 [dcl.type.elab] p2:
17886 // If an elaborated-type-specifier is the sole constituent of a
17887 // declaration, the declaration is ill-formed unless it is an explicit
17888 // specialization, an explicit instantiation or it has one of the
17889 // following forms: [...]
17890 // C++23 [dcl.enum] p1:
17891 // If the enum-head-name of an opaque-enum-declaration contains a
17892 // nested-name-specifier, the declaration shall be an explicit
17893 // specialization.
17894 //
17895 // FIXME: Class template partial specializations can be forward declared
17896 // per CWG2213, but the resolution failed to allow qualified forward
17897 // declarations. This is almost certainly unintentional, so we allow them.
17898 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
17899 !isMemberSpecialization)
17900 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
17902
17903 if (TemplateParams) {
17904 if (Kind == TagTypeKind::Enum) {
17905 Diag(KWLoc, diag::err_enum_template);
17906 return true;
17907 }
17908
17909 if (TemplateParams->size() > 0) {
17910 // This is a declaration or definition of a class template (which may
17911 // be a member of another template).
17912
17913 if (Invalid)
17914 return true;
17915
17916 OwnedDecl = false;
17918 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
17919 AS, ModulePrivateLoc,
17920 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
17921 TemplateParameterLists.data(), SkipBody);
17922 return Result.get();
17923 } else {
17924 // The "template<>" header is extraneous.
17925 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17926 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17927 isMemberSpecialization = true;
17928 }
17929 }
17930
17931 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
17932 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
17933 return true;
17934 }
17935
17936 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
17937 // C++23 [dcl.type.elab]p4:
17938 // If an elaborated-type-specifier appears with the friend specifier as
17939 // an entire member-declaration, the member-declaration shall have one
17940 // of the following forms:
17941 // friend class-key nested-name-specifier(opt) identifier ;
17942 // friend class-key simple-template-id ;
17943 // friend class-key nested-name-specifier template(opt)
17944 // simple-template-id ;
17945 //
17946 // Since enum is not a class-key, so declarations like "friend enum E;"
17947 // are ill-formed. Although CWG2363 reaffirms that such declarations are
17948 // invalid, most implementations accept so we issue a pedantic warning.
17949 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
17950 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
17951 assert(ScopedEnum || !ScopedEnumUsesClassTag);
17952 Diag(KWLoc, diag::note_enum_friend)
17953 << (ScopedEnum + ScopedEnumUsesClassTag);
17954 }
17955
17956 // Figure out the underlying type if this a enum declaration. We need to do
17957 // this early, because it's needed to detect if this is an incompatible
17958 // redeclaration.
17959 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
17960 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
17961
17962 if (Kind == TagTypeKind::Enum) {
17963 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
17964 // No underlying type explicitly specified, or we failed to parse the
17965 // type, default to int.
17966 EnumUnderlying = Context.IntTy.getTypePtr();
17967 } else if (UnderlyingType.get()) {
17968 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17969 // integral type; any cv-qualification is ignored.
17970 // C23 6.7.3.3p5: The underlying type of the enumeration is the
17971 // unqualified, non-atomic version of the type specified by the type
17972 // specifiers in the specifier qualifier list.
17973 TypeSourceInfo *TI = nullptr;
17974 GetTypeFromParser(UnderlyingType.get(), &TI);
17975 EnumUnderlying = TI;
17976
17978 // Recover by falling back to int.
17979 EnumUnderlying = Context.IntTy.getTypePtr();
17980
17983 EnumUnderlying = Context.IntTy.getTypePtr();
17984
17985 // If the underlying type is atomic, we need to adjust the type before
17986 // continuing. This only happens in the case we stored a TypeSourceInfo
17987 // into EnumUnderlying because the other cases are error recovery up to
17988 // this point. But because it's not possible to gin up a TypeSourceInfo
17989 // for a non-atomic type from an atomic one, we'll store into the Type
17990 // field instead. FIXME: it would be nice to have an easy way to get a
17991 // derived TypeSourceInfo which strips qualifiers including the weird
17992 // ones like _Atomic where it forms a different type.
17993 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
17994 TI && TI->getType()->isAtomicType())
17995 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
17996
17997 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
17998 // For MSVC ABI compatibility, unfixed enums must use an underlying type
17999 // of 'int'. However, if this is an unfixed forward declaration, don't set
18000 // the underlying type unless the user enables -fms-compatibility. This
18001 // makes unfixed forward declared enums incomplete and is more conforming.
18002 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18003 EnumUnderlying = Context.IntTy.getTypePtr();
18004 }
18005 }
18006
18007 DeclContext *SearchDC = CurContext;
18008 DeclContext *DC = CurContext;
18009 bool isStdBadAlloc = false;
18010 bool isStdAlignValT = false;
18011
18013 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18015
18016 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18017 /// implemented asks for structural equivalence checking, the returned decl
18018 /// here is passed back to the parser, allowing the tag body to be parsed.
18019 auto createTagFromNewDecl = [&]() -> TagDecl * {
18020 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18021 // If there is an identifier, use the location of the identifier as the
18022 // location of the decl, otherwise use the location of the struct/union
18023 // keyword.
18024 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18025 TagDecl *New = nullptr;
18026
18027 if (Kind == TagTypeKind::Enum) {
18028 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
18029 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
18030 // If this is an undefined enum, bail.
18031 if (TUK != TagUseKind::Definition && !Invalid)
18032 return nullptr;
18033 if (EnumUnderlying) {
18035 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18037 else
18038 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18039 QualType EnumTy = ED->getIntegerType();
18040 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18041 ? Context.getPromotedIntegerType(EnumTy)
18042 : EnumTy);
18043 }
18044 } else { // struct/union
18045 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18046 nullptr);
18047 }
18048
18049 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18050 // Add alignment attributes if necessary; these attributes are checked
18051 // when the ASTContext lays out the structure.
18052 //
18053 // It is important for implementing the correct semantics that this
18054 // happen here (in ActOnTag). The #pragma pack stack is
18055 // maintained as a result of parser callbacks which can occur at
18056 // many points during the parsing of a struct declaration (because
18057 // the #pragma tokens are effectively skipped over during the
18058 // parsing of the struct).
18059 if (TUK == TagUseKind::Definition &&
18060 (!SkipBody || !SkipBody->ShouldSkip)) {
18061 if (LangOpts.HLSL)
18062 RD->addAttr(PackedAttr::CreateImplicit(Context));
18065 }
18066 }
18067 New->setLexicalDeclContext(CurContext);
18068 return New;
18069 };
18070
18071 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18072 if (Name && SS.isNotEmpty()) {
18073 // We have a nested-name tag ('struct foo::bar').
18074
18075 // Check for invalid 'foo::'.
18076 if (SS.isInvalid()) {
18077 Name = nullptr;
18078 goto CreateNewDecl;
18079 }
18080
18081 // If this is a friend or a reference to a class in a dependent
18082 // context, don't try to make a decl for it.
18083 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18084 DC = computeDeclContext(SS, false);
18085 if (!DC) {
18086 IsDependent = true;
18087 return true;
18088 }
18089 } else {
18090 DC = computeDeclContext(SS, true);
18091 if (!DC) {
18092 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
18093 << SS.getRange();
18094 return true;
18095 }
18096 }
18097
18098 if (RequireCompleteDeclContext(SS, DC))
18099 return true;
18100
18101 SearchDC = DC;
18102 // Look-up name inside 'foo::'.
18104
18105 if (Previous.isAmbiguous())
18106 return true;
18107
18108 if (Previous.empty()) {
18109 // Name lookup did not find anything. However, if the
18110 // nested-name-specifier refers to the current instantiation,
18111 // and that current instantiation has any dependent base
18112 // classes, we might find something at instantiation time: treat
18113 // this as a dependent elaborated-type-specifier.
18114 // But this only makes any sense for reference-like lookups.
18115 if (Previous.wasNotFoundInCurrentInstantiation() &&
18116 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18117 IsDependent = true;
18118 return true;
18119 }
18120
18121 // A tag 'foo::bar' must already exist.
18122 Diag(NameLoc, diag::err_not_tag_in_scope)
18123 << Kind << Name << DC << SS.getRange();
18124 Name = nullptr;
18125 Invalid = true;
18126 goto CreateNewDecl;
18127 }
18128 } else if (Name) {
18129 // C++14 [class.mem]p14:
18130 // If T is the name of a class, then each of the following shall have a
18131 // name different from T:
18132 // -- every member of class T that is itself a type
18133 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18134 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
18135 return true;
18136
18137 // If this is a named struct, check to see if there was a previous forward
18138 // declaration or definition.
18139 // FIXME: We're looking into outer scopes here, even when we
18140 // shouldn't be. Doing so can result in ambiguities that we
18141 // shouldn't be diagnosing.
18142 LookupName(Previous, S);
18143
18144 // When declaring or defining a tag, ignore ambiguities introduced
18145 // by types using'ed into this scope.
18146 if (Previous.isAmbiguous() &&
18148 LookupResult::Filter F = Previous.makeFilter();
18149 while (F.hasNext()) {
18150 NamedDecl *ND = F.next();
18151 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18152 SearchDC->getRedeclContext()))
18153 F.erase();
18154 }
18155 F.done();
18156 }
18157
18158 // C++11 [namespace.memdef]p3:
18159 // If the name in a friend declaration is neither qualified nor
18160 // a template-id and the declaration is a function or an
18161 // elaborated-type-specifier, the lookup to determine whether
18162 // the entity has been previously declared shall not consider
18163 // any scopes outside the innermost enclosing namespace.
18164 //
18165 // MSVC doesn't implement the above rule for types, so a friend tag
18166 // declaration may be a redeclaration of a type declared in an enclosing
18167 // scope. They do implement this rule for friend functions.
18168 //
18169 // Does it matter that this should be by scope instead of by
18170 // semantic context?
18171 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18172 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18173 LookupResult::Filter F = Previous.makeFilter();
18174 bool FriendSawTagOutsideEnclosingNamespace = false;
18175 while (F.hasNext()) {
18176 NamedDecl *ND = F.next();
18178 if (DC->isFileContext() &&
18179 !EnclosingNS->Encloses(ND->getDeclContext())) {
18180 if (getLangOpts().MSVCCompat)
18181 FriendSawTagOutsideEnclosingNamespace = true;
18182 else
18183 F.erase();
18184 }
18185 }
18186 F.done();
18187
18188 // Diagnose this MSVC extension in the easy case where lookup would have
18189 // unambiguously found something outside the enclosing namespace.
18190 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18191 NamedDecl *ND = Previous.getFoundDecl();
18192 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18193 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18194 }
18195 }
18196
18197 // Note: there used to be some attempt at recovery here.
18198 if (Previous.isAmbiguous())
18199 return true;
18200
18201 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18202 // FIXME: This makes sure that we ignore the contexts associated
18203 // with C structs, unions, and enums when looking for a matching
18204 // tag declaration or definition. See the similar lookup tweak
18205 // in Sema::LookupName; is there a better way to deal with this?
18207 SearchDC = SearchDC->getParent();
18208 } else if (getLangOpts().CPlusPlus) {
18209 // Inside ObjCContainer want to keep it as a lexical decl context but go
18210 // past it (most often to TranslationUnit) to find the semantic decl
18211 // context.
18212 while (isa<ObjCContainerDecl>(SearchDC))
18213 SearchDC = SearchDC->getParent();
18214 }
18215 } else if (getLangOpts().CPlusPlus) {
18216 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18217 // TagDecl the same way as we skip it for named TagDecl.
18218 while (isa<ObjCContainerDecl>(SearchDC))
18219 SearchDC = SearchDC->getParent();
18220 }
18221
18222 if (Previous.isSingleResult() &&
18223 Previous.getFoundDecl()->isTemplateParameter()) {
18224 // Maybe we will complain about the shadowed template parameter.
18225 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18226 // Just pretend that we didn't see the previous declaration.
18227 Previous.clear();
18228 }
18229
18230 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18231 DC->Equals(getStdNamespace())) {
18232 if (Name->isStr("bad_alloc")) {
18233 // This is a declaration of or a reference to "std::bad_alloc".
18234 isStdBadAlloc = true;
18235
18236 // If std::bad_alloc has been implicitly declared (but made invisible to
18237 // name lookup), fill in this implicit declaration as the previous
18238 // declaration, so that the declarations get chained appropriately.
18239 if (Previous.empty() && StdBadAlloc)
18240 Previous.addDecl(getStdBadAlloc());
18241 } else if (Name->isStr("align_val_t")) {
18242 isStdAlignValT = true;
18243 if (Previous.empty() && StdAlignValT)
18244 Previous.addDecl(getStdAlignValT());
18245 }
18246 }
18247
18248 // If we didn't find a previous declaration, and this is a reference
18249 // (or friend reference), move to the correct scope. In C++, we
18250 // also need to do a redeclaration lookup there, just in case
18251 // there's a shadow friend decl.
18252 if (Name && Previous.empty() &&
18253 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18254 IsTemplateParamOrArg)) {
18255 if (Invalid) goto CreateNewDecl;
18256 assert(SS.isEmpty());
18257
18258 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18259 // C++ [basic.scope.pdecl]p5:
18260 // -- for an elaborated-type-specifier of the form
18261 //
18262 // class-key identifier
18263 //
18264 // if the elaborated-type-specifier is used in the
18265 // decl-specifier-seq or parameter-declaration-clause of a
18266 // function defined in namespace scope, the identifier is
18267 // declared as a class-name in the namespace that contains
18268 // the declaration; otherwise, except as a friend
18269 // declaration, the identifier is declared in the smallest
18270 // non-class, non-function-prototype scope that contains the
18271 // declaration.
18272 //
18273 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18274 // C structs and unions.
18275 //
18276 // It is an error in C++ to declare (rather than define) an enum
18277 // type, including via an elaborated type specifier. We'll
18278 // diagnose that later; for now, declare the enum in the same
18279 // scope as we would have picked for any other tag type.
18280 //
18281 // GNU C also supports this behavior as part of its incomplete
18282 // enum types extension, while GNU C++ does not.
18283 //
18284 // Find the context where we'll be declaring the tag.
18285 // FIXME: We would like to maintain the current DeclContext as the
18286 // lexical context,
18287 SearchDC = getTagInjectionContext(SearchDC);
18288
18289 // Find the scope where we'll be declaring the tag.
18291 } else {
18292 assert(TUK == TagUseKind::Friend);
18293 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18294
18295 // C++ [namespace.memdef]p3:
18296 // If a friend declaration in a non-local class first declares a
18297 // class or function, the friend class or function is a member of
18298 // the innermost enclosing namespace.
18299 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18300 : SearchDC->getEnclosingNamespaceContext();
18301 }
18302
18303 // In C++, we need to do a redeclaration lookup to properly
18304 // diagnose some problems.
18305 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18306 // hidden declaration so that we don't get ambiguity errors when using a
18307 // type declared by an elaborated-type-specifier. In C that is not correct
18308 // and we should instead merge compatible types found by lookup.
18309 if (getLangOpts().CPlusPlus) {
18310 // FIXME: This can perform qualified lookups into function contexts,
18311 // which are meaningless.
18312 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18313 LookupQualifiedName(Previous, SearchDC);
18314 } else {
18315 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18316 LookupName(Previous, S);
18317 }
18318 }
18319
18320 // If we have a known previous declaration to use, then use it.
18321 if (Previous.empty() && SkipBody && SkipBody->Previous)
18322 Previous.addDecl(SkipBody->Previous);
18323
18324 if (!Previous.empty()) {
18325 NamedDecl *PrevDecl = Previous.getFoundDecl();
18326 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18327
18328 // It's okay to have a tag decl in the same scope as a typedef
18329 // which hides a tag decl in the same scope. Finding this
18330 // with a redeclaration lookup can only actually happen in C++.
18331 //
18332 // This is also okay for elaborated-type-specifiers, which is
18333 // technically forbidden by the current standard but which is
18334 // okay according to the likely resolution of an open issue;
18335 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18336 if (getLangOpts().CPlusPlus) {
18337 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18338 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18339 if (Tag->getDeclName() == Name &&
18340 Tag->getDeclContext()->getRedeclContext()
18341 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18342 PrevDecl = Tag;
18343 Previous.clear();
18344 Previous.addDecl(Tag);
18345 Previous.resolveKind();
18346 }
18347 }
18348 } else if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18349 TUK == TagUseKind::Reference && RD &&
18350 RD->isInjectedClassName()) {
18351 // If lookup found the injected class name, the previous declaration is
18352 // the class being injected into.
18353 PrevDecl = cast<TagDecl>(RD->getDeclContext());
18354 Previous.clear();
18355 Previous.addDecl(PrevDecl);
18356 Previous.resolveKind();
18357 IsInjectedClassName = true;
18358 }
18359 }
18360
18361 // If this is a redeclaration of a using shadow declaration, it must
18362 // declare a tag in the same context. In MSVC mode, we allow a
18363 // redefinition if either context is within the other.
18364 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18365 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18366 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18367 TUK != TagUseKind::Friend &&
18368 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18369 !(OldTag && isAcceptableTagRedeclContext(
18370 *this, OldTag->getDeclContext(), SearchDC))) {
18371 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18372 Diag(Shadow->getTargetDecl()->getLocation(),
18373 diag::note_using_decl_target);
18374 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18375 << 0;
18376 // Recover by ignoring the old declaration.
18377 Previous.clear();
18378 goto CreateNewDecl;
18379 }
18380 }
18381
18382 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18383 // If this is a use of a previous tag, or if the tag is already declared
18384 // in the same scope (so that the definition/declaration completes or
18385 // rementions the tag), reuse the decl.
18386 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18387 isDeclInScope(DirectPrevDecl, SearchDC, S,
18388 SS.isNotEmpty() || isMemberSpecialization)) {
18389 // Make sure that this wasn't declared as an enum and now used as a
18390 // struct or something similar.
18391 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18392 TUK == TagUseKind::Definition, KWLoc,
18393 Name)) {
18394 bool SafeToContinue =
18395 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18396 Kind != TagTypeKind::Enum);
18397 if (SafeToContinue)
18398 Diag(KWLoc, diag::err_use_with_wrong_tag)
18399 << Name
18401 PrevTagDecl->getKindName());
18402 else
18403 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18404 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18405
18406 if (SafeToContinue)
18407 Kind = PrevTagDecl->getTagKind();
18408 else {
18409 // Recover by making this an anonymous redefinition.
18410 Name = nullptr;
18411 Previous.clear();
18412 Invalid = true;
18413 }
18414 }
18415
18416 if (Kind == TagTypeKind::Enum &&
18417 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18418 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18419 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18420 return PrevTagDecl;
18421
18422 QualType EnumUnderlyingTy;
18423 if (TypeSourceInfo *TI =
18424 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18425 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18426 else if (const Type *T =
18427 dyn_cast_if_present<const Type *>(EnumUnderlying))
18428 EnumUnderlyingTy = QualType(T, 0);
18429
18430 // All conflicts with previous declarations are recovered by
18431 // returning the previous declaration, unless this is a definition,
18432 // in which case we want the caller to bail out.
18433 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18434 ScopedEnum, EnumUnderlyingTy,
18435 IsFixed, PrevEnum))
18436 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18437 }
18438
18439 // C++11 [class.mem]p1:
18440 // A member shall not be declared twice in the member-specification,
18441 // except that a nested class or member class template can be declared
18442 // and then later defined.
18443 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18444 S->isDeclScope(PrevDecl)) {
18445 Diag(NameLoc, diag::ext_member_redeclared);
18446 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18447 }
18448
18449 if (!Invalid) {
18450 // If this is a use, just return the declaration we found, unless
18451 // we have attributes.
18452 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18453 if (!Attrs.empty()) {
18454 // FIXME: Diagnose these attributes. For now, we create a new
18455 // declaration to hold them.
18456 } else if (TUK == TagUseKind::Reference &&
18457 (PrevTagDecl->getFriendObjectKind() ==
18459 PrevDecl->getOwningModule() != getCurrentModule()) &&
18460 SS.isEmpty()) {
18461 // This declaration is a reference to an existing entity, but
18462 // has different visibility from that entity: it either makes
18463 // a friend visible or it makes a type visible in a new module.
18464 // In either case, create a new declaration. We only do this if
18465 // the declaration would have meant the same thing if no prior
18466 // declaration were found, that is, if it was found in the same
18467 // scope where we would have injected a declaration.
18468 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18469 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18470 return PrevTagDecl;
18471 // This is in the injected scope, create a new declaration in
18472 // that scope.
18474 } else {
18475 return PrevTagDecl;
18476 }
18477 }
18478
18479 // Diagnose attempts to redefine a tag.
18480 if (TUK == TagUseKind::Definition) {
18481 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18482 // If the type is currently being defined, complain
18483 // about a nested redefinition.
18484 if (Def->isBeingDefined()) {
18485 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18486 Diag(PrevTagDecl->getLocation(),
18487 diag::note_previous_definition);
18488 Name = nullptr;
18489 Previous.clear();
18490 Invalid = true;
18491 } else {
18492 // If we're defining a specialization and the previous
18493 // definition is from an implicit instantiation, don't emit an
18494 // error here; we'll catch this in the general case below.
18495 bool IsExplicitSpecializationAfterInstantiation = false;
18496 if (isMemberSpecialization) {
18497 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18498 IsExplicitSpecializationAfterInstantiation =
18499 RD->getTemplateSpecializationKind() !=
18501 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18502 IsExplicitSpecializationAfterInstantiation =
18503 ED->getTemplateSpecializationKind() !=
18505 }
18506
18507 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18508 // do not keep more that one definition around (merge them).
18509 // However, ensure the decl passes the structural compatibility
18510 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18511 NamedDecl *Hidden = nullptr;
18512 bool HiddenDefVisible = false;
18513 if (SkipBody &&
18514 (isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible) ||
18515 getLangOpts().C23)) {
18516 // There is a definition of this tag, but it is not visible.
18517 // We explicitly make use of C++'s one definition rule here,
18518 // and assume that this definition is identical to the hidden
18519 // one we already have. Make the existing definition visible
18520 // and use it in place of this one.
18521 if (!getLangOpts().CPlusPlus) {
18522 // Postpone making the old definition visible until after we
18523 // complete parsing the new one and do the structural
18524 // comparison.
18525 SkipBody->CheckSameAsPrevious = true;
18526 SkipBody->New = createTagFromNewDecl();
18527 SkipBody->Previous = Def;
18528
18529 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18530 return Def;
18531 }
18532
18533 SkipBody->ShouldSkip = true;
18534 SkipBody->Previous = Def;
18535 if (!HiddenDefVisible && Hidden)
18537 // Carry on and handle it like a normal definition. We'll
18538 // skip starting the definition later.
18539
18540 } else if (!IsExplicitSpecializationAfterInstantiation) {
18541 // A redeclaration in function prototype scope in C isn't
18542 // visible elsewhere, so merely issue a warning.
18543 if (!getLangOpts().CPlusPlus &&
18545 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18546 << Name;
18547 else
18548 Diag(NameLoc, diag::err_redefinition) << Name;
18550 NameLoc.isValid() ? NameLoc : KWLoc);
18551 // If this is a redefinition, recover by making this
18552 // struct be anonymous, which will make any later
18553 // references get the previous definition.
18554 Name = nullptr;
18555 Previous.clear();
18556 Invalid = true;
18557 }
18558 }
18559 }
18560
18561 // Okay, this is definition of a previously declared or referenced
18562 // tag. We're going to create a new Decl for it.
18563 }
18564
18565 // Okay, we're going to make a redeclaration. If this is some kind
18566 // of reference, make sure we build the redeclaration in the same DC
18567 // as the original, and ignore the current access specifier.
18568 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18569 SearchDC = PrevTagDecl->getDeclContext();
18570 AS = AS_none;
18571 }
18572 }
18573 // If we get here we have (another) forward declaration or we
18574 // have a definition. Just create a new decl.
18575
18576 } else {
18577 // If we get here, this is a definition of a new tag type in a nested
18578 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18579 // new decl/type. We set PrevDecl to NULL so that the entities
18580 // have distinct types.
18581 Previous.clear();
18582 }
18583 // If we get here, we're going to create a new Decl. If PrevDecl
18584 // is non-NULL, it's a definition of the tag declared by
18585 // PrevDecl. If it's NULL, we have a new definition.
18586
18587 // Otherwise, PrevDecl is not a tag, but was found with tag
18588 // lookup. This is only actually possible in C++, where a few
18589 // things like templates still live in the tag namespace.
18590 } else {
18591 // Use a better diagnostic if an elaborated-type-specifier
18592 // found the wrong kind of type on the first
18593 // (non-redeclaration) lookup.
18594 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18595 !Previous.isForRedeclaration()) {
18596 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18597 Diag(NameLoc, diag::err_tag_reference_non_tag)
18598 << PrevDecl << NTK << Kind;
18599 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18600 Invalid = true;
18601
18602 // Otherwise, only diagnose if the declaration is in scope.
18603 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18604 SS.isNotEmpty() || isMemberSpecialization)) {
18605 // do nothing
18606
18607 // Diagnose implicit declarations introduced by elaborated types.
18608 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18609 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18610 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18611 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18612 Invalid = true;
18613
18614 // Otherwise it's a declaration. Call out a particularly common
18615 // case here.
18616 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18617 unsigned Kind = 0;
18618 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18619 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18620 << Name << Kind << TND->getUnderlyingType();
18621 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18622 Invalid = true;
18623
18624 // Otherwise, diagnose.
18625 } else {
18626 // The tag name clashes with something else in the target scope,
18627 // issue an error and recover by making this tag be anonymous.
18628 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18629 notePreviousDefinition(PrevDecl, NameLoc);
18630 Name = nullptr;
18631 Invalid = true;
18632 }
18633
18634 // The existing declaration isn't relevant to us; we're in a
18635 // new scope, so clear out the previous declaration.
18636 Previous.clear();
18637 }
18638 }
18639
18640CreateNewDecl:
18641
18642 TagDecl *PrevDecl = nullptr;
18643 if (Previous.isSingleResult())
18644 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18645
18646 // If there is an identifier, use the location of the identifier as the
18647 // location of the decl, otherwise use the location of the struct/union
18648 // keyword.
18649 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18650
18651 // Otherwise, create a new declaration. If there is a previous
18652 // declaration of the same entity, the two will be linked via
18653 // PrevDecl.
18654 TagDecl *New;
18655
18656 if (Kind == TagTypeKind::Enum) {
18657 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18658 // enum X { A, B, C } D; D should chain to X.
18659 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
18660 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
18661 ScopedEnumUsesClassTag, IsFixed);
18662
18665 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
18666
18667 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
18669
18670 // If this is an undefined enum, warn.
18671 if (TUK != TagUseKind::Definition && !Invalid) {
18672 TagDecl *Def;
18673 if (IsFixed && ED->isFixed()) {
18674 // C++0x: 7.2p2: opaque-enum-declaration.
18675 // Conflicts are diagnosed above. Do nothing.
18676 } else if (PrevDecl &&
18677 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
18678 Diag(Loc, diag::ext_forward_ref_enum_def)
18679 << New;
18680 Diag(Def->getLocation(), diag::note_previous_definition);
18681 } else {
18682 unsigned DiagID = diag::ext_forward_ref_enum;
18683 if (getLangOpts().MSVCCompat)
18684 DiagID = diag::ext_ms_forward_ref_enum;
18685 else if (getLangOpts().CPlusPlus)
18686 DiagID = diag::err_forward_ref_enum;
18687 Diag(Loc, DiagID);
18688 }
18689 }
18690
18691 if (EnumUnderlying) {
18693 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18695 else
18696 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18697 QualType EnumTy = ED->getIntegerType();
18698 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18699 ? Context.getPromotedIntegerType(EnumTy)
18700 : EnumTy);
18701 assert(ED->isComplete() && "enum with type should be complete");
18702 }
18703 } else {
18704 // struct/union/class
18705
18706 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
18707 // struct X { int A; } D; D should chain to X.
18708 if (getLangOpts().CPlusPlus) {
18709 // FIXME: Look for a way to use RecordDecl for simple structs.
18710 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18711 cast_or_null<CXXRecordDecl>(PrevDecl));
18712
18713 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
18715 } else
18716 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18717 cast_or_null<RecordDecl>(PrevDecl));
18718 }
18719
18720 // Only C23 and later allow defining new types in 'offsetof()'.
18721 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
18723 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
18724 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
18725
18726 // C++11 [dcl.type]p3:
18727 // A type-specifier-seq shall not define a class or enumeration [...].
18728 if (!Invalid && getLangOpts().CPlusPlus &&
18729 (IsTypeSpecifier || IsTemplateParamOrArg) &&
18730 TUK == TagUseKind::Definition) {
18731 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
18732 << Context.getCanonicalTagType(New);
18733 Invalid = true;
18734 }
18735
18737 DC->getDeclKind() == Decl::Enum) {
18738 Diag(New->getLocation(), diag::err_type_defined_in_enum)
18739 << Context.getCanonicalTagType(New);
18740 Invalid = true;
18741 }
18742
18743 // Maybe add qualifier info.
18744 if (SS.isNotEmpty()) {
18745 if (SS.isSet()) {
18746 // If this is either a declaration or a definition, check the
18747 // nested-name-specifier against the current context.
18748 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
18749 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
18750 /*TemplateId=*/nullptr,
18751 isMemberSpecialization))
18752 Invalid = true;
18753
18754 New->setQualifierInfo(SS.getWithLocInContext(Context));
18755 if (TemplateParameterLists.size() > 0) {
18756 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
18757 }
18758 }
18759 else
18760 Invalid = true;
18761 }
18762
18763 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18764 // Add alignment attributes if necessary; these attributes are checked when
18765 // the ASTContext lays out the structure.
18766 //
18767 // It is important for implementing the correct semantics that this
18768 // happen here (in ActOnTag). The #pragma pack stack is
18769 // maintained as a result of parser callbacks which can occur at
18770 // many points during the parsing of a struct declaration (because
18771 // the #pragma tokens are effectively skipped over during the
18772 // parsing of the struct).
18773 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
18774 if (LangOpts.HLSL)
18775 RD->addAttr(PackedAttr::CreateImplicit(Context));
18778 }
18779 }
18780
18781 if (ModulePrivateLoc.isValid()) {
18782 if (isMemberSpecialization)
18783 Diag(New->getLocation(), diag::err_module_private_specialization)
18784 << 2
18785 << FixItHint::CreateRemoval(ModulePrivateLoc);
18786 // __module_private__ does not apply to local classes. However, we only
18787 // diagnose this as an error when the declaration specifiers are
18788 // freestanding. Here, we just ignore the __module_private__.
18789 else if (!SearchDC->isFunctionOrMethod())
18790 New->setModulePrivate();
18791 }
18792
18793 // If this is a specialization of a member class (of a class template),
18794 // check the specialization.
18795 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
18796 Invalid = true;
18797
18798 // If we're declaring or defining a tag in function prototype scope in C,
18799 // note that this type can only be used within the function and add it to
18800 // the list of decls to inject into the function definition scope. However,
18801 // in C23 and later, while the type is only visible within the function, the
18802 // function can be called with a compatible type defined in the same TU, so
18803 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
18804 if ((Name || Kind == TagTypeKind::Enum) &&
18805 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
18806 if (getLangOpts().CPlusPlus) {
18807 // C++ [dcl.fct]p6:
18808 // Types shall not be defined in return or parameter types.
18809 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
18810 Diag(Loc, diag::err_type_defined_in_param_type)
18811 << Name;
18812 Invalid = true;
18813 }
18814 if (TUK == TagUseKind::Declaration)
18815 Invalid = true;
18816 } else if (!PrevDecl) {
18817 // In C23 mode, if the declaration is complete, we do not want to
18818 // diagnose.
18819 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
18820 Diag(Loc, diag::warn_decl_in_param_list)
18821 << Context.getCanonicalTagType(New);
18822 }
18823 }
18824
18825 if (Invalid)
18826 New->setInvalidDecl();
18827
18828 // Set the lexical context. If the tag has a C++ scope specifier, the
18829 // lexical context will be different from the semantic context.
18830 New->setLexicalDeclContext(CurContext);
18831
18832 // Mark this as a friend decl if applicable.
18833 // In Microsoft mode, a friend declaration also acts as a forward
18834 // declaration so we always pass true to setObjectOfFriendDecl to make
18835 // the tag name visible.
18836 if (TUK == TagUseKind::Friend)
18837 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
18838
18839 // Set the access specifier.
18840 if (!Invalid && SearchDC->isRecord())
18841 SetMemberAccessSpecifier(New, PrevDecl, AS);
18842
18843 if (PrevDecl)
18845
18846 if (TUK == TagUseKind::Definition) {
18847 if (!SkipBody || !SkipBody->ShouldSkip) {
18848 New->startDefinition();
18849 } else {
18850 New->setCompleteDefinition();
18851 New->demoteThisDefinitionToDeclaration();
18852 }
18853 }
18854
18855 ProcessDeclAttributeList(S, New, Attrs);
18857
18858 // If this has an identifier, add it to the scope stack.
18859 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
18860 // We might be replacing an existing declaration in the lookup tables;
18861 // if so, borrow its access specifier.
18862 if (PrevDecl)
18863 New->setAccess(PrevDecl->getAccess());
18864
18865 DeclContext *DC = New->getDeclContext()->getRedeclContext();
18867 if (Name) // can be null along some error paths
18868 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18869 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
18870 } else if (Name) {
18871 S = getNonFieldDeclScope(S);
18872 PushOnScopeChains(New, S, true);
18873 } else {
18874 CurContext->addDecl(New);
18875 }
18876
18877 // If this is the C FILE type, notify the AST context.
18878 if (IdentifierInfo *II = New->getIdentifier())
18879 if (!New->isInvalidDecl() &&
18880 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
18881 II->isStr("FILE"))
18882 Context.setFILEDecl(New);
18883
18884 if (PrevDecl)
18885 mergeDeclAttributes(New, PrevDecl);
18886
18887 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
18890 }
18891
18892 // If there's a #pragma GCC visibility in scope, set the visibility of this
18893 // record.
18895
18896 // If this is not a definition, process API notes for it now.
18897 if (TUK != TagUseKind::Definition)
18899
18900 if (isMemberSpecialization && !New->isInvalidDecl())
18902
18903 OwnedDecl = true;
18904 // In C++, don't return an invalid declaration. We can't recover well from
18905 // the cases where we make the type anonymous.
18906 if (Invalid && getLangOpts().CPlusPlus) {
18907 if (New->isBeingDefined())
18908 if (auto RD = dyn_cast<RecordDecl>(New))
18909 RD->completeDefinition();
18910 return true;
18911 } else if (SkipBody && SkipBody->ShouldSkip) {
18912 return SkipBody->Previous;
18913 } else {
18914 return New;
18915 }
18916}
18917
18920 TagDecl *Tag = cast<TagDecl>(TagD);
18921
18922 // Enter the tag context.
18923 PushDeclContext(S, Tag);
18924
18926
18927 // If there's a #pragma GCC visibility in scope, set the visibility of this
18928 // record.
18930}
18931
18933 SkipBodyInfo &SkipBody) {
18934 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
18935 return false;
18936
18937 // Make the previous decl visible.
18939 CleanupMergedEnum(S, SkipBody.New);
18940 return true;
18941}
18942
18944 SourceLocation FinalLoc,
18945 bool IsFinalSpelledSealed,
18946 bool IsAbstract,
18947 SourceLocation LBraceLoc) {
18950
18951 FieldCollector->StartClass();
18952
18953 if (!Record->getIdentifier())
18954 return;
18955
18956 if (IsAbstract)
18957 Record->markAbstract();
18958
18959 if (FinalLoc.isValid()) {
18960 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
18961 IsFinalSpelledSealed
18962 ? FinalAttr::Keyword_sealed
18963 : FinalAttr::Keyword_final));
18964 }
18965
18966 // C++ [class]p2:
18967 // [...] The class-name is also inserted into the scope of the
18968 // class itself; this is known as the injected-class-name. For
18969 // purposes of access checking, the injected-class-name is treated
18970 // as if it were a public member name.
18971 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
18972 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
18973 Record->getLocation(), Record->getIdentifier());
18974 InjectedClassName->setImplicit();
18975 InjectedClassName->setAccess(AS_public);
18976 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
18977 InjectedClassName->setDescribedClassTemplate(Template);
18978
18979 PushOnScopeChains(InjectedClassName, S);
18980 assert(InjectedClassName->isInjectedClassName() &&
18981 "Broken injected-class-name");
18982}
18983
18985 SourceRange BraceRange) {
18987 TagDecl *Tag = cast<TagDecl>(TagD);
18988 Tag->setBraceRange(BraceRange);
18989
18990 // Make sure we "complete" the definition even it is invalid.
18991 if (Tag->isBeingDefined()) {
18992 assert(Tag->isInvalidDecl() && "We should already have completed it");
18993 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
18994 RD->completeDefinition();
18995 }
18996
18997 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
18998 FieldCollector->FinishClass();
18999 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19000 auto *Def = RD->getDefinition();
19001 assert(Def && "The record is expected to have a completed definition");
19002 unsigned NumInitMethods = 0;
19003 for (auto *Method : Def->methods()) {
19004 if (!Method->getIdentifier())
19005 continue;
19006 if (Method->getName() == "__init")
19007 NumInitMethods++;
19008 }
19009 if (NumInitMethods > 1 || !Def->hasInitMethod())
19010 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
19011 }
19012
19013 // If we're defining a dynamic class in a module interface unit, we always
19014 // need to produce the vtable for it, even if the vtable is not used in the
19015 // current TU.
19016 //
19017 // The case where the current class is not dynamic is handled in
19018 // MarkVTableUsed.
19019 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19020 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
19021 }
19022
19023 // Exit this scope of this tag's definition.
19025
19026 if (getCurLexicalContext()->isObjCContainer() &&
19027 Tag->getDeclContext()->isFileContext())
19028 Tag->setTopLevelDeclInObjCContainer();
19029
19030 // Notify the consumer that we've defined a tag.
19031 if (!Tag->isInvalidDecl())
19032 Consumer.HandleTagDeclDefinition(Tag);
19033
19034 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19035 // from XLs and instead matches the XL #pragma pack(1) behavior.
19036 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19037 AlignPackStack.hasValue()) {
19038 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19039 // Only diagnose #pragma align(packed).
19040 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19041 return;
19042 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
19043 if (!RD)
19044 return;
19045 // Only warn if there is at least 1 bitfield member.
19046 if (llvm::any_of(RD->fields(),
19047 [](const FieldDecl *FD) { return FD->isBitField(); }))
19048 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
19049 }
19050}
19051
19054 TagDecl *Tag = cast<TagDecl>(TagD);
19055 Tag->setInvalidDecl();
19056
19057 // Make sure we "complete" the definition even it is invalid.
19058 if (Tag->isBeingDefined()) {
19059 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19060 RD->completeDefinition();
19061 }
19062
19063 // We're undoing ActOnTagStartDefinition here, not
19064 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19065 // the FieldCollector.
19066
19068}
19069
19070// Note that FieldName may be null for anonymous bitfields.
19072 const IdentifierInfo *FieldName,
19073 QualType FieldTy, bool IsMsStruct,
19074 Expr *BitWidth) {
19075 assert(BitWidth);
19076 if (BitWidth->containsErrors())
19077 return ExprError();
19078
19079 // C99 6.7.2.1p4 - verify the field type.
19080 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19081 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19082 // Handle incomplete and sizeless types with a specific error.
19083 if (RequireCompleteSizedType(FieldLoc, FieldTy,
19084 diag::err_field_incomplete_or_sizeless))
19085 return ExprError();
19086 if (FieldName)
19087 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
19088 << FieldName << FieldTy << BitWidth->getSourceRange();
19089 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
19090 << FieldTy << BitWidth->getSourceRange();
19092 return ExprError();
19093
19094 // If the bit-width is type- or value-dependent, don't try to check
19095 // it now.
19096 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19097 return BitWidth;
19098
19099 llvm::APSInt Value;
19100 ExprResult ICE =
19102 if (ICE.isInvalid())
19103 return ICE;
19104 BitWidth = ICE.get();
19105
19106 // Zero-width bitfield is ok for anonymous field.
19107 if (Value == 0 && FieldName)
19108 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
19109 << FieldName << BitWidth->getSourceRange();
19110
19111 if (Value.isSigned() && Value.isNegative()) {
19112 if (FieldName)
19113 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
19114 << FieldName << toString(Value, 10);
19115 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
19116 << toString(Value, 10);
19117 }
19118
19119 // The size of the bit-field must not exceed our maximum permitted object
19120 // size.
19121 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19122 return Diag(FieldLoc, diag::err_bitfield_too_wide)
19123 << !FieldName << FieldName << toString(Value, 10);
19124 }
19125
19126 if (!FieldTy->isDependentType()) {
19127 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
19128 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
19129 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
19130
19131 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19132 // ABI.
19133 bool CStdConstraintViolation =
19134 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19135 bool MSBitfieldViolation = Value.ugt(TypeStorageSize) && IsMsStruct;
19136 if (CStdConstraintViolation || MSBitfieldViolation) {
19137 unsigned DiagWidth =
19138 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19139 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
19140 << (bool)FieldName << FieldName << toString(Value, 10)
19141 << !CStdConstraintViolation << DiagWidth;
19142 }
19143
19144 // Warn on types where the user might conceivably expect to get all
19145 // specified bits as value bits: that's all integral types other than
19146 // 'bool'.
19147 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19148 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
19149 << FieldName << Value << (unsigned)TypeWidth;
19150 }
19151 }
19152
19153 if (isa<ConstantExpr>(BitWidth))
19154 return BitWidth;
19155 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
19156}
19157
19159 Declarator &D, Expr *BitfieldWidth) {
19160 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
19161 D, BitfieldWidth,
19162 /*InitStyle=*/ICIS_NoInit, AS_public);
19163 return Res;
19164}
19165
19167 SourceLocation DeclStart,
19168 Declarator &D, Expr *BitWidth,
19169 InClassInitStyle InitStyle,
19170 AccessSpecifier AS) {
19171 if (D.isDecompositionDeclarator()) {
19173 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19174 << Decomp.getSourceRange();
19175 return nullptr;
19176 }
19177
19178 const IdentifierInfo *II = D.getIdentifier();
19179 SourceLocation Loc = DeclStart;
19180 if (II) Loc = D.getIdentifierLoc();
19181
19183 QualType T = TInfo->getType();
19184 if (getLangOpts().CPlusPlus) {
19186
19189 D.setInvalidType();
19190 T = Context.IntTy;
19191 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19192 }
19193 }
19194
19196
19198 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19199 << getLangOpts().CPlusPlus17;
19202 diag::err_invalid_thread)
19204
19205 // Check to see if this name was declared as a member previously
19206 NamedDecl *PrevDecl = nullptr;
19207 LookupResult Previous(*this, II, Loc, LookupMemberName,
19209 LookupName(Previous, S);
19210 switch (Previous.getResultKind()) {
19213 PrevDecl = Previous.getAsSingle<NamedDecl>();
19214 break;
19215
19217 PrevDecl = Previous.getRepresentativeDecl();
19218 break;
19219
19223 break;
19224 }
19225 Previous.suppressDiagnostics();
19226
19227 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19228 // Maybe we will complain about the shadowed template parameter.
19230 // Just pretend that we didn't see the previous declaration.
19231 PrevDecl = nullptr;
19232 }
19233
19234 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19235 PrevDecl = nullptr;
19236
19237 bool Mutable
19238 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19239 SourceLocation TSSL = D.getBeginLoc();
19240 FieldDecl *NewFD
19241 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19242 TSSL, AS, PrevDecl, &D);
19243
19244 if (NewFD->isInvalidDecl())
19245 Record->setInvalidDecl();
19246
19248 NewFD->setModulePrivate();
19249
19250 if (NewFD->isInvalidDecl() && PrevDecl) {
19251 // Don't introduce NewFD into scope; there's already something
19252 // with the same name in the same scope.
19253 } else if (II) {
19254 PushOnScopeChains(NewFD, S);
19255 } else
19256 Record->addDecl(NewFD);
19257
19258 return NewFD;
19259}
19260
19262 TypeSourceInfo *TInfo,
19264 bool Mutable, Expr *BitWidth,
19265 InClassInitStyle InitStyle,
19266 SourceLocation TSSL,
19267 AccessSpecifier AS, NamedDecl *PrevDecl,
19268 Declarator *D) {
19269 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19270 bool InvalidDecl = false;
19271 if (D) InvalidDecl = D->isInvalidType();
19272
19273 // If we receive a broken type, recover by assuming 'int' and
19274 // marking this declaration as invalid.
19275 if (T.isNull() || T->containsErrors()) {
19276 InvalidDecl = true;
19277 T = Context.IntTy;
19278 }
19279
19280 QualType EltTy = Context.getBaseElementType(T);
19281 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19282 bool isIncomplete =
19283 LangOpts.HLSL // HLSL allows sizeless builtin types
19284 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19285 : RequireCompleteSizedType(Loc, EltTy,
19286 diag::err_field_incomplete_or_sizeless);
19287 if (isIncomplete) {
19288 // Fields of incomplete type force their record to be invalid.
19289 Record->setInvalidDecl();
19290 InvalidDecl = true;
19291 } else {
19292 NamedDecl *Def;
19293 EltTy->isIncompleteType(&Def);
19294 if (Def && Def->isInvalidDecl()) {
19295 Record->setInvalidDecl();
19296 InvalidDecl = true;
19297 }
19298 }
19299 }
19300
19301 // TR 18037 does not allow fields to be declared with address space
19302 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19303 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19304 Diag(Loc, diag::err_field_with_address_space);
19305 Record->setInvalidDecl();
19306 InvalidDecl = true;
19307 }
19308
19309 if (LangOpts.OpenCL) {
19310 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19311 // used as structure or union field: image, sampler, event or block types.
19312 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19313 T->isBlockPointerType()) {
19314 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19315 Record->setInvalidDecl();
19316 InvalidDecl = true;
19317 }
19318 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19319 // is enabled.
19320 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19321 "__cl_clang_bitfields", LangOpts)) {
19322 Diag(Loc, diag::err_opencl_bitfields);
19323 InvalidDecl = true;
19324 }
19325 }
19326
19327 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19328 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19329 T.hasQualifiers()) {
19330 InvalidDecl = true;
19331 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19332 }
19333
19334 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19335 // than a variably modified type.
19336 if (!InvalidDecl && T->isVariablyModifiedType()) {
19338 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19339 InvalidDecl = true;
19340 }
19341
19342 // Fields can not have abstract class types
19343 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19344 diag::err_abstract_type_in_decl,
19346 InvalidDecl = true;
19347
19348 if (InvalidDecl)
19349 BitWidth = nullptr;
19350 // If this is declared as a bit-field, check the bit-field.
19351 if (BitWidth) {
19352 BitWidth =
19353 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19354 if (!BitWidth) {
19355 InvalidDecl = true;
19356 BitWidth = nullptr;
19357 }
19358 }
19359
19360 // Check that 'mutable' is consistent with the type of the declaration.
19361 if (!InvalidDecl && Mutable) {
19362 unsigned DiagID = 0;
19363 if (T->isReferenceType())
19364 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19365 : diag::err_mutable_reference;
19366 else if (T.isConstQualified())
19367 DiagID = diag::err_mutable_const;
19368
19369 if (DiagID) {
19370 SourceLocation ErrLoc = Loc;
19371 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19372 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19373 Diag(ErrLoc, DiagID);
19374 if (DiagID != diag::ext_mutable_reference) {
19375 Mutable = false;
19376 InvalidDecl = true;
19377 }
19378 }
19379 }
19380
19381 // C++11 [class.union]p8 (DR1460):
19382 // At most one variant member of a union may have a
19383 // brace-or-equal-initializer.
19384 if (InitStyle != ICIS_NoInit)
19386
19387 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19388 BitWidth, Mutable, InitStyle);
19389 if (InvalidDecl)
19390 NewFD->setInvalidDecl();
19391
19392 if (!InvalidDecl)
19394
19395 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19396 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19397 Diag(Loc, diag::err_duplicate_member) << II;
19398 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19399 NewFD->setInvalidDecl();
19400 }
19401
19402 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19403 if (Record->isUnion()) {
19404 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19405 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19406
19407 // C++ [class.union]p1: An object of a class with a non-trivial
19408 // constructor, a non-trivial copy constructor, a non-trivial
19409 // destructor, or a non-trivial copy assignment operator
19410 // cannot be a member of a union, nor can an array of such
19411 // objects.
19412 if (CheckNontrivialField(NewFD))
19413 NewFD->setInvalidDecl();
19414 }
19415
19416 // C++ [class.union]p1: If a union contains a member of reference type,
19417 // the program is ill-formed, except when compiling with MSVC extensions
19418 // enabled.
19419 if (EltTy->isReferenceType()) {
19420 const bool HaveMSExt =
19421 getLangOpts().MicrosoftExt &&
19423
19424 Diag(NewFD->getLocation(),
19425 HaveMSExt ? diag::ext_union_member_of_reference_type
19426 : diag::err_union_member_of_reference_type)
19427 << NewFD->getDeclName() << EltTy;
19428 if (!HaveMSExt)
19429 NewFD->setInvalidDecl();
19430 }
19431 }
19432 }
19433
19434 // FIXME: We need to pass in the attributes given an AST
19435 // representation, not a parser representation.
19436 if (D) {
19437 // FIXME: The current scope is almost... but not entirely... correct here.
19438 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19439
19440 if (NewFD->hasAttrs())
19442 }
19443
19444 // In auto-retain/release, infer strong retension for fields of
19445 // retainable type.
19446 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19447 NewFD->setInvalidDecl();
19448
19449 if (T.isObjCGCWeak())
19450 Diag(Loc, diag::warn_attribute_weak_on_field);
19451
19452 // PPC MMA non-pointer types are not allowed as field types.
19453 if (Context.getTargetInfo().getTriple().isPPC64() &&
19454 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19455 NewFD->setInvalidDecl();
19456
19457 NewFD->setAccess(AS);
19458 return NewFD;
19459}
19460
19462 assert(FD);
19463 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19464
19465 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19466 return false;
19467
19468 QualType EltTy = Context.getBaseElementType(FD->getType());
19469 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19470 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19471 // We check for copy constructors before constructors
19472 // because otherwise we'll never get complaints about
19473 // copy constructors.
19474
19476 // We're required to check for any non-trivial constructors. Since the
19477 // implicit default constructor is suppressed if there are any
19478 // user-declared constructors, we just need to check that there is a
19479 // trivial default constructor and a trivial copy constructor. (We don't
19480 // worry about move constructors here, since this is a C++98 check.)
19481 if (RDecl->hasNonTrivialCopyConstructor())
19483 else if (!RDecl->hasTrivialDefaultConstructor())
19485 else if (RDecl->hasNonTrivialCopyAssignment())
19487 else if (RDecl->hasNonTrivialDestructor())
19489
19490 if (member != CXXSpecialMemberKind::Invalid) {
19491 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19492 RDecl->hasObjectMember()) {
19493 // Objective-C++ ARC: it is an error to have a non-trivial field of
19494 // a union. However, system headers in Objective-C programs
19495 // occasionally have Objective-C lifetime objects within unions,
19496 // and rather than cause the program to fail, we make those
19497 // members unavailable.
19498 SourceLocation Loc = FD->getLocation();
19499 if (getSourceManager().isInSystemHeader(Loc)) {
19500 if (!FD->hasAttr<UnavailableAttr>())
19501 FD->addAttr(UnavailableAttr::CreateImplicit(
19502 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19503 return false;
19504 }
19505 }
19506
19507 Diag(FD->getLocation(),
19509 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19510 : diag::err_illegal_union_or_anon_struct_member)
19511 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19512 DiagnoseNontrivial(RDecl, member);
19513 return !getLangOpts().CPlusPlus11;
19514 }
19515 }
19516
19517 return false;
19518}
19519
19521 SmallVectorImpl<Decl *> &AllIvarDecls) {
19522 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19523 return;
19524
19525 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19526 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19527
19528 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19529 return;
19530 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19531 if (!ID) {
19532 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19533 if (!CD->IsClassExtension())
19534 return;
19535 }
19536 // No need to add this to end of @implementation.
19537 else
19538 return;
19539 }
19540 // All conditions are met. Add a new bitfield to the tail end of ivars.
19541 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19542 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19543 Expr *BitWidth =
19544 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19545
19546 Ivar = ObjCIvarDecl::Create(
19547 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19548 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19549 ObjCIvarDecl::Private, BitWidth, true);
19550 AllIvarDecls.push_back(Ivar);
19551}
19552
19553/// [class.dtor]p4:
19554/// At the end of the definition of a class, overload resolution is
19555/// performed among the prospective destructors declared in that class with
19556/// an empty argument list to select the destructor for the class, also
19557/// known as the selected destructor.
19558///
19559/// We do the overload resolution here, then mark the selected constructor in the AST.
19560/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19562 if (!Record->hasUserDeclaredDestructor()) {
19563 return;
19564 }
19565
19566 SourceLocation Loc = Record->getLocation();
19568
19569 for (auto *Decl : Record->decls()) {
19570 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19571 if (DD->isInvalidDecl())
19572 continue;
19573 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19574 OCS);
19575 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19576 }
19577 }
19578
19579 if (OCS.empty()) {
19580 return;
19581 }
19583 unsigned Msg = 0;
19584 OverloadCandidateDisplayKind DisplayKind;
19585
19586 switch (OCS.BestViableFunction(S, Loc, Best)) {
19587 case OR_Success:
19588 case OR_Deleted:
19589 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19590 break;
19591
19592 case OR_Ambiguous:
19593 Msg = diag::err_ambiguous_destructor;
19594 DisplayKind = OCD_AmbiguousCandidates;
19595 break;
19596
19598 Msg = diag::err_no_viable_destructor;
19599 DisplayKind = OCD_AllCandidates;
19600 break;
19601 }
19602
19603 if (Msg) {
19604 // OpenCL have got their own thing going with destructors. It's slightly broken,
19605 // but we allow it.
19606 if (!S.LangOpts.OpenCL) {
19607 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19608 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19609 Record->setInvalidDecl();
19610 }
19611 // It's a bit hacky: At this point we've raised an error but we want the
19612 // rest of the compiler to continue somehow working. However almost
19613 // everything we'll try to do with the class will depend on there being a
19614 // destructor. So let's pretend the first one is selected and hope for the
19615 // best.
19616 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19617 }
19618}
19619
19620/// [class.mem.special]p5
19621/// Two special member functions are of the same kind if:
19622/// - they are both default constructors,
19623/// - they are both copy or move constructors with the same first parameter
19624/// type, or
19625/// - they are both copy or move assignment operators with the same first
19626/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19628 CXXMethodDecl *M1,
19629 CXXMethodDecl *M2,
19631 // We don't want to compare templates to non-templates: See
19632 // https://github.com/llvm/llvm-project/issues/59206
19634 return bool(M1->getDescribedFunctionTemplate()) ==
19636 // FIXME: better resolve CWG
19637 // https://cplusplus.github.io/CWG/issues/2787.html
19638 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19639 M2->getNonObjectParameter(0)->getType()))
19640 return false;
19641 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
19643 return false;
19644
19645 return true;
19646}
19647
19648/// [class.mem.special]p6:
19649/// An eligible special member function is a special member function for which:
19650/// - the function is not deleted,
19651/// - the associated constraints, if any, are satisfied, and
19652/// - no special member function of the same kind whose associated constraints
19653/// [CWG2595], if any, are satisfied is more constrained.
19657 SmallVector<bool, 4> SatisfactionStatus;
19658
19659 for (CXXMethodDecl *Method : Methods) {
19660 if (!Method->getTrailingRequiresClause())
19661 SatisfactionStatus.push_back(true);
19662 else {
19663 ConstraintSatisfaction Satisfaction;
19664 if (S.CheckFunctionConstraints(Method, Satisfaction))
19665 SatisfactionStatus.push_back(false);
19666 else
19667 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
19668 }
19669 }
19670
19671 for (size_t i = 0; i < Methods.size(); i++) {
19672 if (!SatisfactionStatus[i])
19673 continue;
19674 CXXMethodDecl *Method = Methods[i];
19675 CXXMethodDecl *OrigMethod = Method;
19676 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
19677 OrigMethod = cast<CXXMethodDecl>(MF);
19678
19680 bool AnotherMethodIsMoreConstrained = false;
19681 for (size_t j = 0; j < Methods.size(); j++) {
19682 if (i == j || !SatisfactionStatus[j])
19683 continue;
19684 CXXMethodDecl *OtherMethod = Methods[j];
19685 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
19686 OtherMethod = cast<CXXMethodDecl>(MF);
19687
19688 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
19689 CSM))
19690 continue;
19691
19693 if (!Other)
19694 continue;
19695 if (!Orig) {
19696 AnotherMethodIsMoreConstrained = true;
19697 break;
19698 }
19699 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
19700 AnotherMethodIsMoreConstrained)) {
19701 // There was an error with the constraints comparison. Exit the loop
19702 // and don't consider this function eligible.
19703 AnotherMethodIsMoreConstrained = true;
19704 }
19705 if (AnotherMethodIsMoreConstrained)
19706 break;
19707 }
19708 // FIXME: Do not consider deleted methods as eligible after implementing
19709 // DR1734 and DR1496.
19710 if (!AnotherMethodIsMoreConstrained) {
19711 Method->setIneligibleOrNotSelected(false);
19712 Record->addedEligibleSpecialMemberFunction(Method,
19713 1 << llvm::to_underlying(CSM));
19714 }
19715 }
19716}
19717
19720 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
19721 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
19722 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
19723 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
19724 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
19725
19726 for (auto *Decl : Record->decls()) {
19727 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
19728 if (!MD) {
19729 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
19730 if (FTD)
19731 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
19732 }
19733 if (!MD)
19734 continue;
19735 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
19736 if (CD->isInvalidDecl())
19737 continue;
19738 if (CD->isDefaultConstructor())
19739 DefaultConstructors.push_back(MD);
19740 else if (CD->isCopyConstructor())
19741 CopyConstructors.push_back(MD);
19742 else if (CD->isMoveConstructor())
19743 MoveConstructors.push_back(MD);
19744 } else if (MD->isCopyAssignmentOperator()) {
19745 CopyAssignmentOperators.push_back(MD);
19746 } else if (MD->isMoveAssignmentOperator()) {
19747 MoveAssignmentOperators.push_back(MD);
19748 }
19749 }
19750
19751 SetEligibleMethods(S, Record, DefaultConstructors,
19753 SetEligibleMethods(S, Record, CopyConstructors,
19755 SetEligibleMethods(S, Record, MoveConstructors,
19757 SetEligibleMethods(S, Record, CopyAssignmentOperators,
19759 SetEligibleMethods(S, Record, MoveAssignmentOperators,
19761}
19762
19763bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
19764 // Check to see if a FieldDecl is a pointer to a function.
19765 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
19766 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
19767 if (!FD) {
19768 // Check whether this is a forward declaration that was inserted by
19769 // Clang. This happens when a non-forward declared / defined type is
19770 // used, e.g.:
19771 //
19772 // struct foo {
19773 // struct bar *(*f)();
19774 // struct bar *(*g)();
19775 // };
19776 //
19777 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
19778 // incomplete definition.
19779 if (const auto *TD = dyn_cast<TagDecl>(D))
19780 return !TD->isCompleteDefinition();
19781 return false;
19782 }
19783 QualType FieldType = FD->getType().getDesugaredType(Context);
19784 if (isa<PointerType>(FieldType)) {
19785 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
19786 return PointeeType.getDesugaredType(Context)->isFunctionType();
19787 }
19788 // If a member is a struct entirely of function pointers, that counts too.
19789 if (const auto *Record = FieldType->getAsRecordDecl();
19790 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
19791 return true;
19792 return false;
19793 };
19794
19795 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
19796}
19797
19798void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
19799 ArrayRef<Decl *> Fields, SourceLocation LBrac,
19800 SourceLocation RBrac,
19801 const ParsedAttributesView &Attrs) {
19802 assert(EnclosingDecl && "missing record or interface decl");
19803
19804 // If this is an Objective-C @implementation or category and we have
19805 // new fields here we should reset the layout of the interface since
19806 // it will now change.
19807 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
19808 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
19809 switch (DC->getKind()) {
19810 default: break;
19811 case Decl::ObjCCategory:
19812 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
19813 break;
19814 case Decl::ObjCImplementation:
19815 Context.
19816 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
19817 break;
19818 }
19819 }
19820
19821 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
19822 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
19823
19824 // Start counting up the number of named members; make sure to include
19825 // members of anonymous structs and unions in the total.
19826 unsigned NumNamedMembers = 0;
19827 if (Record) {
19828 for (const auto *I : Record->decls()) {
19829 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
19830 if (IFD->getDeclName())
19831 ++NumNamedMembers;
19832 }
19833 }
19834
19835 // Verify that all the fields are okay.
19837 const FieldDecl *PreviousField = nullptr;
19838 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
19839 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
19840 FieldDecl *FD = cast<FieldDecl>(*i);
19841
19842 // Get the type for the field.
19843 const Type *FDTy = FD->getType().getTypePtr();
19844
19845 if (!FD->isAnonymousStructOrUnion()) {
19846 // Remember all fields written by the user.
19847 RecFields.push_back(FD);
19848 }
19849
19850 // If the field is already invalid for some reason, don't emit more
19851 // diagnostics about it.
19852 if (FD->isInvalidDecl()) {
19853 EnclosingDecl->setInvalidDecl();
19854 continue;
19855 }
19856
19857 // C99 6.7.2.1p2:
19858 // A structure or union shall not contain a member with
19859 // incomplete or function type (hence, a structure shall not
19860 // contain an instance of itself, but may contain a pointer to
19861 // an instance of itself), except that the last member of a
19862 // structure with more than one named member may have incomplete
19863 // array type; such a structure (and any union containing,
19864 // possibly recursively, a member that is such a structure)
19865 // shall not be a member of a structure or an element of an
19866 // array.
19867 bool IsLastField = (i + 1 == Fields.end());
19868 if (FDTy->isFunctionType()) {
19869 // Field declared as a function.
19870 Diag(FD->getLocation(), diag::err_field_declared_as_function)
19871 << FD->getDeclName();
19872 FD->setInvalidDecl();
19873 EnclosingDecl->setInvalidDecl();
19874 continue;
19875 } else if (FDTy->isIncompleteArrayType() &&
19876 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
19877 if (Record) {
19878 // Flexible array member.
19879 // Microsoft and g++ is more permissive regarding flexible array.
19880 // It will accept flexible array in union and also
19881 // as the sole element of a struct/class.
19882 unsigned DiagID = 0;
19883 if (!Record->isUnion() && !IsLastField) {
19884 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
19885 << FD->getDeclName() << FD->getType() << Record->getTagKind();
19886 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
19887 FD->setInvalidDecl();
19888 EnclosingDecl->setInvalidDecl();
19889 continue;
19890 } else if (Record->isUnion())
19891 DiagID = getLangOpts().MicrosoftExt
19892 ? diag::ext_flexible_array_union_ms
19893 : diag::ext_flexible_array_union_gnu;
19894 else if (NumNamedMembers < 1)
19895 DiagID = getLangOpts().MicrosoftExt
19896 ? diag::ext_flexible_array_empty_aggregate_ms
19897 : diag::ext_flexible_array_empty_aggregate_gnu;
19898
19899 if (DiagID)
19900 Diag(FD->getLocation(), DiagID)
19901 << FD->getDeclName() << Record->getTagKind();
19902 // While the layout of types that contain virtual bases is not specified
19903 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
19904 // virtual bases after the derived members. This would make a flexible
19905 // array member declared at the end of an object not adjacent to the end
19906 // of the type.
19907 if (CXXRecord && CXXRecord->getNumVBases() != 0)
19908 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
19909 << FD->getDeclName() << Record->getTagKind();
19910 if (!getLangOpts().C99)
19911 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
19912 << FD->getDeclName() << Record->getTagKind();
19913
19914 // If the element type has a non-trivial destructor, we would not
19915 // implicitly destroy the elements, so disallow it for now.
19916 //
19917 // FIXME: GCC allows this. We should probably either implicitly delete
19918 // the destructor of the containing class, or just allow this.
19919 QualType BaseElem = Context.getBaseElementType(FD->getType());
19920 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
19921 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
19922 << FD->getDeclName() << FD->getType();
19923 FD->setInvalidDecl();
19924 EnclosingDecl->setInvalidDecl();
19925 continue;
19926 }
19927 // Okay, we have a legal flexible array member at the end of the struct.
19928 Record->setHasFlexibleArrayMember(true);
19929 } else {
19930 // In ObjCContainerDecl ivars with incomplete array type are accepted,
19931 // unless they are followed by another ivar. That check is done
19932 // elsewhere, after synthesized ivars are known.
19933 }
19934 } else if (!FDTy->isDependentType() &&
19935 (LangOpts.HLSL // HLSL allows sizeless builtin types
19937 diag::err_incomplete_type)
19939 FD->getLocation(), FD->getType(),
19940 diag::err_field_incomplete_or_sizeless))) {
19941 // Incomplete type
19942 FD->setInvalidDecl();
19943 EnclosingDecl->setInvalidDecl();
19944 continue;
19945 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
19946 if (Record && RD->hasFlexibleArrayMember()) {
19947 // A type which contains a flexible array member is considered to be a
19948 // flexible array member.
19949 Record->setHasFlexibleArrayMember(true);
19950 if (!Record->isUnion()) {
19951 // If this is a struct/class and this is not the last element, reject
19952 // it. Note that GCC supports variable sized arrays in the middle of
19953 // structures.
19954 if (!IsLastField)
19955 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
19956 << FD->getDeclName() << FD->getType();
19957 else {
19958 // We support flexible arrays at the end of structs in
19959 // other structs as an extension.
19960 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
19961 << FD->getDeclName();
19962 }
19963 }
19964 }
19965 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
19967 diag::err_abstract_type_in_decl,
19969 // Ivars can not have abstract class types
19970 FD->setInvalidDecl();
19971 }
19972 if (Record && RD->hasObjectMember())
19973 Record->setHasObjectMember(true);
19974 if (Record && RD->hasVolatileMember())
19975 Record->setHasVolatileMember(true);
19976 } else if (FDTy->isObjCObjectType()) {
19977 /// A field cannot be an Objective-c object
19978 Diag(FD->getLocation(), diag::err_statically_allocated_object)
19980 QualType T = Context.getObjCObjectPointerType(FD->getType());
19981 FD->setType(T);
19982 } else if (Record && Record->isUnion() &&
19984 getSourceManager().isInSystemHeader(FD->getLocation()) &&
19985 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
19987 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
19988 // For backward compatibility, fields of C unions declared in system
19989 // headers that have non-trivial ObjC ownership qualifications are marked
19990 // as unavailable unless the qualifier is explicit and __strong. This can
19991 // break ABI compatibility between programs compiled with ARC and MRR, but
19992 // is a better option than rejecting programs using those unions under
19993 // ARC.
19994 FD->addAttr(UnavailableAttr::CreateImplicit(
19995 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
19996 FD->getLocation()));
19997 } else if (getLangOpts().ObjC &&
19998 getLangOpts().getGC() != LangOptions::NonGC && Record &&
19999 !Record->hasObjectMember()) {
20000 if (FD->getType()->isObjCObjectPointerType() ||
20001 FD->getType().isObjCGCStrong())
20002 Record->setHasObjectMember(true);
20003 else if (Context.getAsArrayType(FD->getType())) {
20004 QualType BaseType = Context.getBaseElementType(FD->getType());
20005 if (const auto *RD = BaseType->getAsRecordDecl();
20006 RD && RD->hasObjectMember())
20007 Record->setHasObjectMember(true);
20008 else if (BaseType->isObjCObjectPointerType() ||
20009 BaseType.isObjCGCStrong())
20010 Record->setHasObjectMember(true);
20011 }
20012 }
20013
20014 if (Record && !getLangOpts().CPlusPlus &&
20015 !shouldIgnoreForRecordTriviality(FD)) {
20016 QualType FT = FD->getType();
20018 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20020 Record->isUnion())
20021 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20022 }
20025 Record->setNonTrivialToPrimitiveCopy(true);
20026 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20027 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20028 }
20029 if (FD->hasAttr<ExplicitInitAttr>())
20030 Record->setHasUninitializedExplicitInitFields(true);
20031 if (FT.isDestructedType()) {
20032 Record->setNonTrivialToPrimitiveDestroy(true);
20033 Record->setParamDestroyedInCallee(true);
20034 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20035 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20036 }
20037
20038 if (const auto *RD = FT->getAsRecordDecl()) {
20039 if (RD->getArgPassingRestrictions() ==
20041 Record->setArgPassingRestrictions(
20043 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20044 Record->setArgPassingRestrictions(
20046 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20047 Q && Q.isAddressDiscriminated()) {
20048 Record->setArgPassingRestrictions(
20050 Record->setNonTrivialToPrimitiveCopy(true);
20051 }
20052 }
20053
20054 if (Record && FD->getType().isVolatileQualified())
20055 Record->setHasVolatileMember(true);
20056 bool ReportMSBitfieldStoragePacking =
20057 Record && PreviousField &&
20058 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
20059 Record->getLocation());
20060 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20061 return FD->isBitField() && !FD->getType()->isDependentType();
20062 };
20063
20064 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20065 IsNonDependentBitField(PreviousField)) {
20066 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
20067 CharUnits PreviousFieldStorageSize =
20068 Context.getTypeSizeInChars(PreviousField->getType());
20069 if (FDStorageSize != PreviousFieldStorageSize) {
20070 Diag(FD->getLocation(),
20071 diag::warn_ms_bitfield_mismatched_storage_packing)
20072 << FD << FD->getType() << FDStorageSize.getQuantity()
20073 << PreviousFieldStorageSize.getQuantity();
20074 Diag(PreviousField->getLocation(),
20075 diag::note_ms_bitfield_mismatched_storage_size_previous)
20076 << PreviousField << PreviousField->getType();
20077 }
20078 }
20079 // Keep track of the number of named members.
20080 if (FD->getIdentifier())
20081 ++NumNamedMembers;
20082 }
20083
20084 // Okay, we successfully defined 'Record'.
20085 if (Record) {
20086 bool Completed = false;
20087 if (S) {
20088 Scope *Parent = S->getParent();
20089 if (Parent && Parent->isTypeAliasScope() &&
20090 Parent->isTemplateParamScope())
20091 Record->setInvalidDecl();
20092 }
20093
20094 if (CXXRecord) {
20095 if (!CXXRecord->isInvalidDecl()) {
20096 // Set access bits correctly on the directly-declared conversions.
20098 I = CXXRecord->conversion_begin(),
20099 E = CXXRecord->conversion_end(); I != E; ++I)
20100 I.setAccess((*I)->getAccess());
20101 }
20102
20103 // Add any implicitly-declared members to this class.
20105
20106 if (!CXXRecord->isDependentType()) {
20107 if (!CXXRecord->isInvalidDecl()) {
20108 // If we have virtual base classes, we may end up finding multiple
20109 // final overriders for a given virtual function. Check for this
20110 // problem now.
20111 if (CXXRecord->getNumVBases()) {
20112 CXXFinalOverriderMap FinalOverriders;
20113 CXXRecord->getFinalOverriders(FinalOverriders);
20114
20115 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20116 MEnd = FinalOverriders.end();
20117 M != MEnd; ++M) {
20118 for (OverridingMethods::iterator SO = M->second.begin(),
20119 SOEnd = M->second.end();
20120 SO != SOEnd; ++SO) {
20121 assert(SO->second.size() > 0 &&
20122 "Virtual function without overriding functions?");
20123 if (SO->second.size() == 1)
20124 continue;
20125
20126 // C++ [class.virtual]p2:
20127 // In a derived class, if a virtual member function of a base
20128 // class subobject has more than one final overrider the
20129 // program is ill-formed.
20130 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
20131 << (const NamedDecl *)M->first << Record;
20132 Diag(M->first->getLocation(),
20133 diag::note_overridden_virtual_function);
20135 OM = SO->second.begin(),
20136 OMEnd = SO->second.end();
20137 OM != OMEnd; ++OM)
20138 Diag(OM->Method->getLocation(), diag::note_final_overrider)
20139 << (const NamedDecl *)M->first << OM->Method->getParent();
20140
20141 Record->setInvalidDecl();
20142 }
20143 }
20144 CXXRecord->completeDefinition(&FinalOverriders);
20145 Completed = true;
20146 }
20147 }
20148 ComputeSelectedDestructor(*this, CXXRecord);
20150 }
20151 }
20152
20153 if (!Completed)
20154 Record->completeDefinition();
20155
20156 // Handle attributes before checking the layout.
20158
20159 // Maybe randomize the record's decls. We automatically randomize a record
20160 // of function pointers, unless it has the "no_randomize_layout" attribute.
20161 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20162 !Record->isRandomized() && !Record->isUnion() &&
20163 (Record->hasAttr<RandomizeLayoutAttr>() ||
20164 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20165 EntirelyFunctionPointers(Record)))) {
20166 SmallVector<Decl *, 32> NewDeclOrdering;
20168 NewDeclOrdering))
20169 Record->reorderDecls(NewDeclOrdering);
20170 }
20171
20172 // We may have deferred checking for a deleted destructor. Check now.
20173 if (CXXRecord) {
20174 auto *Dtor = CXXRecord->getDestructor();
20175 if (Dtor && Dtor->isImplicit() &&
20177 CXXRecord->setImplicitDestructorIsDeleted();
20178 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20179 }
20180 }
20181
20182 if (Record->hasAttrs()) {
20184
20185 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20187 IA->getRange(), IA->getBestCase(),
20188 IA->getInheritanceModel());
20189 }
20190
20191 // Check if the structure/union declaration is a type that can have zero
20192 // size in C. For C this is a language extension, for C++ it may cause
20193 // compatibility problems.
20194 bool CheckForZeroSize;
20195 if (!getLangOpts().CPlusPlus) {
20196 CheckForZeroSize = true;
20197 } else {
20198 // For C++ filter out types that cannot be referenced in C code.
20200 CheckForZeroSize =
20201 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20202 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20203 CXXRecord->isCLike();
20204 }
20205 if (CheckForZeroSize) {
20206 bool ZeroSize = true;
20207 bool IsEmpty = true;
20208 unsigned NonBitFields = 0;
20209 for (RecordDecl::field_iterator I = Record->field_begin(),
20210 E = Record->field_end();
20211 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20212 IsEmpty = false;
20213 if (I->isUnnamedBitField()) {
20214 if (!I->isZeroLengthBitField())
20215 ZeroSize = false;
20216 } else {
20217 ++NonBitFields;
20218 QualType FieldType = I->getType();
20219 if (FieldType->isIncompleteType() ||
20220 !Context.getTypeSizeInChars(FieldType).isZero())
20221 ZeroSize = false;
20222 }
20223 }
20224
20225 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20226 // allowed in C++, but warn if its declaration is inside
20227 // extern "C" block.
20228 if (ZeroSize) {
20229 Diag(RecLoc, getLangOpts().CPlusPlus ?
20230 diag::warn_zero_size_struct_union_in_extern_c :
20231 diag::warn_zero_size_struct_union_compat)
20232 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20233 }
20234
20235 // Structs without named members are extension in C (C99 6.7.2.1p7),
20236 // but are accepted by GCC. In C2y, this became implementation-defined
20237 // (C2y 6.7.3.2p10).
20238 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20239 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20240 : diag::ext_no_named_members_in_struct_union)
20241 << Record->isUnion();
20242 }
20243 }
20244 } else {
20245 ObjCIvarDecl **ClsFields =
20246 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20247 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20248 ID->setEndOfDefinitionLoc(RBrac);
20249 // Add ivar's to class's DeclContext.
20250 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20251 ClsFields[i]->setLexicalDeclContext(ID);
20252 ID->addDecl(ClsFields[i]);
20253 }
20254 // Must enforce the rule that ivars in the base classes may not be
20255 // duplicates.
20256 if (ID->getSuperClass())
20257 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20258 } else if (ObjCImplementationDecl *IMPDecl =
20259 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20260 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20261 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20262 // Ivar declared in @implementation never belongs to the implementation.
20263 // Only it is in implementation's lexical context.
20264 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20265 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20266 RBrac);
20267 IMPDecl->setIvarLBraceLoc(LBrac);
20268 IMPDecl->setIvarRBraceLoc(RBrac);
20269 } else if (ObjCCategoryDecl *CDecl =
20270 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20271 // case of ivars in class extension; all other cases have been
20272 // reported as errors elsewhere.
20273 // FIXME. Class extension does not have a LocEnd field.
20274 // CDecl->setLocEnd(RBrac);
20275 // Add ivar's to class extension's DeclContext.
20276 // Diagnose redeclaration of private ivars.
20277 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20278 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20279 if (IDecl) {
20280 if (const ObjCIvarDecl *ClsIvar =
20281 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20282 Diag(ClsFields[i]->getLocation(),
20283 diag::err_duplicate_ivar_declaration);
20284 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20285 continue;
20286 }
20287 for (const auto *Ext : IDecl->known_extensions()) {
20288 if (const ObjCIvarDecl *ClsExtIvar
20289 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20290 Diag(ClsFields[i]->getLocation(),
20291 diag::err_duplicate_ivar_declaration);
20292 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20293 continue;
20294 }
20295 }
20296 }
20297 ClsFields[i]->setLexicalDeclContext(CDecl);
20298 CDecl->addDecl(ClsFields[i]);
20299 }
20300 CDecl->setIvarLBraceLoc(LBrac);
20301 CDecl->setIvarRBraceLoc(RBrac);
20302 }
20303 }
20306}
20307
20308// Given an integral type, return the next larger integral type
20309// (or a NULL type of no such type exists).
20311 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20312 // enum checking below.
20313 assert((T->isIntegralType(Context) ||
20314 T->isEnumeralType()) && "Integral type required!");
20315 const unsigned NumTypes = 4;
20316 QualType SignedIntegralTypes[NumTypes] = {
20317 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20318 };
20319 QualType UnsignedIntegralTypes[NumTypes] = {
20320 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20321 Context.UnsignedLongLongTy
20322 };
20323
20324 unsigned BitWidth = Context.getTypeSize(T);
20325 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20326 : UnsignedIntegralTypes;
20327 for (unsigned I = 0; I != NumTypes; ++I)
20328 if (Context.getTypeSize(Types[I]) > BitWidth)
20329 return Types[I];
20330
20331 return QualType();
20332}
20333
20335 EnumConstantDecl *LastEnumConst,
20336 SourceLocation IdLoc,
20337 IdentifierInfo *Id,
20338 Expr *Val) {
20339 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20340 llvm::APSInt EnumVal(IntWidth);
20341 QualType EltTy;
20342
20344 Val = nullptr;
20345
20346 if (Val)
20347 Val = DefaultLvalueConversion(Val).get();
20348
20349 if (Val) {
20350 if (Enum->isDependentType() || Val->isTypeDependent() ||
20351 Val->containsErrors())
20352 EltTy = Context.DependentTy;
20353 else {
20354 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20355 // underlying type, but do allow it in all other contexts.
20356 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20357 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20358 // constant-expression in the enumerator-definition shall be a converted
20359 // constant expression of the underlying type.
20360 EltTy = Enum->getIntegerType();
20362 Val, EltTy, EnumVal, CCEKind::Enumerator);
20363 if (Converted.isInvalid())
20364 Val = nullptr;
20365 else
20366 Val = Converted.get();
20367 } else if (!Val->isValueDependent() &&
20368 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20370 .get())) {
20371 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20372 } else {
20373 if (Enum->isComplete()) {
20374 EltTy = Enum->getIntegerType();
20375
20376 // In Obj-C and Microsoft mode, require the enumeration value to be
20377 // representable in the underlying type of the enumeration. In C++11,
20378 // we perform a non-narrowing conversion as part of converted constant
20379 // expression checking.
20380 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20381 if (Context.getTargetInfo()
20382 .getTriple()
20383 .isWindowsMSVCEnvironment()) {
20384 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20385 } else {
20386 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20387 }
20388 }
20389
20390 // Cast to the underlying type.
20391 Val = ImpCastExprToType(Val, EltTy,
20392 EltTy->isBooleanType() ? CK_IntegralToBoolean
20393 : CK_IntegralCast)
20394 .get();
20395 } else if (getLangOpts().CPlusPlus) {
20396 // C++11 [dcl.enum]p5:
20397 // If the underlying type is not fixed, the type of each enumerator
20398 // is the type of its initializing value:
20399 // - If an initializer is specified for an enumerator, the
20400 // initializing value has the same type as the expression.
20401 EltTy = Val->getType();
20402 } else {
20403 // C99 6.7.2.2p2:
20404 // The expression that defines the value of an enumeration constant
20405 // shall be an integer constant expression that has a value
20406 // representable as an int.
20407
20408 // Complain if the value is not representable in an int.
20409 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20410 Diag(IdLoc, getLangOpts().C23
20411 ? diag::warn_c17_compat_enum_value_not_int
20412 : diag::ext_c23_enum_value_not_int)
20413 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20414 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20415 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20416 // Force the type of the expression to 'int'.
20417 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20418 }
20419 EltTy = Val->getType();
20420 }
20421 }
20422 }
20423 }
20424
20425 if (!Val) {
20426 if (Enum->isDependentType())
20427 EltTy = Context.DependentTy;
20428 else if (!LastEnumConst) {
20429 // C++0x [dcl.enum]p5:
20430 // If the underlying type is not fixed, the type of each enumerator
20431 // is the type of its initializing value:
20432 // - If no initializer is specified for the first enumerator, the
20433 // initializing value has an unspecified integral type.
20434 //
20435 // GCC uses 'int' for its unspecified integral type, as does
20436 // C99 6.7.2.2p3.
20437 if (Enum->isFixed()) {
20438 EltTy = Enum->getIntegerType();
20439 }
20440 else {
20441 EltTy = Context.IntTy;
20442 }
20443 } else {
20444 // Assign the last value + 1.
20445 EnumVal = LastEnumConst->getInitVal();
20446 ++EnumVal;
20447 EltTy = LastEnumConst->getType();
20448
20449 // Check for overflow on increment.
20450 if (EnumVal < LastEnumConst->getInitVal()) {
20451 // C++0x [dcl.enum]p5:
20452 // If the underlying type is not fixed, the type of each enumerator
20453 // is the type of its initializing value:
20454 //
20455 // - Otherwise the type of the initializing value is the same as
20456 // the type of the initializing value of the preceding enumerator
20457 // unless the incremented value is not representable in that type,
20458 // in which case the type is an unspecified integral type
20459 // sufficient to contain the incremented value. If no such type
20460 // exists, the program is ill-formed.
20462 if (T.isNull() || Enum->isFixed()) {
20463 // There is no integral type larger enough to represent this
20464 // value. Complain, then allow the value to wrap around.
20465 EnumVal = LastEnumConst->getInitVal();
20466 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20467 ++EnumVal;
20468 if (Enum->isFixed())
20469 // When the underlying type is fixed, this is ill-formed.
20470 Diag(IdLoc, diag::err_enumerator_wrapped)
20471 << toString(EnumVal, 10)
20472 << EltTy;
20473 else
20474 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20475 << toString(EnumVal, 10);
20476 } else {
20477 EltTy = T;
20478 }
20479
20480 // Retrieve the last enumerator's value, extent that type to the
20481 // type that is supposed to be large enough to represent the incremented
20482 // value, then increment.
20483 EnumVal = LastEnumConst->getInitVal();
20484 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20485 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20486 ++EnumVal;
20487
20488 // If we're not in C++, diagnose the overflow of enumerator values,
20489 // which in C99 means that the enumerator value is not representable in
20490 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20491 // are representable in some larger integral type and we allow it in
20492 // older language modes as an extension.
20493 // Exclude fixed enumerators since they are diagnosed with an error for
20494 // this case.
20495 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20496 Diag(IdLoc, getLangOpts().C23
20497 ? diag::warn_c17_compat_enum_value_not_int
20498 : diag::ext_c23_enum_value_not_int)
20499 << 1 << toString(EnumVal, 10) << 1;
20500 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20501 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20502 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20503 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20504 : diag::ext_c23_enum_value_not_int)
20505 << 1 << toString(EnumVal, 10) << 1;
20506 }
20507 }
20508 }
20509
20510 if (!EltTy->isDependentType()) {
20511 // Make the enumerator value match the signedness and size of the
20512 // enumerator's type.
20513 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20514 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20515 }
20516
20517 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20518 Val, EnumVal);
20519}
20520
20522 SourceLocation IILoc) {
20523 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20525 return SkipBodyInfo();
20526
20527 // We have an anonymous enum definition. Look up the first enumerator to
20528 // determine if we should merge the definition with an existing one and
20529 // skip the body.
20530 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20532 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20533 if (!PrevECD)
20534 return SkipBodyInfo();
20535
20536 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20537 NamedDecl *Hidden;
20538 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20540 Skip.Previous = Hidden;
20541 return Skip;
20542 }
20543
20544 return SkipBodyInfo();
20545}
20546
20547Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20548 SourceLocation IdLoc, IdentifierInfo *Id,
20549 const ParsedAttributesView &Attrs,
20550 SourceLocation EqualLoc, Expr *Val,
20551 SkipBodyInfo *SkipBody) {
20552 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20553 EnumConstantDecl *LastEnumConst =
20554 cast_or_null<EnumConstantDecl>(lastEnumConst);
20555
20556 // The scope passed in may not be a decl scope. Zip up the scope tree until
20557 // we find one that is.
20558 S = getNonFieldDeclScope(S);
20559
20560 // Verify that there isn't already something declared with this name in this
20561 // scope.
20562 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20564 LookupName(R, S);
20565 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20566
20567 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20568 // Maybe we will complain about the shadowed template parameter.
20569 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20570 // Just pretend that we didn't see the previous declaration.
20571 PrevDecl = nullptr;
20572 }
20573
20574 // C++ [class.mem]p15:
20575 // If T is the name of a class, then each of the following shall have a name
20576 // different from T:
20577 // - every enumerator of every member of class T that is an unscoped
20578 // enumerated type
20579 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20581 DeclarationNameInfo(Id, IdLoc)))
20582 return nullptr;
20583
20585 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20586 if (!New)
20587 return nullptr;
20588
20589 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20590 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20591 // Check for other kinds of shadowing not already handled.
20592 CheckShadow(New, PrevDecl, R);
20593 }
20594
20595 // When in C++, we may get a TagDecl with the same name; in this case the
20596 // enum constant will 'hide' the tag.
20597 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20598 "Received TagDecl when not in C++!");
20599 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20600 if (isa<EnumConstantDecl>(PrevDecl))
20601 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20602 else
20603 Diag(IdLoc, diag::err_redefinition) << Id;
20604 notePreviousDefinition(PrevDecl, IdLoc);
20605 return nullptr;
20606 }
20607 }
20608
20609 // Process attributes.
20610 ProcessDeclAttributeList(S, New, Attrs);
20613
20614 // Register this decl in the current scope stack.
20615 New->setAccess(TheEnumDecl->getAccess());
20617
20619
20620 return New;
20621}
20622
20623// Returns true when the enum initial expression does not trigger the
20624// duplicate enum warning. A few common cases are exempted as follows:
20625// Element2 = Element1
20626// Element2 = Element1 + 1
20627// Element2 = Element1 - 1
20628// Where Element2 and Element1 are from the same enum.
20630 Expr *InitExpr = ECD->getInitExpr();
20631 if (!InitExpr)
20632 return true;
20633 InitExpr = InitExpr->IgnoreImpCasts();
20634
20635 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
20636 if (!BO->isAdditiveOp())
20637 return true;
20638 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
20639 if (!IL)
20640 return true;
20641 if (IL->getValue() != 1)
20642 return true;
20643
20644 InitExpr = BO->getLHS();
20645 }
20646
20647 // This checks if the elements are from the same enum.
20648 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
20649 if (!DRE)
20650 return true;
20651
20652 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
20653 if (!EnumConstant)
20654 return true;
20655
20657 Enum)
20658 return true;
20659
20660 return false;
20661}
20662
20663// Emits a warning when an element is implicitly set a value that
20664// a previous element has already been set to.
20666 EnumDecl *Enum, QualType EnumType) {
20667 // Avoid anonymous enums
20668 if (!Enum->getIdentifier())
20669 return;
20670
20671 // Only check for small enums.
20672 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
20673 return;
20674
20675 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
20676 return;
20677
20678 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
20679 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
20680
20681 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
20682
20683 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
20684 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
20685
20686 // Use int64_t as a key to avoid needing special handling for map keys.
20687 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
20688 llvm::APSInt Val = D->getInitVal();
20689 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
20690 };
20691
20692 DuplicatesVector DupVector;
20693 ValueToVectorMap EnumMap;
20694
20695 // Populate the EnumMap with all values represented by enum constants without
20696 // an initializer.
20697 for (auto *Element : Elements) {
20698 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
20699
20700 // Null EnumConstantDecl means a previous diagnostic has been emitted for
20701 // this constant. Skip this enum since it may be ill-formed.
20702 if (!ECD) {
20703 return;
20704 }
20705
20706 // Constants with initializers are handled in the next loop.
20707 if (ECD->getInitExpr())
20708 continue;
20709
20710 // Duplicate values are handled in the next loop.
20711 EnumMap.insert({EnumConstantToKey(ECD), ECD});
20712 }
20713
20714 if (EnumMap.size() == 0)
20715 return;
20716
20717 // Create vectors for any values that has duplicates.
20718 for (auto *Element : Elements) {
20719 // The last loop returned if any constant was null.
20721 if (!ValidDuplicateEnum(ECD, Enum))
20722 continue;
20723
20724 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
20725 if (Iter == EnumMap.end())
20726 continue;
20727
20728 DeclOrVector& Entry = Iter->second;
20729 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
20730 // Ensure constants are different.
20731 if (D == ECD)
20732 continue;
20733
20734 // Create new vector and push values onto it.
20735 auto Vec = std::make_unique<ECDVector>();
20736 Vec->push_back(D);
20737 Vec->push_back(ECD);
20738
20739 // Update entry to point to the duplicates vector.
20740 Entry = Vec.get();
20741
20742 // Store the vector somewhere we can consult later for quick emission of
20743 // diagnostics.
20744 DupVector.emplace_back(std::move(Vec));
20745 continue;
20746 }
20747
20748 ECDVector *Vec = cast<ECDVector *>(Entry);
20749 // Make sure constants are not added more than once.
20750 if (*Vec->begin() == ECD)
20751 continue;
20752
20753 Vec->push_back(ECD);
20754 }
20755
20756 // Emit diagnostics.
20757 for (const auto &Vec : DupVector) {
20758 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
20759
20760 // Emit warning for one enum constant.
20761 auto *FirstECD = Vec->front();
20762 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
20763 << FirstECD << toString(FirstECD->getInitVal(), 10)
20764 << FirstECD->getSourceRange();
20765
20766 // Emit one note for each of the remaining enum constants with
20767 // the same value.
20768 for (auto *ECD : llvm::drop_begin(*Vec))
20769 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
20770 << ECD << toString(ECD->getInitVal(), 10)
20771 << ECD->getSourceRange();
20772 }
20773}
20774
20775bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
20776 bool AllowMask) const {
20777 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
20778 assert(ED->isCompleteDefinition() && "expected enum definition");
20779
20780 auto R = FlagBitsCache.try_emplace(ED);
20781 llvm::APInt &FlagBits = R.first->second;
20782
20783 if (R.second) {
20784 for (auto *E : ED->enumerators()) {
20785 const auto &EVal = E->getInitVal();
20786 // Only single-bit enumerators introduce new flag values.
20787 if (EVal.isPowerOf2())
20788 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
20789 }
20790 }
20791
20792 // A value is in a flag enum if either its bits are a subset of the enum's
20793 // flag bits (the first condition) or we are allowing masks and the same is
20794 // true of its complement (the second condition). When masks are allowed, we
20795 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
20796 //
20797 // While it's true that any value could be used as a mask, the assumption is
20798 // that a mask will have all of the insignificant bits set. Anything else is
20799 // likely a logic error.
20800 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
20801 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
20802}
20803
20804// Emits a warning when a suspicious comparison operator is used along side
20805// binary operators in enum initializers.
20807 const EnumDecl *Enum) {
20808 bool HasBitwiseOp = false;
20809 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
20810
20811 // Iterate over all the enum values, gather suspisious comparison ops and
20812 // whether any enum initialisers contain a binary operator.
20813 for (const auto *ECD : Enum->enumerators()) {
20814 const Expr *InitExpr = ECD->getInitExpr();
20815 if (!InitExpr)
20816 continue;
20817
20818 const Expr *E = InitExpr->IgnoreParenImpCasts();
20819
20820 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
20821 BinaryOperatorKind Op = BinOp->getOpcode();
20822
20823 // Check for bitwise ops (<<, >>, &, |)
20824 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
20825 HasBitwiseOp = true;
20826 } else if (Op == BO_LT || Op == BO_GT) {
20827 // Check for the typo pattern (Comparison < or >)
20828 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
20829 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
20830 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
20831 if (IntLiteral->getValue() == 1)
20832 SuspiciousCompares.push_back(BinOp);
20833 }
20834 }
20835 }
20836 }
20837
20838 // If we found a bitwise op and some sus compares, iterate over the compares
20839 // and warn.
20840 if (HasBitwiseOp) {
20841 for (const auto *BinOp : SuspiciousCompares) {
20842 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
20845 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
20846
20847 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
20848 << BinOp->getOpcodeStr() << SuggestedOp;
20849
20850 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
20851 << SuggestedOp
20852 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
20853 }
20854 }
20855}
20856
20858 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
20859 const ParsedAttributesView &Attrs) {
20860 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
20861 CanQualType EnumType = Context.getCanonicalTagType(Enum);
20862
20863 ProcessDeclAttributeList(S, Enum, Attrs);
20865
20866 if (Enum->isDependentType()) {
20867 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
20868 EnumConstantDecl *ECD =
20869 cast_or_null<EnumConstantDecl>(Elements[i]);
20870 if (!ECD) continue;
20871
20872 ECD->setType(EnumType);
20873 }
20874
20875 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
20876 return;
20877 }
20878
20879 // Verify that all the values are okay, compute the size of the values, and
20880 // reverse the list.
20881 unsigned NumNegativeBits = 0;
20882 unsigned NumPositiveBits = 0;
20883 bool MembersRepresentableByInt =
20884 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
20885
20886 // Figure out the type that should be used for this enum.
20887 QualType BestType;
20888 unsigned BestWidth;
20889
20890 // C++0x N3000 [conv.prom]p3:
20891 // An rvalue of an unscoped enumeration type whose underlying
20892 // type is not fixed can be converted to an rvalue of the first
20893 // of the following types that can represent all the values of
20894 // the enumeration: int, unsigned int, long int, unsigned long
20895 // int, long long int, or unsigned long long int.
20896 // C99 6.4.4.3p2:
20897 // An identifier declared as an enumeration constant has type int.
20898 // The C99 rule is modified by C23.
20899 QualType BestPromotionType;
20900
20901 bool Packed = Enum->hasAttr<PackedAttr>();
20902 // -fshort-enums is the equivalent to specifying the packed attribute on all
20903 // enum definitions.
20904 if (LangOpts.ShortEnums)
20905 Packed = true;
20906
20907 // If the enum already has a type because it is fixed or dictated by the
20908 // target, promote that type instead of analyzing the enumerators.
20909 if (Enum->isComplete()) {
20910 BestType = Enum->getIntegerType();
20911 if (Context.isPromotableIntegerType(BestType))
20912 BestPromotionType = Context.getPromotedIntegerType(BestType);
20913 else
20914 BestPromotionType = BestType;
20915
20916 BestWidth = Context.getIntWidth(BestType);
20917 } else {
20918 bool EnumTooLarge = Context.computeBestEnumTypes(
20919 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
20920 BestWidth = Context.getIntWidth(BestType);
20921 if (EnumTooLarge)
20922 Diag(Enum->getLocation(), diag::ext_enum_too_large);
20923 }
20924
20925 // Loop over all of the enumerator constants, changing their types to match
20926 // the type of the enum if needed.
20927 for (auto *D : Elements) {
20928 auto *ECD = cast_or_null<EnumConstantDecl>(D);
20929 if (!ECD) continue; // Already issued a diagnostic.
20930
20931 // C99 says the enumerators have int type, but we allow, as an
20932 // extension, the enumerators to be larger than int size. If each
20933 // enumerator value fits in an int, type it as an int, otherwise type it the
20934 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
20935 // that X has type 'int', not 'unsigned'.
20936
20937 // Determine whether the value fits into an int.
20938 llvm::APSInt InitVal = ECD->getInitVal();
20939
20940 // If it fits into an integer type, force it. Otherwise force it to match
20941 // the enum decl type.
20942 QualType NewTy;
20943 unsigned NewWidth;
20944 bool NewSign;
20945 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
20946 MembersRepresentableByInt) {
20947 // C23 6.7.3.3.3p15:
20948 // The enumeration member type for an enumerated type without fixed
20949 // underlying type upon completion is:
20950 // - int if all the values of the enumeration are representable as an
20951 // int; or,
20952 // - the enumerated type
20953 NewTy = Context.IntTy;
20954 NewWidth = Context.getTargetInfo().getIntWidth();
20955 NewSign = true;
20956 } else if (ECD->getType() == BestType) {
20957 // Already the right type!
20958 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
20959 // C++ [dcl.enum]p4: Following the closing brace of an
20960 // enum-specifier, each enumerator has the type of its
20961 // enumeration.
20962 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20963 // with fixed underlying type is the enumerated type.
20964 ECD->setType(EnumType);
20965 continue;
20966 } else {
20967 NewTy = BestType;
20968 NewWidth = BestWidth;
20969 NewSign = BestType->isSignedIntegerOrEnumerationType();
20970 }
20971
20972 // Adjust the APSInt value.
20973 InitVal = InitVal.extOrTrunc(NewWidth);
20974 InitVal.setIsSigned(NewSign);
20975 ECD->setInitVal(Context, InitVal);
20976
20977 // Adjust the Expr initializer and type.
20978 if (ECD->getInitExpr() &&
20979 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
20980 ECD->setInitExpr(ImplicitCastExpr::Create(
20981 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
20982 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
20983 if (getLangOpts().CPlusPlus ||
20984 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
20985 // C++ [dcl.enum]p4: Following the closing brace of an
20986 // enum-specifier, each enumerator has the type of its
20987 // enumeration.
20988 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
20989 // with fixed underlying type is the enumerated type.
20990 ECD->setType(EnumType);
20991 else
20992 ECD->setType(NewTy);
20993 }
20994
20995 Enum->completeDefinition(BestType, BestPromotionType,
20996 NumPositiveBits, NumNegativeBits);
20997
20998 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
21000
21001 if (Enum->isClosedFlag()) {
21002 for (Decl *D : Elements) {
21003 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
21004 if (!ECD) continue; // Already issued a diagnostic.
21005
21006 llvm::APSInt InitVal = ECD->getInitVal();
21007 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21008 !IsValueInFlagEnum(Enum, InitVal, true))
21009 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
21010 << ECD << Enum;
21011 }
21012 }
21013
21014 // Now that the enum type is defined, ensure it's not been underaligned.
21015 if (Enum->hasAttrs())
21017}
21018
21020 SourceLocation EndLoc) {
21021
21023 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
21024 CurContext->addDecl(New);
21025 return New;
21026}
21027
21029 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
21030 CurContext->addDecl(New);
21031 PushDeclContext(S, New);
21033 PushCompoundScope(false);
21034 return New;
21035}
21036
21038 if (Statement)
21039 D->setStmt(Statement);
21043}
21044
21046 IdentifierInfo* AliasName,
21047 SourceLocation PragmaLoc,
21048 SourceLocation NameLoc,
21049 SourceLocation AliasNameLoc) {
21050 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
21052 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21054 AsmLabelAttr *Attr =
21055 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
21056
21057 // If a declaration that:
21058 // 1) declares a function or a variable
21059 // 2) has external linkage
21060 // already exists, add a label attribute to it.
21061 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21062 if (isDeclExternC(PrevDecl))
21063 PrevDecl->addAttr(Attr);
21064 else
21065 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
21066 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
21067 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21068 } else
21069 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
21070}
21071
21073 SourceLocation PragmaLoc,
21074 SourceLocation NameLoc) {
21075 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
21076
21077 if (PrevDecl) {
21078 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
21079 } else {
21080 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
21081 }
21082}
21083
21085 IdentifierInfo* AliasName,
21086 SourceLocation PragmaLoc,
21087 SourceLocation NameLoc,
21088 SourceLocation AliasNameLoc) {
21089 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
21091 WeakInfo W = WeakInfo(Name, NameLoc);
21092
21093 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21094 if (!PrevDecl->hasAttr<AliasAttr>())
21095 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
21097 } else {
21098 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
21099 }
21100}
21101
21103 bool Final) {
21104 assert(FD && "Expected non-null FunctionDecl");
21105
21106 // Templates are emitted when they're instantiated.
21107 if (FD->isDependentContext())
21109
21110 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21111 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21112 FD->hasAttr<SYCLExternalAttr>()))
21114
21115 // Check whether this function is an externally visible definition.
21116 auto IsEmittedForExternalSymbol = [this, FD]() {
21117 // We have to check the GVA linkage of the function's *definition* -- if we
21118 // only have a declaration, we don't know whether or not the function will
21119 // be emitted, because (say) the definition could include "inline".
21120 const FunctionDecl *Def = FD->getDefinition();
21121
21122 // We can't compute linkage when we skip function bodies.
21123 return Def && !Def->hasSkippedBody() &&
21125 getASTContext().GetGVALinkageForFunction(Def));
21126 };
21127
21128 if (LangOpts.OpenMPIsTargetDevice) {
21129 // In OpenMP device mode we will not emit host only functions, or functions
21130 // we don't need due to their linkage.
21131 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21132 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21133 // DevTy may be changed later by
21134 // #pragma omp declare target to(*) device_type(*).
21135 // Therefore DevTy having no value does not imply host. The emission status
21136 // will be checked again at the end of compilation unit with Final = true.
21137 if (DevTy)
21138 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21140 // If we have an explicit value for the device type, or we are in a target
21141 // declare context, we need to emit all extern and used symbols.
21142 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21143 if (IsEmittedForExternalSymbol())
21145 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21146 // we'll omit it.
21147 if (Final)
21149 } else if (LangOpts.OpenMP > 45) {
21150 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21151 // function. In 5.0, no_host was introduced which might cause a function to
21152 // be omitted.
21153 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21154 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21155 if (DevTy)
21156 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21158 }
21159
21160 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21162
21163 if (LangOpts.CUDA) {
21164 // When compiling for device, host functions are never emitted. Similarly,
21165 // when compiling for host, device and global functions are never emitted.
21166 // (Technically, we do emit a host-side stub for global functions, but this
21167 // doesn't count for our purposes here.)
21169 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21171 if (!LangOpts.CUDAIsDevice &&
21174
21175 if (IsEmittedForExternalSymbol())
21177
21178 // If FD is a virtual destructor of an explicit instantiation
21179 // of a template class, return Emitted.
21180 if (auto *Destructor = dyn_cast<CXXDestructorDecl>(FD)) {
21181 if (Destructor->isVirtual()) {
21182 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(
21183 Destructor->getParent())) {
21185 Spec->getTemplateSpecializationKind();
21189 }
21190 }
21191 }
21192 }
21193
21194 // Otherwise, the function is known-emitted if it's in our set of
21195 // known-emitted functions.
21197}
21198
21200 // Host-side references to a __global__ function refer to the stub, so the
21201 // function itself is never emitted and therefore should not be marked.
21202 // If we have host fn calls kernel fn calls host+device, the HD function
21203 // does not get instantiated on the host. We model this by omitting at the
21204 // call to the kernel from the callgraph. This ensures that, when compiling
21205 // for host, only HD functions actually called from the host get marked as
21206 // known-emitted.
21207 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21209}
21210
21212 bool &Visible) {
21213 Visible = hasVisibleDefinition(D, Suggested);
21214 // The redefinition of D in the **current** TU is allowed if D is invisible or
21215 // D is defined in the global module of other module units. We didn't check if
21216 // it is in global module as, we'll check the redefinition in named module
21217 // later with better diagnostic message.
21218 return D->isInAnotherModuleUnit() || !Visible;
21219}
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:2241
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)
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:74
#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 ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:187
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:179
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:234
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:845
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:609
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:628
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:860
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 isMainFileLoc(const Sema &S, SourceLocation Loc)
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:226
SourceManager & getSourceManager()
Definition ASTContext.h:858
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:797
const LangOptions & getLangOpts() const
Definition ASTContext.h:951
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:916
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:3497
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:3730
QualType getElementType() const
Definition TypeBase.h:3742
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:4188
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4674
bool doesNotEscape() const
Definition Decl.h:4825
This class is used for builtin types like 'int'.
Definition TypeBase.h:3172
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:235
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:382
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:1692
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
Represents a C++ constructor within a class.
Definition DeclCXX.h:2611
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:3026
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:2986
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2946
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:3241
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:2876
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:3116
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:2136
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:2773
bool isVirtual() const
Definition DeclCXX.h:2191
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:2838
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2262
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2753
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2297
bool isConst() const
Definition DeclCXX.h:2188
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:2232
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:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:181
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:207
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:186
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:80
SourceLocation getBeginLoc() const
Definition DeclSpec.h:84
bool isSet() const
Deprecated.
Definition DeclSpec.h:199
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:95
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:184
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:179
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:3624
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:3768
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:215
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:255
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3824
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
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:1392
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
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:2142
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
bool isNamespace() const
Definition DeclBase.h:2198
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:2185
bool isRecord() const
Definition DeclBase.h:2189
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:2373
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
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:2102
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:218
bool isVirtualSpecified() const
Definition DeclSpec.h:653
bool isModulePrivateSpecified() const
Definition DeclSpec.h:834
static const TST TST_typeof_unqualType
Definition DeclSpec.h:280
bool hasAutoTypeSpec() const
Definition DeclSpec.h:578
static const TST TST_typename
Definition DeclSpec.h:277
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:235
void ClearStorageClassSpecs()
Definition DeclSpec.h:498
bool isNoreturnSpecified() const
Definition DeclSpec.h:666
TST getTypeSpecType() const
Definition DeclSpec.h:520
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:493
SCS getStorageClassSpec() const
Definition DeclSpec.h:484
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:558
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:557
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:714
static const TST TST_interface
Definition DeclSpec.h:275
static const TST TST_typeofExpr
Definition DeclSpec.h:279
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:600
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:713
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:667
bool isExternInLinkageSpec() const
Definition DeclSpec.h:488
static const TST TST_union
Definition DeclSpec.h:273
SCS
storage-class-specifier
Definition DeclSpec.h:222
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:659
static const TST TST_int
Definition DeclSpec.h:256
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:835
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:530
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:793
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:485
ParsedAttributes & getAttributes()
Definition DeclSpec.h:878
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:629
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:601
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:660
Expr * getRepAsExpr() const
Definition DeclSpec.h:538
static const TST TST_enum
Definition DeclSpec.h:272
static const TST TST_decltype
Definition DeclSpec.h:282
static bool isDeclRep(TST T)
Definition DeclSpec.h:451
bool isInlineSpecified() const
Definition DeclSpec.h:642
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:602
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:281
static const TST TST_class
Definition DeclSpec.h:276
TypeSpecifierType TST
Definition DeclSpec.h:248
static const TST TST_void
Definition DeclSpec.h:250
void ClearConstexprSpec()
Definition DeclSpec.h:846
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:292
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:494
Decl * getRepAsDecl() const
Definition DeclSpec.h:534
static const TST TST_unspecified
Definition DeclSpec.h:249
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:604
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:654
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:841
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:565
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:797
static const TSCS TSCS_thread_local
Definition DeclSpec.h:238
static const TST TST_error
Definition DeclSpec.h:299
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclSpec.h:649
bool isTypeSpecOwned() const
Definition DeclSpec.h:524
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:645
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:605
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:603
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:826
bool hasExplicitSpecifier() const
Definition DeclSpec.h:656
bool hasConstexprSpecifier() const
Definition DeclSpec.h:842
static const TST TST_typeofType
Definition DeclSpec.h:278
static const TST TST_auto
Definition DeclSpec.h:289
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:837
static const TST TST_struct
Definition DeclSpec.h:274
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:1061
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1076
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:449
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:435
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
bool isFromGlobalModule() const
Whether this declaration comes from global module.
T * getAttr() const
Definition DeclBase.h:573
bool hasAttrs() const
Definition DeclBase.h:518
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:520
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition DeclBase.h:771
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:1151
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:638
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:893
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1219
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1218
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:600
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:842
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:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2793
bool isInvalidDecl() const
Definition DeclBase.h:588
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1169
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:594
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:575
DeclContext * getDeclContext()
Definition DeclBase.h:448
attr_range attrs() const
Definition DeclBase.h:535
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void dropAttr()
Definition DeclBase.h:556
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:1636
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1235
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
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:2062
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2102
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2000
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:2012
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:2046
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1921
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2477
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2419
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2068
Expr * getAsmLabel() const
Definition DeclSpec.h:2723
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2762
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2704
void setRedeclaration(bool Val)
Definition DeclSpec.h:2785
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2357
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2360
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2105
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2654
void takeAttributesAppending(ParsedAttributes &attrs)
takeAttributesAppending - Takes attributes from the given ParsedAttributes set and add them to this d...
Definition DeclSpec.h:2697
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2734
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2684
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2415
bool isRedeclaration() const
Definition DeclSpec.h:2786
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2707
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2089
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2104
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:410
bool isFunctionDefinition() const
Definition DeclSpec.h:2758
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2087
bool hasInitializer() const
Definition DeclSpec.h:2767
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2754
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2083
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2374
bool isInvalidType() const
Definition DeclSpec.h:2735
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2103
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2347
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2770
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:2075
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2508
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2351
A decomposition declaration.
Definition DeclCXX.h:4252
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3700
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1809
SourceRange getSourceRange() const
Definition DeclSpec.h:1857
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1855
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:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:959
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
llvm::APSInt getInitVal() const
Definition Decl.h:3443
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5712
const Expr * getInitExpr() const
Definition Decl.h:3441
Represents an enum.
Definition Decl.h:4013
enumerator_range enumerators() const
Definition Decl.h:4159
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4231
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4195
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4198
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4245
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5075
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5114
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4240
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5089
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4181
void setEnumKeyRange(SourceRange Range)
Definition Decl.h:4093
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4186
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:3090
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:3086
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:3070
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
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:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4716
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
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:4701
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4762
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5845
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
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:2189
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2476
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4206
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3734
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4199
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4194
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3299
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2314
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2701
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2680
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4025
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3763
param_iterator param_end()
Definition Decl.h:2787
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2695
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3707
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2389
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2377
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3615
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4314
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2448
void setWillHaveBody(bool V=true)
Definition Decl.h:2686
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:2594
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2443
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4324
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3748
param_iterator param_begin()
Definition Decl.h:2786
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2823
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2326
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2540
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3134
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3376
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4258
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2888
bool isStatic() const
Definition Decl.h:2929
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4527
void setTrivial(bool IT)
Definition Decl.h:2378
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4145
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:2470
bool isDeletedAsWritten() const
Definition Decl.h:2544
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2353
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3619
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2357
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:2428
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2349
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2679
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2282
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3369
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:2916
bool param_empty() const
Definition Decl.h:2785
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3224
void setRangeEnd(SourceLocation E)
Definition Decl.h:2218
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3703
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2385
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2421
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4550
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2933
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4139
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2473
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4418
void setDefaulted(bool D=true)
Definition Decl.h:2386
bool isConsteval() const
Definition Decl.h:2482
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:2862
void setBody(Stmt *B)
Definition Decl.cpp:3292
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3633
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3170
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2459
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4166
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3827
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2211
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3200
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2435
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:3247
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:2899
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3689
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2685
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5251
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5283
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5752
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5115
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
unsigned getNumParams() const
Definition TypeBase.h:5593
QualType getParamType(unsigned i) const
Definition TypeBase.h:5595
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5812
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5628
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5719
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5604
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5600
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.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
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:4622
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4734
CallingConv getCC() const
Definition TypeBase.h:4681
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4700
unsigned getRegParm() const
Definition TypeBase.h:4674
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4670
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4693
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4714
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4728
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4511
ExtInfo getExtInfo() const
Definition TypeBase.h:4867
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3646
unsigned getRegParmType() const
Definition TypeBase.h:4854
CallingConv getCallConv() const
Definition TypeBase.h:4866
QualType getReturnType() const
Definition TypeBase.h:4851
bool getCmseNSCallAttr() const
Definition TypeBase.h:4865
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:2073
Represents a C array with an unspecified size.
Definition TypeBase.h:3917
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5739
void setInherited(bool I)
Definition Attr.h:161
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2582
child_range children()
Definition Expr.h:5501
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:975
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:2084
@ 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 IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
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:1387
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3018
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3271
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:3661
Describes a module or submodule.
Definition Module.h:144
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:150
Module * Parent
The parent of this module.
Definition Module.h:193
bool isPrivateModule() const
Definition Module.h:249
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:648
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:664
bool isModulePartition() const
Is this a module partition.
Definition Module.h:653
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:224
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:722
@ 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:1870
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:706
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1942
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:3310
Represents a parameter to a function.
Definition Decl.h:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1854
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1823
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1882
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:2958
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2981
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:8206
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:3336
QualType getPointeeType() const
Definition TypeBase.h:3346
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:8472
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8466
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:1459
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2965
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:110
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1220
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1302
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:3031
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8388
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8514
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:8428
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1444
QualType getCanonicalType() const
Definition TypeBase.h:8440
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8482
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:3015
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition TypeBase.h:1439
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8461
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1683
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1551
bool isCanonical() const
Definition TypeBase.h:8445
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1315
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1448
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2738
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition TypeBase.h:1499
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition TypeBase.h:1504
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:8328
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8335
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4734
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:4327
field_range fields() const
Definition Decl.h:4530
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5233
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4527
field_iterator field_begin() const
Definition Decl.cpp:5276
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7502
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:5332
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3581
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3152
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3195
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 CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1532
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:758
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:212
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:846
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:911
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:923
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:689
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:655
void deduceAddressSpace(VarDecl *Decl)
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:758
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:725
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:669
void ActOnVariableDeclarator(VarDecl *VD)
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:1911
Mode getAlignMode() const
Definition Sema.h:1913
A RAII object to temporarily push a declaration context.
Definition Sema.h:3518
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1378
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1390
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3738
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3748
static NameClassification Unknown()
Definition Sema.h:3718
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3722
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3766
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3754
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3728
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3760
static NameClassification UndeclaredNonType()
Definition Sema.h:3734
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3742
static NameClassification Error()
Definition Sema.h:3714
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12520
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12554
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.
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:3616
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13117
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2560
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1133
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:8298
CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD)
Definition Sema.h:6359
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9381
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9385
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9404
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9420
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9417
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9393
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9388
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:1525
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...
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition Sema.h:1254
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:4788
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3598
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1837
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:6551
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:1465
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:281
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Preprocessor & getPreprocessor() const
Definition Sema.h:938
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2068
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2062
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:4191
@ Delete
deleted-function-body
Definition Sema.h:4197
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:1550
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:1674
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:686
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...
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:1300
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:225
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2350
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void * SkippedDefinitionContext
Definition Sema.h:4415
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1510
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1365
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:79
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2065
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:3606
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:2061
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:756
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:710
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:1204
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:1679
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:12218
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8416
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:799
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:2351
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:4626
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:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2369
void PopCompoundScope()
Definition Sema.cpp:2502
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:14495
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14498
@ UPPC_Initializer
An initializer.
Definition Sema.h:14510
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14504
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14483
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14522
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14507
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14486
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14489
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:2463
SourceLocation CurInitSegLoc
Definition Sema.h:2104
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:224
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:3623
SemaOpenACC & OpenACC()
Definition Sema.h:1515
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:1299
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:2141
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:1298
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:2578
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15584
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1475
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:1838
SemaRISCV & RISCV()
Definition Sema.h:1540
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:15761
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:214
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:1555
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:2050
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:7015
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2060
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1137
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:909
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:4803
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1333
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2497
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:7012
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:643
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:15578
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2103
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9911
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:1438
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1520
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:1654
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:3620
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:14029
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:3569
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:1839
@ NTCUK_Destruct
Definition Sema.h:4130
@ NTCUK_Init
Definition Sema.h:4129
@ NTCUK_Copy
Definition Sema.h:4131
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1836
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, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
MaybeODRUseExprSet MaybeODRUseExprs
Definition Sema.h:6812
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
TopLevelStmtDecl * ActOnStartTopLevelStmtDecl(Scope *S)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
void ProcessPragmaExport(DeclaratorDecl *newDecl)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor)
In the MS ABI, we need to instantiate default arguments of dllexported default constructors along wit...
void CheckCompleteVariableDeclaration(VarDecl *VD)
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2518
RedeclarationKind forRedeclarationInCurContext() const
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition Sema.h:6573
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition SemaDecl.cpp:638
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
llvm::DenseMap< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3594
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition SemaDecl.cpp:274
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
ASTConsumer & Consumer
Definition Sema.h:1301
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4689
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7019
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1338
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1800
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9939
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, const ParsedAttributesView &DeclAttrs, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
SemaPPC & PPC()
Definition Sema.h:1530
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition SemaStmt.cpp:75
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1259
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD)
Only called on function definitions; if there is a MSVC pragma optimize in scope, consider changing t...
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition Sema.h:3613
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8371
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D)
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1303
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, StringLiteral *Message=nullptr)
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD)
DiagnosticsEngine & Diags
Definition Sema.h:1302
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:933
FPOptions CurFPFeatures
Definition Sema.h:1296
static bool CanBeGetReturnObject(const FunctionDecl *FD)
NamespaceDecl * getStdNamespace() const
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD)
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2059
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
@ TPC_FriendFunctionTemplate
Definition Sema.h:11650
@ TPC_ClassTemplateMember
Definition Sema.h:11648
@ TPC_FunctionTemplate
Definition Sema.h:11647
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11651
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
friend class InitializationSequence
Definition Sema.h:1580
bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl)
Certain globally-unique variables might be accidentally duplicated if built into multiple shared libr...
void DiagnoseUnusedDecl(const NamedDecl *ND)
void PopDeclContext()
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6589
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak applied to it,...
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void ActOnUninitializedDecl(Decl *dcl)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionExceptionSpec - Checks whether the exception spec is a subset of base spec.
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void ActOnCXXForRangeDecl(Decl *D)
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckOverridingFunctionReturnType - Checks whether the return types are covariant,...
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition Sema.h:3588
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2124
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1835
Decl * ActOnDeclarator(Scope *S, Declarator &D)
@ AbstractVariableType
Definition Sema.h:6283
@ AbstractReturnType
Definition Sema.h:6281
@ AbstractFieldType
Definition Sema.h:6284
@ AbstractIvarType
Definition Sema.h:6285
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
void CheckAlignasUnderalignment(Decl *D)
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:8420
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6470
void CheckVariableDeclarationType(VarDecl *NewVD)
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1292
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New)
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
llvm::SmallPtrSet< const NamedDecl *, 4 > TypoCorrectedFunctionDefinitions
The function definitions which were renamed as part of typo-correction to match their respective decl...
Definition Sema.h:3565
void AddSectionMSAllocText(FunctionDecl *FD)
Only called on function definitions; if there is a #pragma alloc_text that decides which code section...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
SemaWasm & Wasm()
Definition Sema.h:1565
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, int FirstArg)
IdentifierResolver IdResolver
Definition Sema.h:3511
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2509
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:729
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:147
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition Sema.h:8379
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1291
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling)
TemplateNameKindForDiagnostics
Describes the detailed kind of a template name. Used in diagnostics.
Definition Sema.h:3861
void warnOnReservedIdentifier(const NamedDecl *D)
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
SemaARM & ARM()
Definition Sema.h:1445
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:326
AvailabilityAttr * mergeAvailabilityAttr(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)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8713
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
child_range children()
Definition Stmt.cpp:304
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:1948
StringRef getString() const
Definition Expr.h:1870
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition Decl.h:4005
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition Decl.cpp:4930
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3813
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3799
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3818
bool isStruct() const
Definition Decl.h:3925
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4902
bool isUnion() const
Definition Decl.h:3928
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3950
TagKind getTagKind() const
Definition Decl.h:3917
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3863
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual llvm::APInt getFMVPriority(ArrayRef< StringRef > Features) const
virtual bool validateCpuSupports(StringRef Name) const
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation getRAngleLoc() const
SourceLocation getTemplateLoc() const
Token - This structure provides full information about a lexed token.
Definition Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:104
bool isOneOf(Ts... Ks) const
Definition Token.h:105
bool isNot(tok::TokenKind K) const
Definition Token.h:111
A declaration that models statements at global scope.
Definition Decl.h:4637
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5863
void setStmt(Stmt *S)
Definition Decl.cpp:5883
Represents a declaration of a type.
Definition Decl.h:3513
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition TypeLoc.h:349
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1437
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:887
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8359
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8370
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1839
bool isStructureType() const
Definition Type.cpp:679
bool isDependentSizedArrayType() const
Definition TypeBase.h:8744
bool isVoidType() const
Definition TypeBase.h:8991
bool isBooleanType() const
Definition TypeBase.h:9128
bool isFunctionReferenceType() const
Definition TypeBase.h:8699
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2253
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9178
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3055
bool isIncompleteArrayType() const
Definition TypeBase.h:8732
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9294
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8728
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9158
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8724
bool isFunctionPointerType() const
Definition TypeBase.h:8692
bool isPointerType() const
Definition TypeBase.h:8625
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
bool isReferenceType() const
Definition TypeBase.h:8649
bool isScalarType() const
Definition TypeBase.h:9097
bool isVariableArrayType() const
Definition TypeBase.h:8736
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9113
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.h:63
bool isImageType() const
Definition TypeBase.h:8889
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2907
bool isOpenCLSpecificType() const
Definition TypeBase.h:8925
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2790
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2455
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isHalfType() const
Definition TypeBase.h:8995
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2073
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2601
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2784
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9171
bool isAtomicType() const
Definition TypeBase.h:8817
bool isFunctionProtoType() const
Definition TypeBase.h:2607
bool isObjCIdType() const
Definition TypeBase.h:8837
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2808
bool isObjCObjectType() const
Definition TypeBase.h:8808
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9134
bool isEventT() const
Definition TypeBase.h:8873
bool isPointerOrReferenceType() const
Definition TypeBase.h:8629
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2479
bool isFunctionType() const
Definition TypeBase.h:8621
bool isObjCObjectPointerType() const
Definition TypeBase.h:8804
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8710
bool isFloatingType() const
Definition Type.cpp:2341
bool isAnyPointerType() const
Definition TypeBase.h:8633
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:2078
bool isSamplerT() const
Definition TypeBase.h:8869
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:654
bool isNullPtrType() const
Definition TypeBase.h:9028
bool isRecordType() const
Definition TypeBase.h:8752
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5447
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5094
bool isUnionType() const
Definition Type.cpp:719
bool isReserveIDT() const
Definition TypeBase.h:8885
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3667
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5762
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3612
QualType getUnderlyingType() const
Definition Decl.h:3617
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition Decl.h:3623
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6160
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
decl_iterator begin()
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Expr * getSubExpr() const
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2283
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2343
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1033
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1065
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1069
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1121
UnionParsedType ConstructorName
When Kind == IK_ConstructorName, the class-name of the type whose constructor is being referenced.
Definition DeclSpec.h:1073
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition DeclSpec.h:1094
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1242
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1077
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1091
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1080
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1061
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1115
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1085
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3402
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3466
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3445
Wrapper for source info for types used via transparent aliases.
Definition TypeLoc.h:785
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5594
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5588
Represents a variable declaration or definition.
Definition Decl.h:926
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2822
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2163
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1525
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1569
TLSKind getTLSKind() const
Definition Decl.cpp:2180
bool hasInit() const
Definition Decl.cpp:2410
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1452
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition Decl.cpp:2272
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2202
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition Decl.cpp:2473
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2269
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
bool isCXXCondDecl() const
Definition Decl.h:1611
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:937
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition Decl.h:940
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:934
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2175
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1593
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1226
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2378
void setInlineSpecified()
Definition Decl.h:1558
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1208
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2784
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1342
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1173
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1551
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1177
const Expr * getInit() const
Definition Decl.h:1368
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1217
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1184
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2441
void setConstexpr(bool IC)
Definition Decl.h:1572
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:949
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:952
void setInit(Expr *I)
Definition Decl.cpp:2489
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2357
@ TentativeDefinition
This declaration is a tentative definition.
Definition Decl.h:1298
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1295
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1301
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2827
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition Decl.cpp:2257
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1253
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1168
void setImplicitlyInline()
Definition Decl.h:1563
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition Decl.h:1476
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1588
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition Decl.cpp:2718
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1262
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2791
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1358
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3974
Expr * getSizeExpr() const
Definition TypeBase.h:3988
Captures information about a #pragma weak directive.
Definition Weak.h:25
ValueDecl * getVariable() const
Definition ScopeInfo.h:679
bool isVariableCapture() const
Definition ScopeInfo.h:654
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:690
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:749
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:736
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:725
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:712
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:759
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1100
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:741
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition ScopeInfo.h:141
void addByrefBlockVar(VarDecl *VD)
Definition ScopeInfo.h:502
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition ScopeInfo.h:150
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition ScopeInfo.h:167
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition ScopeInfo.h:145
Expr * SYCLKernelLaunchIdExpr
An unresolved identifier lookup expression for an implicit call to a SYCL kernel launch function in a...
Definition ScopeInfo.h:250
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition ScopeInfo.h:158
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:888
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition ScopeInfo.h:919
ParmVarDecl * ExplicitObjectParameter
Definition ScopeInfo.h:885
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition ScopeInfo.h:952
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:875
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:883
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:878
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:900
Provides information about an attempted template argument deduction, whose success or failure was des...
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
Public enums and private classes that are part of the SourceManager implementation.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
constexpr bool isInitializedByPipeline(LangAS AS)
Definition HLSLRuntime.h:34
bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
bool randomizeStructureLayout(const ASTContext &Context, RecordDecl *RD, llvm::SmallVectorImpl< Decl * > &FinalOrdering)
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_struct
Definition Specifiers.h:81
@ TST_class
Definition Specifiers.h:82
@ TST_union
Definition Specifiers.h:80
@ TST_enum
Definition Specifiers.h:79
@ TST_interface
Definition Specifiers.h:83
ImplicitTypenameContext
Definition DeclSpec.h:1904
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:212
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ GVA_AvailableExternally
Definition Linkage.h:74
CUDAFunctionTarget
Definition Cuda.h:61
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
int hasAttribute(AttributeCommonInfo::Syntax Syntax, llvm::StringRef ScopeName, llvm::StringRef AttrName, const TargetInfo &Target, const LangOptions &LangOpts, bool CheckPlugins)
Return the version number associated with the attribute if we recognize and implement the attribute s...
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:35
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
InClassInitStyle
In-class initialization styles for non-static data members.
Definition Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
std::pair< FileID, unsigned > FileIDAndOffset
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:604
@ TemplateTemplateArgument
Definition Sema.h:613
NonTrivialCUnionContext
Definition Sema.h:532
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:628
@ None
Don't merge availability attributes at all.
Definition Sema.h:630
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:636
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:642
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:633
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:639
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1029
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1027
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1025
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1021
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1019
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1017
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1011
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1023
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1013
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1015
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_protected
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:127
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition Lookup.h:137
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition Linkage.h:63
@ CLanguageLinkage
Definition Linkage.h:64
@ CXXLanguageLinkage
Definition Linkage.h:65
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Auto
Definition Specifiers.h:256
@ SC_PrivateExtern
Definition Specifiers.h:253
@ SC_Extern
Definition Specifiers.h:251
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
@ SC_None
Definition Specifiers.h:250
@ TSCS_thread_local
C++11 thread_local.
Definition Specifiers.h:241
@ TSCS_unspecified
Definition Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition Specifiers.h:238
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
Definition Linkage.h:54
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
llvm::Expected< Decl * > ExpectedDecl
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:342
@ SD_Static
Static storage duration.
Definition Specifiers.h:343
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:908
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:616
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:319
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:451
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5939
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5944
@ Struct
The "struct" keyword.
Definition TypeBase.h:5941
@ Class
The "class" keyword.
Definition TypeBase.h:5950
@ Union
The "union" keyword.
Definition TypeBase.h:5947
@ Enum
The "enum" keyword.
Definition TypeBase.h:5953
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:108
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
ExprResult ExprError()
Definition Ownership.h:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition Decl.h:4320
@ TU_Complete
The translation unit is a complete translation unit.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
@ LCD_ByRef
Definition Lambda.h:25
@ LCD_None
Definition Lambda.h:23
@ LCD_ByCopy
Definition Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
MultiVersionKind
Definition Decl.h:1979
bool isExternalFormalLinkage(Linkage L)
Definition Linkage.h:117
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_X86StdCall
Definition Specifiers.h:280
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:179
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:840
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5935
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5925
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5928
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5932
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1746
@ EST_None
no exception specification
@ EST_BasicNoexcept
noexcept
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition Visibility.h:37
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
const Expr * ConstraintExpr
Definition Decl.h:88
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1441
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition DeclSpec.h:1592
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1416
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1375
const IdentifierInfo * Ident
Definition DeclSpec.h:1347
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1256
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1676
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition DeclSpec.cpp:132
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1657
FunctionTypeInfo Fun
Definition DeclSpec.h:1655
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition DeclSpec.h:1704
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
Extra information about a function prototype.
Definition TypeBase.h:5400
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5427
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:5978
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3309
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
std::vector< std::string > Features
Definition TargetInfo.h:61
Describes how types, statements, expressions, and declarations should be printed.
ValueType CurrentValue
Definition Sema.h:2035
SourceLocation CurrentPragmaLocation
Definition Sema.h:2036
bool CheckSameAsPrevious
Definition Sema.h:355
NamedDecl * Previous
Definition Sema.h:356
NamedDecl * New
Definition Sema.h:357
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
OpaquePtr< T > get() const
Definition Ownership.h:105
SourceLocation SymbolLocations[3]
The source locations of the individual tokens that name the operator, e.g., the "new",...
Definition DeclSpec.h:1053
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1044