clang 24.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/Type.h"
38#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
39#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
40#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
41#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
43#include "clang/Sema/DeclSpec.h"
46#include "clang/Sema/Lookup.h"
48#include "clang/Sema/Scope.h"
51#include "clang/Sema/SemaARM.h"
52#include "clang/Sema/SemaCUDA.h"
53#include "clang/Sema/SemaHLSL.h"
55#include "clang/Sema/SemaObjC.h"
58#include "clang/Sema/SemaPPC.h"
60#include "clang/Sema/SemaSYCL.h"
62#include "clang/Sema/SemaWasm.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/STLForwardCompat.h"
66#include "llvm/ADT/ScopeExit.h"
67#include "llvm/ADT/SmallPtrSet.h"
68#include "llvm/ADT/SmallString.h"
69#include "llvm/ADT/StringExtras.h"
70#include "llvm/ADT/StringRef.h"
71#include "llvm/Support/SaveAndRestore.h"
72#include "llvm/TargetParser/Triple.h"
73#include <algorithm>
74#include <cstring>
75#include <optional>
76#include <unordered_map>
77
78using namespace clang;
79using namespace sema;
80
82 if (OwnedType) {
83 Decl *Group[2] = { OwnedType, Ptr };
85 }
86
88}
89
90namespace {
91
92class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
93 public:
94 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
95 bool AllowTemplates = false,
96 bool AllowNonTemplates = true)
97 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
98 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
99 WantExpressionKeywords = false;
100 WantCXXNamedCasts = false;
101 WantRemainingKeywords = false;
102 }
103
104 bool ValidateCandidate(const TypoCorrection &candidate) override {
105 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
106 if (!AllowInvalidDecl && ND->isInvalidDecl())
107 return false;
108
109 if (getAsTypeTemplateDecl(ND))
110 return AllowTemplates;
111
112 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
113 if (!IsType)
114 return false;
115
116 if (AllowNonTemplates)
117 return true;
118
119 // An injected-class-name of a class template (specialization) is valid
120 // as a template or as a non-template.
121 if (AllowTemplates) {
122 auto *RD = dyn_cast<CXXRecordDecl>(ND);
123 if (!RD || !RD->isInjectedClassName())
124 return false;
125 RD = cast<CXXRecordDecl>(RD->getDeclContext());
126 return RD->getDescribedClassTemplate() ||
128 }
129
130 return false;
131 }
132
133 return !WantClassName && candidate.isKeyword();
134 }
135
136 std::unique_ptr<CorrectionCandidateCallback> clone() override {
137 return std::make_unique<TypeNameValidatorCCC>(*this);
138 }
139
140 private:
141 bool AllowInvalidDecl;
142 bool WantClassName;
143 bool AllowTemplates;
144 bool AllowNonTemplates;
145};
146
147} // end anonymous namespace
148
150 TypeDecl *TD, SourceLocation NameLoc) {
151 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
152 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
153 if (DCK != DiagCtorKind::None && LookupRD && FoundRD &&
154 FoundRD->isInjectedClassName() &&
155 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) {
156 Diag(NameLoc,
158 ? diag::ext_out_of_line_qualified_id_type_names_constructor
159 : diag::err_out_of_line_qualified_id_type_names_constructor)
160 << TD->getIdentifier() << /*Type=*/1
161 << 0 /*if any keyword was present, it was 'typename'*/;
162 }
163
164 DiagnoseUseOfDecl(TD, NameLoc);
165 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = Base.getType()->getAsCXXRecordDecl();
191 if (BaseRD) {
192 } else if (auto *TST = dyn_cast<TemplateSpecializationType>(
193 Base.getType().getCanonicalType())) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
207 CTD->findPartialSpecialization(Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(&II)) {
215 if (!isa<TypeDecl>(ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'MyClass::II' instead of 'II', and this implicit typename was
257 // allowed. We'll fully resolve the lookup during template instantiation.
258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD).getTypePtr());
262 QualType T =
263 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274}
275
277 Scope *S, CXXScopeSpec *SS, bool isClassName,
278 bool HasTrailingDot, ParsedType ObjectTypePtr,
279 bool IsCtorOrDtorName,
280 bool WantNontrivialTypeSourceInfo,
281 bool IsClassTemplateDeductionContext,
282 ImplicitTypenameContext AllowImplicitTypename,
283 IdentifierInfo **CorrectedII) {
284 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
285 // FIXME: Consider allowing this outside C++1z mode as an extension.
286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287 getLangOpts().CPlusPlus17 && IsImplicitTypename &&
288 !HasTrailingDot;
289
290 // Determine where we will perform name lookup.
291 DeclContext *LookupCtx = nullptr;
292 if (ObjectTypePtr) {
293 QualType ObjectType = ObjectTypePtr.get();
294 if (ObjectType->isRecordType())
295 LookupCtx = computeDeclContext(ObjectType);
296 } else if (SS && SS->isNotEmpty()) {
297 LookupCtx = computeDeclContext(*SS, false);
298
299 if (!LookupCtx) {
300 if (isDependentScopeSpecifier(*SS)) {
301 // C++ [temp.res]p3:
302 // A qualified-id that refers to a type and in which the
303 // nested-name-specifier depends on a template-parameter (14.6.2)
304 // shall be prefixed by the keyword typename to indicate that the
305 // qualified-id denotes a type, forming an
306 // elaborated-type-specifier (7.1.5.3).
307 //
308 // We therefore do not perform any name lookup if the result would
309 // refer to a member of an unknown specialization.
310 // In C++2a, in several contexts a 'typename' is not required. Also
311 // allow this as an extension.
312 if (IsImplicitTypename) {
313 if (AllowImplicitTypename == ImplicitTypenameContext::No)
314 return nullptr;
315 SourceLocation QualifiedLoc = SS->getRange().getBegin();
316 // FIXME: Defer the diagnostic after we build the type and use it.
317 auto DB = DiagCompat(QualifiedLoc, diag_compat::implicit_typename)
318 << Context.getDependentNameType(ElaboratedTypeKeyword::None,
319 SS->getScopeRep(), &II);
321 DB << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
322 }
323
324 // We know from the grammar that this name refers to a type,
325 // so build a dependent node to describe the type.
326 if (WantNontrivialTypeSourceInfo)
327 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
328 (ImplicitTypenameContext)IsImplicitTypename)
329 .get();
330
333 IsImplicitTypename ? ElaboratedTypeKeyword::Typename
335 SourceLocation(), QualifierLoc, II, NameLoc);
336 return ParsedType::make(T);
337 }
338
339 return nullptr;
340 }
341
342 if (!LookupCtx->isDependentContext() &&
343 RequireCompleteDeclContext(*SS, LookupCtx))
344 return nullptr;
345 }
346
347 // In the case where we know that the identifier is a class name, we know that
348 // it is a type declaration (struct, class, union or enum) so we can use tag
349 // name lookup.
350 //
351 // C++ [class.derived]p2 (wrt lookup in a base-specifier): The lookup for
352 // the component name of the type-name or simple-template-id is type-only.
353 LookupNameKind Kind = isClassName ? LookupTagName : LookupOrdinaryName;
354 LookupResult Result(*this, &II, NameLoc, Kind);
355 if (LookupCtx) {
356 // Perform "qualified" name lookup into the declaration context we
357 // computed, which is either the type of the base of a member access
358 // expression or the declaration context associated with a prior
359 // nested-name-specifier.
360 LookupQualifiedName(Result, LookupCtx);
361
362 if (ObjectTypePtr && Result.empty()) {
363 // C++ [basic.lookup.classref]p3:
364 // If the unqualified-id is ~type-name, the type-name is looked up
365 // in the context of the entire postfix-expression. If the type T of
366 // the object expression is of a class type C, the type-name is also
367 // looked up in the scope of class C. At least one of the lookups shall
368 // find a name that refers to (possibly cv-qualified) T.
369 LookupName(Result, S);
370 }
371 } else {
372 // Perform unqualified name lookup.
373 LookupName(Result, S);
374
375 // For unqualified lookup in a class template in MSVC mode, look into
376 // dependent base classes where the primary class template is known.
377 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
378 if (ParsedType TypeInBase =
379 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
380 return TypeInBase;
381 }
382 }
383
384 NamedDecl *IIDecl = nullptr;
385 UsingShadowDecl *FoundUsingShadow = nullptr;
386 switch (Result.getResultKind()) {
388 if (CorrectedII) {
389 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
390 AllowDeducedTemplate);
391 TypoCorrection Correction =
392 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, CCC,
394 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
396 bool MemberOfUnknownSpecialization;
398 TemplateName.setIdentifier(NewII, NameLoc);
400 CXXScopeSpec NewSS, *NewSSPtr = SS;
401 if (SS && NNS) {
402 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
403 NewSSPtr = &NewSS;
404 }
405 if (Correction && (NNS || NewII != &II) &&
406 // Ignore a correction to a template type as the to-be-corrected
407 // identifier is not a template (typo correction for template names
408 // is handled elsewhere).
409 !(getLangOpts().CPlusPlus && NewSSPtr &&
410 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
411 Template, MemberOfUnknownSpecialization))) {
412 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
413 isClassName, HasTrailingDot, ObjectTypePtr,
414 IsCtorOrDtorName,
415 WantNontrivialTypeSourceInfo,
416 IsClassTemplateDeductionContext);
417 if (Ty) {
418 diagnoseTypo(Correction,
419 PDiag(diag::err_unknown_type_or_class_name_suggest)
420 << Result.getLookupName() << isClassName);
421 if (SS && NNS)
422 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
423 *CorrectedII = NewII;
424 return Ty;
425 }
426 }
427 }
428 Result.suppressDiagnostics();
429 return nullptr;
431 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
432 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
433 SS->getScopeRep(), &II);
434 TypeLocBuilder TLB;
438 TL.setNameLoc(NameLoc);
440 }
441 [[fallthrough]];
444 Result.suppressDiagnostics();
445 return nullptr;
446
448 // Recover from type-hiding ambiguities by hiding the type. We'll
449 // do the lookup again when looking for an object, and we can
450 // diagnose the error then. If we don't do this, then the error
451 // about hiding the type will be immediately followed by an error
452 // that only makes sense if the identifier was treated like a type.
453 if (Result.getAmbiguityKind() == LookupAmbiguityKind::AmbiguousTagHiding) {
454 Result.suppressDiagnostics();
455 return nullptr;
456 }
457
458 // Look to see if we have a type anywhere in the list of results.
459 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
460 Res != ResEnd; ++Res) {
461 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
463 RealRes) ||
464 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
465 if (!IIDecl ||
466 // Make the selection of the recovery decl deterministic.
467 RealRes->getLocation() < IIDecl->getLocation()) {
468 IIDecl = RealRes;
469 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
470 }
471 }
472 }
473
474 if (!IIDecl) {
475 // None of the entities we found is a type, so there is no way
476 // to even assume that the result is a type. In this case, don't
477 // complain about the ambiguity. The parser will either try to
478 // perform this lookup again (e.g., as an object name), which
479 // will produce the ambiguity, or will complain that it expected
480 // a type name.
481 Result.suppressDiagnostics();
482 return nullptr;
483 }
484
485 // We found a type within the ambiguous lookup; diagnose the
486 // ambiguity and then return that type. This might be the right
487 // answer, or it might not be, but it suppresses any attempt to
488 // perform the name lookup again.
489 break;
490
492 IIDecl = Result.getFoundDecl();
493 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
494 break;
495 }
496
497 assert(IIDecl && "Didn't find decl");
498
499 TypeLocBuilder TLB;
500 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
501 checkTypeDeclType(LookupCtx,
502 IsImplicitTypename ? DiagCtorKind::Implicit
504 TD, NameLoc);
505 QualType T;
506 if (FoundUsingShadow) {
508 SS ? SS->getScopeRep() : std::nullopt,
509 FoundUsingShadow);
510 if (!WantNontrivialTypeSourceInfo)
511 return ParsedType::make(T);
512 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
515 NameLoc);
516 } else if (auto *Tag = dyn_cast<TagDecl>(TD)) {
518 SS ? SS->getScopeRep() : std::nullopt, Tag,
519 /*OwnsTag=*/false);
520 if (!WantNontrivialTypeSourceInfo)
521 return ParsedType::make(T);
522 auto TL = TLB.push<TagTypeLoc>(T);
524 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
526 TL.setNameLoc(NameLoc);
527 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TD);
528 TN && !isa<ObjCTypeParamDecl>(TN)) {
529 T = Context.getTypedefType(ElaboratedTypeKeyword::None,
530 SS ? SS->getScopeRep() : std::nullopt, TN);
531 if (!WantNontrivialTypeSourceInfo)
532 return ParsedType::make(T);
533 TLB.push<TypedefTypeLoc>(T).set(
534 /*ElaboratedKeywordLoc=*/SourceLocation(),
536 NameLoc);
537 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD)) {
538 T = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,
539 SS ? SS->getScopeRep() : std::nullopt,
540 UD);
541 if (!WantNontrivialTypeSourceInfo)
542 return ParsedType::make(T);
543 TLB.push<UnresolvedUsingTypeLoc>(T).set(
544 /*ElaboratedKeywordLoc=*/SourceLocation(),
546 NameLoc);
547 } else {
548 T = Context.getTypeDeclType(TD);
549 if (!WantNontrivialTypeSourceInfo)
550 return ParsedType::make(T);
552 TLB.push<ObjCTypeParamTypeLoc>(T).setNameLoc(NameLoc);
553 else
554 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
555 }
557 }
558
559 if (getLangOpts().HLSL) {
560 if (auto *TD = dyn_cast_or_null<TemplateDecl>(
561 getAsTemplateNameDecl(IIDecl, /*AllowFunctionTemplates=*/false,
562 /*AllowDependent=*/false))) {
563 QualType ShorthandTy = HLSL().ActOnTemplateShorthand(TD, NameLoc);
564 if (!ShorthandTy.isNull())
565 return ParsedType::make(ShorthandTy);
566 }
567 }
568
569 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
570 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
571 if (!HasTrailingDot) {
572 // FIXME: Support UsingType for this case.
573 QualType T = Context.getObjCInterfaceType(IDecl);
574 if (!WantNontrivialTypeSourceInfo)
575 return ParsedType::make(T);
576 auto TL = TLB.push<ObjCInterfaceTypeLoc>(T);
577 TL.setNameLoc(NameLoc);
578 // FIXME: Pass in this source location.
579 TL.setNameEndLoc(NameLoc);
581 }
582 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
583 (void)DiagnoseUseOfDecl(UD, NameLoc);
584 // Recover with 'int'
585 return ParsedType::make(Context.IntTy);
586 } else if (AllowDeducedTemplate) {
587 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
588 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
589 // FIXME: Support UsingType here.
590 TemplateName Template = Context.getQualifiedTemplateName(
591 SS ? SS->getScopeRep() : std::nullopt, /*TemplateKeyword=*/false,
592 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
593 QualType T = Context.getDeducedTemplateSpecializationType(
595 Template);
598 TL.setNameLoc(NameLoc);
599 TL.setQualifierLoc(SS ? SS->getWithLocInContext(Context)
602 }
603 }
604
605 // As it's not plausibly a type, suppress diagnostics.
606 Result.suppressDiagnostics();
607 return nullptr;
608}
609
610// Builds a fake NNS for the given decl context.
613 for (;; DC = DC->getLookupParent()) {
614 DC = DC->getPrimaryContext();
615 auto *ND = dyn_cast<NamespaceDecl>(DC);
616 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
617 return NestedNameSpecifier(Context, ND, std::nullopt);
618 if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
619 return NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
622 }
623 llvm_unreachable("something isn't in TU scope?");
624}
625
626/// Find the parent class with dependent bases of the innermost enclosing method
627/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
628/// up allowing unqualified dependent type names at class-level, which MSVC
629/// correctly rejects.
630static const CXXRecordDecl *
632 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
633 DC = DC->getPrimaryContext();
634 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
635 if (MD->getParent()->hasAnyDependentBases())
636 return MD->getParent();
637 }
638 return nullptr;
639}
640
642 SourceLocation NameLoc,
643 bool IsTemplateTypeArg) {
644 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
645
646 NestedNameSpecifier NNS = std::nullopt;
647 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
648 // If we weren't able to parse a default template argument, delay lookup
649 // until instantiation time by making a non-dependent DependentTypeName. We
650 // pretend we saw a NestedNameSpecifier referring to the current scope, and
651 // lookup is retried.
652 // FIXME: This hurts our diagnostic quality, since we get errors like "no
653 // type named 'Foo' in 'current_namespace'" when the user didn't write any
654 // name specifiers.
656 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
657 } else if (const CXXRecordDecl *RD =
659 // Build a DependentNameType that will perform lookup into RD at
660 // instantiation time.
661 NNS = NestedNameSpecifier(Context.getCanonicalTagType(RD)->getTypePtr());
662
663 // Diagnose that this identifier was undeclared, and retry the lookup during
664 // template instantiation.
665 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
666 << RD;
667 } else {
668 // This is not a situation that we should recover from.
669 return ParsedType();
670 }
671
672 QualType T =
673 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II);
674
675 // Build type location information. We synthesized the qualifier, so we have
676 // to build a fake NestedNameSpecifierLoc.
677 NestedNameSpecifierLocBuilder NNSLocBuilder;
678 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
679 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
680
681 TypeLocBuilder Builder;
682 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
683 DepTL.setNameLoc(NameLoc);
685 DepTL.setQualifierLoc(QualifierLoc);
686 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
687}
688
690 // Do a tag name lookup in this scope.
691 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
692 LookupName(R, S, false);
693 R.suppressDiagnostics();
694 if (R.getResultKind() == LookupResultKind::Found)
695 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
696 switch (TD->getTagKind()) {
702 return DeclSpec::TST_union;
704 return DeclSpec::TST_class;
706 return DeclSpec::TST_enum;
707 }
708 }
709
711}
712
714 if (!CurContext->isRecord())
715 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
716
717 switch (SS->getScopeRep().getKind()) {
719 return true;
721 QualType T(SS->getScopeRep().getAsType(), 0);
722 for (const auto &Base : cast<CXXRecordDecl>(CurContext)->bases())
723 if (Context.hasSameUnqualifiedType(T, Base.getType()))
724 return true;
725 [[fallthrough]];
726 }
727 default:
728 return S->isFunctionPrototypeScope();
729 }
730}
731
733 SourceLocation IILoc,
734 Scope *S,
735 CXXScopeSpec *SS,
736 ParsedType &SuggestedType,
737 bool IsTemplateName) {
738 // Don't report typename errors for editor placeholders.
739 if (II->isEditorPlaceholder())
740 return;
741 // We don't have anything to suggest (yet).
742 SuggestedType = nullptr;
743
744 // There may have been a typo in the name of the type. Look up typo
745 // results, in case we have something that we can suggest.
746 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
747 /*AllowTemplates=*/IsTemplateName,
748 /*AllowNonTemplates=*/!IsTemplateName);
749 if (TypoCorrection Corrected =
752 // FIXME: Support error recovery for the template-name case.
753 bool CanRecover = !IsTemplateName;
754 if (Corrected.isKeyword()) {
755 // We corrected to a keyword.
756 diagnoseTypo(Corrected,
757 PDiag(IsTemplateName ? diag::err_no_template_suggest
758 : diag::err_unknown_typename_suggest)
759 << II);
760 II = Corrected.getCorrectionAsIdentifierInfo();
761 } else {
762 // We found a similarly-named type or interface; suggest that.
763 if (!SS || !SS->isSet()) {
764 diagnoseTypo(Corrected,
765 PDiag(IsTemplateName ? diag::err_no_template_suggest
766 : diag::err_unknown_typename_suggest)
767 << II, CanRecover);
768 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
769 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
770 bool DroppedSpecifier =
771 Corrected.WillReplaceSpecifier() && II->getName() == CorrectedStr;
772 diagnoseTypo(Corrected,
773 PDiag(IsTemplateName
774 ? diag::err_no_member_template_suggest
775 : diag::err_unknown_nested_typename_suggest)
776 << II << DC << DroppedSpecifier << SS->getRange(),
777 CanRecover);
778 } else {
779 llvm_unreachable("could not have corrected a typo here");
780 }
781
782 if (!CanRecover)
783 return;
784
785 CXXScopeSpec tmpSS;
786 if (Corrected.getCorrectionSpecifier())
787 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
788 SourceRange(IILoc));
789 // FIXME: Support class template argument deduction here.
790 SuggestedType =
791 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
792 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
793 /*IsCtorOrDtorName=*/false,
794 /*WantNontrivialTypeSourceInfo=*/true);
795 }
796 return;
797 }
798
799 if (getLangOpts().CPlusPlus && !IsTemplateName) {
800 // See if II is a class template that the user forgot to pass arguments to.
801 UnqualifiedId Name;
802 Name.setIdentifier(II, IILoc);
803 CXXScopeSpec EmptySS;
804 TemplateTy TemplateResult;
805 bool MemberOfUnknownSpecialization;
806 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
807 Name, nullptr, true, TemplateResult,
808 MemberOfUnknownSpecialization) == TNK_Type_template) {
809 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
810 return;
811 }
812 }
813
814 // FIXME: Should we move the logic that tries to recover from a missing tag
815 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
816
817 if (!SS || (!SS->isSet() && !SS->isInvalid()))
818 Diag(IILoc, IsTemplateName ? diag::err_no_template
819 : diag::err_unknown_typename)
820 << II;
821 else if (DeclContext *DC = computeDeclContext(*SS, false))
822 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
823 : diag::err_typename_nested_not_found)
824 << II << DC << SS->getRange();
825 else if (SS->isValid() && SS->getScopeRep().containsErrors()) {
826 SuggestedType =
827 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
828 } else if (isDependentScopeSpecifier(*SS)) {
829 unsigned DiagID = diag::err_typename_missing;
830 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
831 DiagID = diag::ext_typename_missing;
832
833 SuggestedType =
834 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
835
836 Diag(SS->getRange().getBegin(), DiagID)
837 << GetTypeFromParser(SuggestedType)
838 << SourceRange(SS->getRange().getBegin(), IILoc)
839 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
840 } else {
841 assert(SS && SS->isInvalid() &&
842 "Invalid scope specifier has already been diagnosed");
843 }
844}
845
846/// Determine whether the given result set contains either a type name
847/// or
848static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
849 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
850 NextToken.is(tok::less);
851
852 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
854 return true;
855
856 if (CheckTemplate && isa<TemplateDecl>(*I))
857 return true;
858 }
859
860 return false;
861}
862
864 Scope *S, CXXScopeSpec &SS,
865 IdentifierInfo *&Name,
866 SourceLocation NameLoc) {
867 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
868 SemaRef.LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
869 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
870 StringRef FixItTagName;
871 switch (Tag->getTagKind()) {
873 FixItTagName = "class ";
874 break;
875
877 FixItTagName = "enum ";
878 break;
879
881 FixItTagName = "struct ";
882 break;
883
885 FixItTagName = "__interface ";
886 break;
887
889 FixItTagName = "union ";
890 break;
891 }
892
893 StringRef TagName = FixItTagName.drop_back();
894 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
895 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
896 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
897
898 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
899 I != IEnd; ++I)
900 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
901 << Name << TagName;
902
903 // Replace lookup results with just the tag decl.
905 SemaRef.LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType());
906 return true;
907 }
908
909 return false;
910}
911
913 IdentifierInfo *&Name,
914 SourceLocation NameLoc,
915 const Token &NextToken,
917 DeclarationNameInfo NameInfo(Name, NameLoc);
918 ObjCMethodDecl *CurMethod = getCurMethodDecl();
919
920 assert(NextToken.isNot(tok::coloncolon) &&
921 "parse nested name specifiers before calling ClassifyName");
922 if (getLangOpts().CPlusPlus && SS.isSet() &&
923 isCurrentClassName(*Name, S, &SS)) {
924 // Per [class.qual]p2, this names the constructors of SS, not the
925 // injected-class-name. We don't have a classification for that.
926 // There's not much point caching this result, since the parser
927 // will reject it later.
929 }
930
931 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
932 LookupParsedName(Result, S, &SS, /*ObjectType=*/QualType(),
933 /*AllowBuiltinCreation=*/!CurMethod);
934
935 if (SS.isInvalid())
937
938 // For unqualified lookup in a class template in MSVC mode, look into
939 // dependent base classes where the primary class template is known.
940 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
941 if (ParsedType TypeInBase =
942 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
943 return TypeInBase;
944 }
945
946 // Perform lookup for Objective-C instance variables (including automatically
947 // synthesized instance variables), if we're in an Objective-C method.
948 // FIXME: This lookup really, really needs to be folded in to the normal
949 // unqualified lookup mechanism.
950 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
951 DeclResult Ivar = ObjC().LookupIvarInObjCMethod(Result, S, Name);
952 if (Ivar.isInvalid())
954 if (Ivar.isUsable())
956
957 // We defer builtin creation until after ivar lookup inside ObjC methods.
958 if (Result.empty())
960 }
961
962 bool SecondTry = false;
963 bool IsFilteredTemplateName = false;
964
965Corrected:
966 switch (Result.getResultKind()) {
968 // If an unqualified-id is followed by a '(', then we have a function
969 // call.
970 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
971 // In C++, this is an ADL-only call.
972 // FIXME: Reference?
975
976 // C90 6.3.2.2:
977 // If the expression that precedes the parenthesized argument list in a
978 // function call consists solely of an identifier, and if no
979 // declaration is visible for this identifier, the identifier is
980 // implicitly declared exactly as if, in the innermost block containing
981 // the function call, the declaration
982 //
983 // extern int identifier ();
984 //
985 // appeared.
986 //
987 // We also allow this in C99 as an extension. However, this is not
988 // allowed in all language modes as functions without prototypes may not
989 // be supported.
990 if (getLangOpts().implicitFunctionsAllowed()) {
991 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
993 }
994 }
995
996 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
997 // In C++20 onwards, this could be an ADL-only call to a function
998 // template, and we're required to assume that this is a template name.
999 //
1000 // FIXME: Find a way to still do typo correction in this case.
1002 Context.getAssumedTemplateName(NameInfo.getName());
1004 }
1005
1006 // In C, we first see whether there is a tag type by the same name, in
1007 // which case it's likely that the user just forgot to write "enum",
1008 // "struct", or "union".
1009 if (!getLangOpts().CPlusPlus && !SecondTry &&
1010 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1011 break;
1012 }
1013
1014 // Perform typo correction to determine if there is another name that is
1015 // close to this name.
1016 if (!SecondTry && CCC) {
1017 SecondTry = true;
1018 if (TypoCorrection Corrected =
1019 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1020 &SS, *CCC, CorrectTypoKind::ErrorRecovery)) {
1021 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
1022 unsigned QualifiedDiag = diag::err_no_member_suggest;
1023
1024 NamedDecl *FirstDecl = Corrected.getFoundDecl();
1025 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
1026 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1027 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
1028 UnqualifiedDiag = diag::err_no_template_suggest;
1029 QualifiedDiag = diag::err_no_member_template_suggest;
1030 } else if (UnderlyingFirstDecl &&
1031 (isa<TypeDecl>(UnderlyingFirstDecl) ||
1032 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
1033 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
1034 UnqualifiedDiag = diag::err_unknown_typename_suggest;
1035 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
1036 }
1037
1038 if (SS.isEmpty()) {
1039 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
1040 } else {// FIXME: is this even reachable? Test it.
1041 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1042 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
1043 Name->getName() == CorrectedStr;
1044 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
1045 << Name << computeDeclContext(SS, false)
1046 << DroppedSpecifier << SS.getRange());
1047 }
1048
1049 // Update the name, so that the caller has the new name.
1050 Name = Corrected.getCorrectionAsIdentifierInfo();
1051
1052 // Typo correction corrected to a keyword.
1053 if (Corrected.isKeyword())
1054 return Name;
1055
1056 // Also update the LookupResult...
1057 // FIXME: This should probably go away at some point
1058 Result.clear();
1059 Result.setLookupName(Corrected.getCorrection());
1060 if (FirstDecl)
1061 Result.addDecl(FirstDecl);
1062
1063 // If we found an Objective-C instance variable, let
1064 // LookupInObjCMethod build the appropriate expression to
1065 // reference the ivar.
1066 // FIXME: This is a gross hack.
1067 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1068 DeclResult R =
1069 ObjC().LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1070 if (R.isInvalid())
1072 if (R.isUsable())
1073 return NameClassification::NonType(Ivar);
1074 }
1075
1076 goto Corrected;
1077 }
1078 }
1079
1080 // We failed to correct; just fall through and let the parser deal with it.
1081 Result.suppressDiagnostics();
1083
1085 // We performed name lookup into the current instantiation, and there were
1086 // dependent bases, so we treat this result the same way as any other
1087 // dependent nested-name-specifier.
1088
1089 // C++ [temp.res]p2:
1090 // A name used in a template declaration or definition and that is
1091 // dependent on a template-parameter is assumed not to name a type
1092 // unless the applicable name lookup finds a type name or the name is
1093 // qualified by the keyword typename.
1094 //
1095 // FIXME: If the next token is '<', we might want to ask the parser to
1096 // perform some heroics to see if we actually have a
1097 // template-argument-list, which would indicate a missing 'template'
1098 // keyword here.
1100 }
1101
1105 break;
1106
1108 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1109 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1110 /*AllowDependent=*/false)) {
1111 // C++ [temp.local]p3:
1112 // A lookup that finds an injected-class-name (10.2) can result in an
1113 // ambiguity in certain cases (for example, if it is found in more than
1114 // one base class). If all of the injected-class-names that are found
1115 // refer to specializations of the same class template, and if the name
1116 // is followed by a template-argument-list, the reference refers to the
1117 // class template itself and not a specialization thereof, and is not
1118 // ambiguous.
1119 //
1120 // This filtering can make an ambiguous result into an unambiguous one,
1121 // so try again after filtering out template names.
1123 if (!Result.isAmbiguous()) {
1124 IsFilteredTemplateName = true;
1125 break;
1126 }
1127 }
1128
1129 // Diagnose the ambiguity and return an error.
1131 }
1132
1133 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1134 (IsFilteredTemplateName ||
1136 Result, /*AllowFunctionTemplates=*/true,
1137 /*AllowDependent=*/false,
1138 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1140 // C++ [temp.names]p3:
1141 // After name lookup (3.4) finds that a name is a template-name or that
1142 // an operator-function-id or a literal- operator-id refers to a set of
1143 // overloaded functions any member of which is a function template if
1144 // this is followed by a <, the < is always taken as the delimiter of a
1145 // template-argument-list and never as the less-than operator.
1146 // C++2a [temp.names]p2:
1147 // A name is also considered to refer to a template if it is an
1148 // unqualified-id followed by a < and name lookup finds either one
1149 // or more functions or finds nothing.
1150 if (!IsFilteredTemplateName)
1152
1153 bool IsFunctionTemplate;
1154 bool IsVarTemplate;
1156 if (Result.end() - Result.begin() > 1) {
1157 IsFunctionTemplate = true;
1158 Template = Context.getOverloadedTemplateName(Result.begin(),
1159 Result.end());
1160 } else if (!Result.empty()) {
1162 *Result.begin(), /*AllowFunctionTemplates=*/true,
1163 /*AllowDependent=*/false));
1164 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1165 IsVarTemplate = isa<VarTemplateDecl>(TD);
1166
1167 UsingShadowDecl *FoundUsingShadow =
1168 dyn_cast<UsingShadowDecl>(*Result.begin());
1169 assert(!FoundUsingShadow ||
1170 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
1171 Template = Context.getQualifiedTemplateName(
1172 SS.getScopeRep(),
1173 /*TemplateKeyword=*/false,
1174 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD));
1175 } else {
1176 // All results were non-template functions. This is a function template
1177 // name.
1178 IsFunctionTemplate = true;
1179 Template = Context.getAssumedTemplateName(NameInfo.getName());
1180 }
1181
1182 if (IsFunctionTemplate) {
1183 // Function templates always go through overload resolution, at which
1184 // point we'll perform the various checks (e.g., accessibility) we need
1185 // to based on which function we selected.
1186 Result.suppressDiagnostics();
1187
1189 }
1190
1191 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1193 }
1194
1195 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1196 QualType T;
1197 TypeLocBuilder TLB;
1198 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) {
1199 T = Context.getUsingType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1200 USD);
1201 TLB.push<UsingTypeLoc>(T).set(/*ElaboratedKeywordLoc=*/SourceLocation(),
1202 SS.getWithLocInContext(Context), NameLoc);
1203 } else {
1204 T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, SS.getScopeRep(),
1205 Type);
1206 if (isa<TagType>(T)) {
1207 auto TTL = TLB.push<TagTypeLoc>(T);
1209 TTL.setQualifierLoc(SS.getWithLocInContext(Context));
1210 TTL.setNameLoc(NameLoc);
1211 } else if (isa<TypedefType>(T)) {
1212 TLB.push<TypedefTypeLoc>(T).set(
1213 /*ElaboratedKeywordLoc=*/SourceLocation(),
1214 SS.getWithLocInContext(Context), NameLoc);
1215 } else if (isa<UnresolvedUsingType>(T)) {
1216 TLB.push<UnresolvedUsingTypeLoc>(T).set(
1217 /*ElaboratedKeywordLoc=*/SourceLocation(),
1218 SS.getWithLocInContext(Context), NameLoc);
1219 } else {
1220 TLB.pushTypeSpec(T).setNameLoc(NameLoc);
1221 }
1222 }
1224 };
1225
1226 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1227 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1228 DiagnoseUseOfDecl(Type, NameLoc);
1229 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1230 return BuildTypeFor(Type, *Result.begin());
1231 }
1232
1233 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1234 if (!Class) {
1235 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1236 if (ObjCCompatibleAliasDecl *Alias =
1237 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1238 Class = Alias->getClassInterface();
1239 }
1240
1241 if (Class) {
1242 DiagnoseUseOfDecl(Class, NameLoc);
1243
1244 if (NextToken.is(tok::period)) {
1245 // Interface. <something> is parsed as a property reference expression.
1246 // Just return "unknown" as a fall-through for now.
1247 Result.suppressDiagnostics();
1249 }
1250
1251 QualType T = Context.getObjCInterfaceType(Class);
1252 return ParsedType::make(T);
1253 }
1254
1256 // We want to preserve the UsingShadowDecl for concepts.
1257 if (auto *USD = dyn_cast<UsingShadowDecl>(Result.getRepresentativeDecl()))
1261 }
1262
1263 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1264 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1266 }
1267
1268 // We can have a type template here if we're classifying a template argument.
1273
1274 // Check for a tag type hidden by a non-type decl in a few cases where it
1275 // seems likely a type is wanted instead of the non-type that was found.
1276 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1277 if ((NextToken.is(tok::identifier) ||
1278 (NextIsOp &&
1279 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1280 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1281 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1282 DiagnoseUseOfDecl(Type, NameLoc);
1283 return BuildTypeFor(Type, *Result.begin());
1284 }
1285
1286 // If we already know which single declaration is referenced, just annotate
1287 // that declaration directly. Defer resolving even non-overloaded class
1288 // member accesses, as we need to defer certain access checks until we know
1289 // the context.
1290 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1291 if (Result.isSingleResult() && !ADL &&
1292 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
1293 return NameClassification::NonType(Result.getRepresentativeDecl());
1294
1295 // Otherwise, this is an overload set that we will need to resolve later.
1296 Result.suppressDiagnostics();
1298 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1299 Result.getLookupNameInfo(), ADL, Result.begin(), Result.end(),
1300 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false));
1301}
1302
1305 SourceLocation NameLoc) {
1306 assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1307 CXXScopeSpec SS;
1308 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1309 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1310}
1311
1314 IdentifierInfo *Name,
1315 SourceLocation NameLoc,
1316 bool IsAddressOfOperand) {
1317 DeclarationNameInfo NameInfo(Name, NameLoc);
1318 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1319 NameInfo, IsAddressOfOperand,
1320 /*TemplateArgs=*/nullptr);
1321}
1322
1325 SourceLocation NameLoc,
1326 const Token &NextToken) {
1327 if (getCurMethodDecl() && SS.isEmpty())
1328 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1329 return ObjC().BuildIvarRefExpr(S, NameLoc, Ivar);
1330
1331 // Reconstruct the lookup result.
1332 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1333 Result.addDecl(Found);
1334 Result.resolveKind();
1335
1336 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1337 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
1338}
1339
1341 // For an implicit class member access, transform the result into a member
1342 // access expression if necessary.
1343 auto *ULE = cast<UnresolvedLookupExpr>(E);
1344 if ((*ULE->decls_begin())->isCXXClassMember()) {
1345 CXXScopeSpec SS;
1346 SS.Adopt(ULE->getQualifierLoc());
1347
1348 // Reconstruct the lookup result.
1349 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1351 Result.setNamingClass(ULE->getNamingClass());
1352 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1353 Result.addDecl(*I, I.getAccess());
1354 Result.resolveKind();
1356 nullptr, S);
1357 }
1358
1359 // Otherwise, this is already in the form we needed, and no further checks
1360 // are necessary.
1361 return ULE;
1362}
1363
1383
1385 assert(DC->getLexicalParent() == CurContext &&
1386 "The next DeclContext should be lexically contained in the current one.");
1387 CurContext = DC;
1388 if (S)
1389 S->setEntity(DC);
1390}
1391
1393 assert(CurContext && "DeclContext imbalance!");
1394
1395 CurContext = CurContext->getLexicalParent();
1396 assert(CurContext && "Popped translation unit!");
1397}
1398
1400 Decl *D) {
1401 // Unlike PushDeclContext, the context to which we return is not necessarily
1402 // the containing DC of TD, because the new context will be some pre-existing
1403 // TagDecl definition instead of a fresh one.
1404 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1405 CurContext = cast<TagDecl>(D)->getDefinition();
1406 assert(CurContext && "skipping definition of undefined tag");
1407 // Start lookups from the parent of the current context; we don't want to look
1408 // into the pre-existing complete definition.
1409 S->setEntity(CurContext->getLookupParent());
1410 return Result;
1411}
1412
1416
1418 // C++0x [basic.lookup.unqual]p13:
1419 // A name used in the definition of a static data member of class
1420 // X (after the qualified-id of the static member) is looked up as
1421 // if the name was used in a member function of X.
1422 // C++0x [basic.lookup.unqual]p14:
1423 // If a variable member of a namespace is defined outside of the
1424 // scope of its namespace then any name used in the definition of
1425 // the variable member (after the declarator-id) is looked up as
1426 // if the definition of the variable member occurred in its
1427 // namespace.
1428 // Both of these imply that we should push a scope whose context
1429 // is the semantic context of the declaration. We can't use
1430 // PushDeclContext here because that context is not necessarily
1431 // lexically contained in the current context. Fortunately,
1432 // the containing scope should have the appropriate information.
1433
1434 assert(!S->getEntity() && "scope already has entity");
1435
1436#ifndef NDEBUG
1437 Scope *Ancestor = S->getParent();
1438 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1439 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1440#endif
1441
1442 CurContext = DC;
1443 S->setEntity(DC);
1444
1445 if (S->getParent()->isTemplateParamScope()) {
1446 // Also set the corresponding entities for all immediately-enclosing
1447 // template parameter scopes.
1449 }
1450}
1451
1453 assert(S->getEntity() == CurContext && "Context imbalance!");
1454
1455 // Switch back to the lexical context. The safety of this is
1456 // enforced by an assert in EnterDeclaratorContext.
1457 Scope *Ancestor = S->getParent();
1458 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1459 CurContext = Ancestor->getEntity();
1460
1461 // We don't need to do anything with the scope, which is going to
1462 // disappear.
1463}
1464
1466 assert(S->isTemplateParamScope() &&
1467 "expected to be initializing a template parameter scope");
1468
1469 // C++20 [temp.local]p7:
1470 // In the definition of a member of a class template that appears outside
1471 // of the class template definition, the name of a member of the class
1472 // template hides the name of a template-parameter of any enclosing class
1473 // templates (but not a template-parameter of the member if the member is a
1474 // class or function template).
1475 // C++20 [temp.local]p9:
1476 // In the definition of a class template or in the definition of a member
1477 // of such a template that appears outside of the template definition, for
1478 // each non-dependent base class (13.8.2.1), if the name of the base class
1479 // or the name of a member of the base class is the same as the name of a
1480 // template-parameter, the base class name or member name hides the
1481 // template-parameter name (6.4.10).
1482 //
1483 // This means that a template parameter scope should be searched immediately
1484 // after searching the DeclContext for which it is a template parameter
1485 // scope. For example, for
1486 // template<typename T> template<typename U> template<typename V>
1487 // void N::A<T>::B<U>::f(...)
1488 // we search V then B<U> (and base classes) then U then A<T> (and base
1489 // classes) then T then N then ::.
1490 unsigned ScopeDepth = getTemplateDepth(S);
1491 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1492 DeclContext *SearchDCAfterScope = DC;
1493 for (; DC; DC = DC->getLookupParent()) {
1494 if (const TemplateParameterList *TPL =
1495 cast<Decl>(DC)->getDescribedTemplateParams()) {
1496 unsigned DCDepth = TPL->getDepth() + 1;
1497 if (DCDepth > ScopeDepth)
1498 continue;
1499 if (ScopeDepth == DCDepth)
1500 SearchDCAfterScope = DC = DC->getLookupParent();
1501 break;
1502 }
1503 }
1504 S->setLookupEntity(SearchDCAfterScope);
1505 }
1506}
1507
1509 // We assume that the caller has already called
1510 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1511 FunctionDecl *FD = D->getAsFunction();
1512 if (!FD)
1513 return;
1514
1515 // Same implementation as PushDeclContext, but enters the context
1516 // from the lexical parent, rather than the top-level class.
1517 assert(CurContext == FD->getLexicalParent() &&
1518 "The next DeclContext should be lexically contained in the current one.");
1519 CurContext = FD;
1521
1522 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1523 ParmVarDecl *Param = FD->getParamDecl(P);
1524 // If the parameter has an identifier, then add it to the scope
1525 if (Param->getIdentifier()) {
1526 S->AddDecl(Param);
1527 IdResolver.AddDecl(Param);
1528 }
1529 }
1530}
1531
1533 // Same implementation as PopDeclContext, but returns to the lexical parent,
1534 // rather than the top-level class.
1535 assert(CurContext && "DeclContext imbalance!");
1536 CurContext = CurContext->getLexicalParent();
1537 assert(CurContext && "Popped translation unit!");
1538}
1539
1540/// Determine whether overloading is allowed for a new function
1541/// declaration considering prior declarations of the same name.
1542///
1543/// This routine determines whether overloading is possible, not
1544/// whether a new declaration actually overloads a previous one.
1545/// It will return true in C++ (where overloads are always permitted)
1546/// or, as a C extension, when either the new declaration or a
1547/// previous one is declared with the 'overloadable' attribute.
1549 ASTContext &Context,
1550 const FunctionDecl *New) {
1551 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1552 return true;
1553
1554 // Multiversion function declarations are not overloads in the
1555 // usual sense of that term, but lookup will report that an
1556 // overload set was found if more than one multiversion function
1557 // declaration is present for the same name. It is therefore
1558 // inadequate to assume that some prior declaration(s) had
1559 // the overloadable attribute; checking is required. Since one
1560 // declaration is permitted to omit the attribute, it is necessary
1561 // to check at least two; hence the 'any_of' check below. Note that
1562 // the overloadable attribute is implicitly added to declarations
1563 // that were required to have it but did not.
1564 if (Previous.getResultKind() == LookupResultKind::FoundOverloaded) {
1565 return llvm::any_of(Previous, [](const NamedDecl *ND) {
1566 return ND->hasAttr<OverloadableAttr>();
1567 });
1568 } else if (Previous.getResultKind() == LookupResultKind::Found)
1569 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1570
1571 return false;
1572}
1573
1574void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1575 // Move up the scope chain until we find the nearest enclosing
1576 // non-transparent context. The declaration will be introduced into this
1577 // scope.
1578 while (S->getEntity() && S->getEntity()->isTransparentContext())
1579 S = S->getParent();
1580
1581 // Add scoped declarations into their context, so that they can be
1582 // found later. Declarations without a context won't be inserted
1583 // into any context.
1584 if (AddToContext)
1585 CurContext->addDecl(D);
1586
1587 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1588 // are function-local declarations.
1589 if (getLangOpts().CPlusPlus && D->isOutOfLine()) {
1590 if (!S->getFnParent())
1591 return;
1592
1593 // Even inside a function, an out-of-line definition of a type that is
1594 // nested inside a local class must not be pushed into the enclosing
1595 // function scope. For example:
1596 //
1597 // class A { public: class B; };
1598 // class A::B {}; // out-of-line definition inside the function
1599 // B b; // must fail - only A::B is valid
1600 // Wrapper{B{}} // must also fail
1601 //
1602 // Per C++ scoping rules only the qualified form A::B is accessible.
1603 // Without this guard, PushOnScopeChains would add B to the function's
1604 // local scope, making it findable via unqualified lookup, which is
1605 // incorrect. The condition targets TagDecls (class/struct/union/enum)
1606 // whose DeclContext is a CXXRecordDecl, i.e., types that are members
1607 // of a local class being defined out-of-line.
1609 return;
1610 }
1611
1612 // Template instantiations should also not be pushed into scope.
1613 if (isa<FunctionDecl>(D) &&
1614 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1615 return;
1616
1617 if (isa<UsingEnumDecl>(D) && D->getDeclName().isEmpty()) {
1618 S->AddDecl(D);
1619 return;
1620 }
1621 // If this replaces anything in the current scope,
1623 IEnd = IdResolver.end();
1624 for (; I != IEnd; ++I) {
1625 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1626 S->RemoveDecl(*I);
1627 IdResolver.RemoveDecl(*I);
1628
1629 // Should only need to replace one decl.
1630 break;
1631 }
1632 }
1633
1634 S->AddDecl(D);
1635
1636 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1637 // Implicitly-generated labels may end up getting generated in an order that
1638 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1639 // the label at the appropriate place in the identifier chain.
1640 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1641 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1642 if (IDC == CurContext) {
1643 if (!S->isDeclScope(*I))
1644 continue;
1645 } else if (IDC->Encloses(CurContext))
1646 break;
1647 }
1648
1649 IdResolver.InsertDeclAfter(I, D);
1650 } else {
1651 IdResolver.AddDecl(D);
1652 }
1654}
1655
1657 bool AllowInlineNamespace) const {
1658 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1659}
1660
1662 bool AllowInlineNamespace) const {
1663 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1664 return true;
1665
1666 if (auto *Shadow = dyn_cast<UsingShadowDecl>(D))
1667 return isDeclInScope(Shadow->getTargetDecl(), Ctx, S, AllowInlineNamespace);
1668
1669 return false;
1670}
1671
1673 DeclContext *TargetDC = DC->getPrimaryContext();
1674 do {
1675 if (DeclContext *ScopeDC = S->getEntity())
1676 if (ScopeDC->getPrimaryContext() == TargetDC)
1677 return S;
1678 } while ((S = S->getParent()));
1679
1680 return nullptr;
1681}
1682
1684 DeclContext*,
1685 ASTContext&);
1686
1688 bool ConsiderLinkage,
1689 bool AllowInlineNamespace) {
1690 LookupResult::Filter F = R.makeFilter();
1691 while (F.hasNext()) {
1692 NamedDecl *D = F.next();
1693
1694 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1695 continue;
1696
1697 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1698 continue;
1699
1700 F.erase();
1701 }
1702
1703 F.done();
1704}
1705
1707 if (auto *VD = dyn_cast<VarDecl>(D))
1708 return VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1709 if (auto *FD = dyn_cast<FunctionDecl>(D))
1710 return FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1711 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1712 return RD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation;
1713
1714 return false;
1715}
1716
1718 // [module.interface]p7:
1719 // A declaration is attached to a module as follows:
1720 // - If the declaration is a non-dependent friend declaration that nominates a
1721 // function with a declarator-id that is a qualified-id or template-id or that
1722 // nominates a class other than with an elaborated-type-specifier with neither
1723 // a nested-name-specifier nor a simple-template-id, it is attached to the
1724 // module to which the friend is attached ([basic.link]).
1725 if (New->getFriendObjectKind() &&
1726 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1727 New->setLocalOwningModule(Old->getOwningModule());
1729 return false;
1730 }
1731
1732 // Although we have questions for the module ownership of implicit
1733 // instantiations, it should be sure that we shouldn't diagnose the
1734 // redeclaration of incorrect module ownership for different implicit
1735 // instantiations in different modules. We will diagnose the redeclaration of
1736 // incorrect module ownership for the template itself.
1738 return false;
1739
1740 Module *NewM = New->getOwningModule();
1741 Module *OldM = Old->getOwningModule();
1742
1743 if (NewM && NewM->isPrivateModule())
1744 NewM = NewM->Parent;
1745 if (OldM && OldM->isPrivateModule())
1746 OldM = OldM->Parent;
1747
1748 if (NewM == OldM)
1749 return false;
1750
1751 if (NewM && OldM) {
1752 // A module implementation unit has visibility of the decls in its
1753 // implicitly imported interface.
1754 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface)
1755 return false;
1756
1757 // Partitions are part of the module, but a partition could import another
1758 // module, so verify that the PMIs agree.
1759 if ((NewM->isModulePartition() || OldM->isModulePartition()) &&
1760 getASTContext().isInSameModule(NewM, OldM))
1761 return false;
1762 }
1763
1764 bool NewIsModuleInterface = NewM && NewM->isNamedModule();
1765 bool OldIsModuleInterface = OldM && OldM->isNamedModule();
1766 if (NewIsModuleInterface || OldIsModuleInterface) {
1767 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1768 // if a declaration of D [...] appears in the purview of a module, all
1769 // other such declarations shall appear in the purview of the same module
1770 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1771 << New
1772 << NewIsModuleInterface
1773 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1774 << OldIsModuleInterface
1775 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1776 Diag(Old->getLocation(), diag::note_previous_declaration);
1777 New->setInvalidDecl();
1778 return true;
1779 }
1780
1781 return false;
1782}
1783
1785 // [module.interface]p1:
1786 // An export-declaration shall inhabit a namespace scope.
1787 //
1788 // So it is meaningless to talk about redeclaration which is not at namespace
1789 // scope.
1790 if (!New->getLexicalDeclContext()
1791 ->getNonTransparentContext()
1792 ->isFileContext() ||
1793 !Old->getLexicalDeclContext()
1795 ->isFileContext())
1796 return false;
1797
1798 bool IsNewExported = New->isInExportDeclContext();
1799 bool IsOldExported = Old->isInExportDeclContext();
1800
1801 // It should be irrevelant if both of them are not exported.
1802 if (!IsNewExported && !IsOldExported)
1803 return false;
1804
1805 if (IsOldExported)
1806 return false;
1807
1808 // If the Old declaration are not attached to named modules
1809 // and the New declaration are attached to global module.
1810 // It should be fine to allow the export since it doesn't change
1811 // the linkage of declarations. See
1812 // https://github.com/llvm/llvm-project/issues/98583 for details.
1813 if (!Old->isInNamedModule() && New->getOwningModule() &&
1814 New->getOwningModule()->isImplicitGlobalModule())
1815 return false;
1816
1817 assert(IsNewExported);
1818
1819 auto Lk = Old->getFormalLinkage();
1820 int S = 0;
1821 if (Lk == Linkage::Internal)
1822 S = 1;
1823 else if (Lk == Linkage::Module)
1824 S = 2;
1825 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
1826 Diag(Old->getLocation(), diag::note_previous_declaration);
1827 return true;
1828}
1829
1832 return true;
1833
1835 return true;
1836
1837 return false;
1838}
1839
1841 const NamedDecl *Old) const {
1842 assert(getASTContext().isSameEntity(New, Old) &&
1843 "New and Old are not the same definition, we should diagnostic it "
1844 "immediately instead of checking it.");
1845 assert(const_cast<Sema *>(this)->isReachable(New) &&
1846 const_cast<Sema *>(this)->isReachable(Old) &&
1847 "We shouldn't see unreachable definitions here.");
1848
1849 Module *NewM = New->getOwningModule();
1850 Module *OldM = Old->getOwningModule();
1851
1852 // We only checks for named modules here. The header like modules is skipped.
1853 // FIXME: This is not right if we import the header like modules in the module
1854 // purview.
1855 //
1856 // For example, assuming "header.h" provides definition for `D`.
1857 // ```C++
1858 // //--- M.cppm
1859 // export module M;
1860 // import "header.h"; // or #include "header.h" but import it by clang modules
1861 // actually.
1862 //
1863 // //--- Use.cpp
1864 // import M;
1865 // import "header.h"; // or uses clang modules.
1866 // ```
1867 //
1868 // In this case, `D` has multiple definitions in multiple TU (M.cppm and
1869 // Use.cpp) and `D` is attached to a named module `M`. The compiler should
1870 // reject it. But the current implementation couldn't detect the case since we
1871 // don't record the information about the importee modules.
1872 //
1873 // But this might not be painful in practice. Since the design of C++20 Named
1874 // Modules suggests us to use headers in global module fragment instead of
1875 // module purview.
1876 if (NewM && NewM->isHeaderLikeModule())
1877 NewM = nullptr;
1878 if (OldM && OldM->isHeaderLikeModule())
1879 OldM = nullptr;
1880
1881 if (!NewM && !OldM)
1882 return true;
1883
1884 // [basic.def.odr]p14.3
1885 // Each such definition shall not be attached to a named module
1886 // ([module.unit]).
1887 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule()))
1888 return true;
1889
1890 // Then New and Old lives in the same TU if their share one same module unit.
1891 if (NewM)
1892 NewM = NewM->getTopLevelModule();
1893 if (OldM)
1894 OldM = OldM->getTopLevelModule();
1895 return OldM == NewM;
1896}
1897
1899 if (D->getDeclContext()->isFileContext())
1900 return false;
1901
1902 return isa<UsingShadowDecl>(D) ||
1905}
1906
1907/// Removes using shadow declarations not at class scope from the lookup
1908/// results.
1910 LookupResult::Filter F = R.makeFilter();
1911 while (F.hasNext())
1913 F.erase();
1914
1915 F.done();
1916}
1917
1918/// Check for this common pattern:
1919/// @code
1920/// class S {
1921/// S(const S&); // DO NOT IMPLEMENT
1922/// void operator=(const S&); // DO NOT IMPLEMENT
1923/// };
1924/// @endcode
1926 // FIXME: Should check for private access too but access is set after we get
1927 // the decl here.
1929 return false;
1930
1931 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1932 return CD->isCopyConstructor();
1933 return D->isCopyAssignmentOperator();
1934}
1935
1936bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1937 const DeclContext *DC = D->getDeclContext();
1938 while (!DC->isTranslationUnit()) {
1939 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1940 if (!RD->hasNameForLinkage())
1941 return true;
1942 }
1943 DC = DC->getParent();
1944 }
1945
1946 return !D->isExternallyVisible();
1947}
1948
1950 assert(D);
1951
1952 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1953 return false;
1954
1955 // Ignore all entities declared within templates, and out-of-line definitions
1956 // of members of class templates.
1957 if (D->getDeclContext()->isDependentContext() ||
1959 return false;
1960
1961 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1962 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1963 return false;
1964 // A non-out-of-line declaration of a member specialization was implicitly
1965 // instantiated; it's the out-of-line declaration that we're interested in.
1966 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1967 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1968 return false;
1969
1970 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1971 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1972 return false;
1973 } else {
1974 // 'static inline' functions are defined in headers; don't warn.
1975 if (FD->isInlined() && !isMainFileLoc(FD->getLocation()))
1976 return false;
1977 }
1978
1979 if (FD->doesThisDeclarationHaveABody() &&
1980 Context.DeclMustBeEmitted(FD))
1981 return false;
1982 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1983 // Constants and utility variables are defined in headers with internal
1984 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1985 // like "inline".)
1986 if (!isMainFileLoc(VD->getLocation()))
1987 return false;
1988
1989 if (Context.DeclMustBeEmitted(VD))
1990 return false;
1991
1992 if (VD->isStaticDataMember() &&
1993 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1994 return false;
1995 if (VD->isStaticDataMember() &&
1996 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1997 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1998 return false;
1999
2000 if (VD->isInline() && !isMainFileLoc(VD->getLocation()))
2001 return false;
2002 } else {
2003 return false;
2004 }
2005
2006 // Only warn for unused decls internal to the translation unit.
2007 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
2008 // for inline functions defined in the main source file, for instance.
2009 return mightHaveNonExternalLinkage(D);
2010}
2011
2013 if (!D)
2014 return;
2015
2016 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2017 const FunctionDecl *First = FD->getFirstDecl();
2019 return; // First should already be in the vector.
2020 }
2021
2022 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2023 const VarDecl *First = VD->getFirstDecl();
2025 return; // First should already be in the vector.
2026 }
2027
2029 UnusedFileScopedDecls.push_back(D);
2030}
2031
2032static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts,
2033 const NamedDecl *D) {
2034 if (D->isInvalidDecl())
2035 return false;
2036
2037 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
2038 // For a decomposition declaration, warn if none of the bindings are
2039 // referenced, instead of if the variable itself is referenced (which
2040 // it is, by the bindings' expressions).
2041 bool IsAllIgnored = true;
2042 for (const auto *BD : DD->bindings()) {
2043 if (BD->isReferenced())
2044 return false;
2045 IsAllIgnored = IsAllIgnored && (BD->isPlaceholderVar(LangOpts) ||
2046 BD->hasAttr<UnusedAttr>());
2047 }
2048 if (IsAllIgnored)
2049 return false;
2050 } else if (!D->getDeclName()) {
2051 return false;
2052 } else if (D->isReferenced() || D->isUsed()) {
2053 return false;
2054 }
2055
2056 if (D->isPlaceholderVar(LangOpts))
2057 return false;
2058
2059 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() ||
2060 D->hasAttr<CleanupAttr>())
2061 return false;
2062
2063 if (isa<LabelDecl>(D))
2064 return true;
2065
2066 // Except for labels, we only care about unused decls that are local to
2067 // functions.
2068 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
2069 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
2070 // For dependent types, the diagnostic is deferred.
2071 WithinFunction =
2072 WithinFunction || (R->isLocalClass() && !R->isDependentType());
2073 if (!WithinFunction)
2074 return false;
2075
2076 if (isa<TypedefNameDecl>(D))
2077 return true;
2078
2079 // White-list anything that isn't a local variable.
2081 return false;
2082
2083 // Types of valid local variables should be complete, so this should succeed.
2084 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2085
2086 const Expr *Init = VD->getInit();
2087 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init))
2088 Init = Cleanups->getSubExpr();
2089
2090 const auto *Ty = VD->getType().getTypePtr();
2091
2092 // Only look at the outermost level of typedef.
2093 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
2094 // Allow anything marked with __attribute__((unused)).
2095 if (TT->getDecl()->hasAttr<UnusedAttr>())
2096 return false;
2097 }
2098
2099 // Warn for reference variables whose initializtion performs lifetime
2100 // extension.
2101 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init);
2102 MTE && MTE->getExtendingDecl()) {
2103 Ty = VD->getType().getNonReferenceType().getTypePtr();
2104 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
2105 }
2106
2107 // If we failed to complete the type for some reason, or if the type is
2108 // dependent, don't diagnose the variable.
2109 if (Ty->isIncompleteType() || Ty->isDependentType())
2110 return false;
2111
2112 // Look at the element type to ensure that the warning behaviour is
2113 // consistent for both scalars and arrays.
2114 Ty = Ty->getBaseElementTypeUnsafe();
2115
2116 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2117 if (Tag->hasAttr<UnusedAttr>())
2118 return false;
2119
2120 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2121 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
2122 return false;
2123
2124 if (Init) {
2125 const auto *Construct =
2126 dyn_cast<CXXConstructExpr>(Init->IgnoreImpCasts());
2127 if (Construct && !Construct->isElidable()) {
2128 const CXXConstructorDecl *CD = Construct->getConstructor();
2129 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
2130 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
2131 return false;
2132 }
2133
2134 // Suppress the warning if we don't know how this is constructed, and
2135 // it could possibly be non-trivial constructor.
2136 if (Init->isTypeDependent()) {
2137 for (const CXXConstructorDecl *Ctor : RD->ctors())
2138 if (!Ctor->isTrivial())
2139 return false;
2140 }
2141
2142 // Suppress the warning if the constructor is unresolved because
2143 // its arguments are dependent.
2145 return false;
2146 }
2147 }
2148 }
2149
2150 // TODO: __attribute__((unused)) templates?
2151 }
2152
2153 return true;
2154}
2155
2157 FixItHint &Hint) {
2158 if (isa<LabelDecl>(D)) {
2160 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
2161 /*SkipTrailingWhitespaceAndNewline=*/false);
2162 if (AfterColon.isInvalid())
2163 return;
2165 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
2166 }
2167}
2168
2171 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2172}
2173
2175 DiagReceiverTy DiagReceiver) {
2176 if (D->isDependentType())
2177 return;
2178
2179 for (auto *TmpD : D->decls()) {
2180 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2181 DiagnoseUnusedDecl(T, DiagReceiver);
2182 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
2183 DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
2184 }
2185}
2186
2189 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
2190}
2191
2194 return;
2195
2196 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2197 // typedefs can be referenced later on, so the diagnostics are emitted
2198 // at end-of-translation-unit.
2200 return;
2201 }
2202
2203 FixItHint Hint;
2205
2206 unsigned DiagID;
2207 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
2208 DiagID = diag::warn_unused_exception_param;
2209 else if (isa<LabelDecl>(D))
2210 DiagID = diag::warn_unused_label;
2211 else
2212 DiagID = diag::warn_unused_variable;
2213
2214 SourceLocation DiagLoc = D->getLocation();
2215 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc));
2216}
2217
2219 DiagReceiverTy DiagReceiver) {
2220 // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2221 // it's not really unused.
2222 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>())
2223 return;
2224
2225 // In C++, `_` variables behave as if they were maybe_unused
2226 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts()))
2227 return;
2228
2229 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2230
2231 if (Ty->isReferenceType() || Ty->isDependentType())
2232 return;
2233
2234 if (const TagDecl *Tag = Ty->getAsTagDecl()) {
2235 if (Tag->hasAttr<UnusedAttr>())
2236 return;
2237 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2238 // mimic gcc's behavior.
2239 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag);
2240 RD && !RD->hasAttr<WarnUnusedAttr>())
2241 return;
2242 }
2243
2244 // Don't warn on volatile file-scope variables. They are visible beyond their
2245 // declaring function and writes to them could be observable side effects.
2246 if (VD->getType().isVolatileQualified() && VD->isFileVarDecl())
2247 return;
2248
2249 // Don't warn about __block Objective-C pointer variables, as they might
2250 // be assigned in the block but not used elsewhere for the purpose of lifetime
2251 // extension.
2252 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2253 return;
2254
2255 // Don't warn about Objective-C pointer variables with precise lifetime
2256 // semantics; they can be used to ensure ARC releases the object at a known
2257 // time, which may mean assignment but no other references.
2258 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2259 return;
2260
2261 auto iter = RefsMinusAssignments.find(VD->getCanonicalDecl());
2262 if (iter == RefsMinusAssignments.end())
2263 return;
2264
2265 assert(iter->getSecond() >= 0 &&
2266 "Found a negative number of references to a VarDecl");
2267 if (int RefCnt = iter->getSecond(); RefCnt > 0) {
2268 // Assume the given VarDecl is "used" if its ref count stored in
2269 // `RefMinusAssignments` is positive, with one exception.
2270 //
2271 // For a C++ variable whose decl (with initializer) entirely consist the
2272 // condition expression of a if/while/for construct,
2273 // Clang creates a DeclRefExpr for the condition expression rather than a
2274 // BinaryOperator of AssignmentOp. Thus, the C++ variable's ref
2275 // count stored in `RefMinusAssignment` equals 1 when the variable is never
2276 // used in the body of the if/while/for construct.
2277 bool UnusedCXXCondDecl = VD->isCXXCondDecl() && (RefCnt == 1);
2278 if (!UnusedCXXCondDecl)
2279 return;
2280 }
2281
2282 unsigned DiagID;
2283 if (isa<ParmVarDecl>(VD))
2284 DiagID = diag::warn_unused_but_set_parameter;
2285 else if (VD->isFileVarDecl())
2286 DiagID = diag::warn_unused_but_set_global;
2287 else
2288 DiagID = diag::warn_unused_but_set_variable;
2289 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
2290}
2291
2293 Sema::DiagReceiverTy DiagReceiver) {
2294 // Verify that we have no forward references left. If so, there was a goto
2295 // or address of a label taken, but no definition of it. Label fwd
2296 // definitions are indicated with a null substmt which is also not a resolved
2297 // MS inline assembly label name.
2298 bool Diagnose = false;
2299 if (L->isMSAsmLabel())
2300 Diagnose = !L->isResolvedMSAsmLabel();
2301 else
2302 Diagnose = L->getStmt() == nullptr;
2303 if (Diagnose)
2304 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
2305 << L);
2306}
2307
2309 S->applyNRVO();
2310
2311 if (S->decl_empty()) return;
2313 "Scope shouldn't contain decls!");
2314
2315 /// We visit the decls in non-deterministic order, but we want diagnostics
2316 /// emitted in deterministic order. Collect any diagnostic that may be emitted
2317 /// and sort the diagnostics before emitting them, after we visited all decls.
2318 struct LocAndDiag {
2319 SourceLocation Loc;
2320 std::optional<SourceLocation> PreviousDeclLoc;
2322 };
2324 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
2325 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
2326 };
2327 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
2328 SourceLocation PreviousDeclLoc,
2329 PartialDiagnostic PD) {
2330 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
2331 };
2332
2333 for (auto *TmpD : S->decls()) {
2334 assert(TmpD && "This decl didn't get pushed??");
2335
2336 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2337 NamedDecl *D = cast<NamedDecl>(TmpD);
2338
2339 // Diagnose unused variables in this scope.
2341 DiagnoseUnusedDecl(D, addDiag);
2342 if (const auto *RD = dyn_cast<RecordDecl>(D))
2343 DiagnoseUnusedNestedTypedefs(RD, addDiag);
2344 // Wait until end of TU to diagnose internal linkage file vars.
2345 if (auto *VD = dyn_cast<VarDecl>(D);
2346 VD && !VD->isInternalLinkageFileVar()) {
2347 DiagnoseUnusedButSetDecl(VD, addDiag);
2348 RefsMinusAssignments.erase(VD->getCanonicalDecl());
2349 }
2350 }
2351
2352 if (!D->getDeclName()) continue;
2353
2354 // If this was a forward reference to a label, verify it was defined.
2355 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2356 CheckPoppedLabel(LD, *this, addDiag);
2357
2358 // Partial translation units that are created in incremental processing must
2359 // not clean up the IdResolver because PTUs should take into account the
2360 // declarations that came from previous PTUs.
2361 if (!PP.isIncrementalProcessingEnabled() || getLangOpts().ObjC ||
2363 IdResolver.RemoveDecl(D);
2364
2365 // Warn on it if we are shadowing a declaration.
2366 auto ShadowI = ShadowingDecls.find(D);
2367 if (ShadowI != ShadowingDecls.end()) {
2368 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2369 addDiagWithPrev(D->getLocation(), FD->getLocation(),
2370 PDiag(diag::warn_ctor_parm_shadows_field)
2371 << D << FD << FD->getParent());
2372 }
2373 ShadowingDecls.erase(ShadowI);
2374 }
2375 }
2376
2377 llvm::sort(DeclDiags,
2378 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
2379 // The particular order for diagnostics is not important, as long
2380 // as the order is deterministic. Using the raw location is going
2381 // to generally be in source order unless there are macro
2382 // expansions involved.
2383 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
2384 });
2385 for (const LocAndDiag &D : DeclDiags) {
2386 Diag(D.Loc, D.PD);
2387 if (D.PreviousDeclLoc)
2388 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
2389 }
2390}
2391
2393 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2394 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2395 (S->isClassScope() && !getLangOpts().CPlusPlus))
2396 S = S->getParent();
2397 return S;
2398}
2399
2400static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2402 switch (Error) {
2404 return "";
2406 return BuiltinInfo.getHeaderName(ID);
2408 return "stdio.h";
2410 return "setjmp.h";
2412 return "ucontext.h";
2413 }
2414 llvm_unreachable("unhandled error kind");
2415}
2416
2418 unsigned ID, SourceLocation Loc) {
2419 DeclContext *Parent = Context.getTranslationUnitDecl();
2420
2421 if (getLangOpts().CPlusPlus) {
2423 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false);
2424 CLinkageDecl->setImplicit();
2425 Parent->addDecl(CLinkageDecl);
2426 Parent = CLinkageDecl;
2427 }
2428
2430 if (Context.BuiltinInfo.isImmediate(ID)) {
2431 assert(getLangOpts().CPlusPlus20 &&
2432 "consteval builtins should only be available in C++20 mode");
2433 ConstexprKind = ConstexprSpecKind::Consteval;
2434 }
2435
2437 Context, Parent, Loc, Loc, II, Type, /*TInfo=*/nullptr, SC_Extern,
2438 getCurFPFeatures().isFPConstrained(), /*isInlineSpecified=*/false,
2439 Type->isFunctionProtoType(), ConstexprKind);
2440 New->setImplicit();
2441 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2442
2443 // Create Decl objects for each parameter, adding them to the
2444 // FunctionDecl.
2445 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2447 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2449 Context, New, SourceLocation(), SourceLocation(), nullptr,
2450 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2451 parm->setScopeInfo(0, i);
2452 Params.push_back(parm);
2453 }
2454 New->setParams(Params);
2455 }
2456
2458 return New;
2459}
2460
2462 Scope *S, bool ForRedeclaration,
2463 SourceLocation Loc) {
2465
2467 QualType R = Context.GetBuiltinType(ID, Error);
2468 if (Error) {
2469 if (!ForRedeclaration)
2470 return nullptr;
2471
2472 // If we have a builtin without an associated type we should not emit a
2473 // warning when we were not able to find a type for it.
2475 Context.BuiltinInfo.allowTypeMismatch(ID))
2476 return nullptr;
2477
2478 // If we could not find a type for setjmp it is because the jmp_buf type was
2479 // not defined prior to the setjmp declaration.
2481 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2482 << Context.BuiltinInfo.getName(ID);
2483 return nullptr;
2484 }
2485
2486 // Generally, we emit a warning that the declaration requires the
2487 // appropriate header.
2488 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2489 << getHeaderName(Context.BuiltinInfo, ID, Error)
2490 << Context.BuiltinInfo.getName(ID);
2491 return nullptr;
2492 }
2493
2494 if (!ForRedeclaration &&
2495 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2496 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2497 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
2498 : diag::ext_implicit_lib_function_decl)
2499 << Context.BuiltinInfo.getName(ID) << R;
2500 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2501 Diag(Loc, diag::note_include_header_or_declare)
2502 << Header << Context.BuiltinInfo.getName(ID);
2503 }
2504
2505 if (R.isNull())
2506 return nullptr;
2507
2508 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2510
2511 // TUScope is the translation-unit scope to insert this function into.
2512 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2513 // relate Scopes to DeclContexts, and probably eliminate CurContext
2514 // entirely, but we're not there yet.
2515 DeclContext *SavedContext = CurContext;
2516 CurContext = New->getDeclContext();
2518 CurContext = SavedContext;
2519 return New;
2520}
2521
2522/// Typedef declarations don't have linkage, but they still denote the same
2523/// entity if their types are the same.
2524/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2525/// isSameEntity.
2526static void
2529 // This is only interesting when modules are enabled.
2530 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2531 return;
2532
2533 // Empty sets are uninteresting.
2534 if (Previous.empty())
2535 return;
2536
2537 LookupResult::Filter Filter = Previous.makeFilter();
2538 while (Filter.hasNext()) {
2539 NamedDecl *Old = Filter.next();
2540
2541 // Non-hidden declarations are never ignored.
2542 if (S.isVisible(Old))
2543 continue;
2544
2545 // Declarations of the same entity are not ignored, even if they have
2546 // different linkages.
2547 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2548 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2549 Decl->getUnderlyingType()))
2550 continue;
2551
2552 // If both declarations give a tag declaration a typedef name for linkage
2553 // purposes, then they declare the same entity.
2554 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2555 Decl->getAnonDeclWithTypedefName())
2556 continue;
2557 }
2558
2559 Filter.erase();
2560 }
2561
2562 Filter.done();
2563}
2564
2566 QualType OldType;
2567 if (const TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2568 OldType = OldTypedef->getUnderlyingType();
2569 else
2570 OldType = Context.getTypeDeclType(Old);
2571 QualType NewType = New->getUnderlyingType();
2572
2573 if (NewType->isVariablyModifiedType()) {
2574 // Must not redefine a typedef with a variably-modified type.
2575 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2576 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2577 << Kind << NewType;
2578 if (Old->getLocation().isValid())
2579 notePreviousDefinition(Old, New->getLocation());
2580 New->setInvalidDecl();
2581 return true;
2582 }
2583
2584 if (OldType != NewType &&
2585 !OldType->isDependentType() &&
2586 !NewType->isDependentType() &&
2587 !Context.hasSameType(OldType, NewType)) {
2588 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2589 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2590 << Kind << NewType << OldType;
2591 if (Old->getLocation().isValid())
2592 notePreviousDefinition(Old, New->getLocation());
2593 New->setInvalidDecl();
2594 return true;
2595 }
2596 return false;
2597}
2598
2600 LookupResult &OldDecls) {
2601 // If the new decl is known invalid already, don't bother doing any
2602 // merging checks.
2603 if (New->isInvalidDecl()) return;
2604
2605 // Allow multiple definitions for ObjC built-in typedefs.
2606 // FIXME: Verify the underlying types are equivalent!
2607 if (getLangOpts().ObjC) {
2608 const IdentifierInfo *TypeID = New->getIdentifier();
2609 switch (TypeID->getLength()) {
2610 default: break;
2611 case 2:
2612 {
2613 if (!TypeID->isStr("id"))
2614 break;
2615 QualType T = New->getUnderlyingType();
2616 if (!T->isPointerType())
2617 break;
2618 if (!T->isVoidPointerType()) {
2619 QualType PT = T->castAs<PointerType>()->getPointeeType();
2620 if (!PT->isStructureType())
2621 break;
2622 }
2623 Context.setObjCIdRedefinitionType(T);
2624 // Install the built-in type for 'id', ignoring the current definition.
2625 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2626 Context.getObjCIdType());
2627 return;
2628 }
2629 case 5:
2630 if (!TypeID->isStr("Class"))
2631 break;
2632 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2633 // Install the built-in type for 'Class', ignoring the current definition.
2634 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2635 Context.getObjCClassType());
2636 return;
2637 case 3:
2638 if (!TypeID->isStr("SEL"))
2639 break;
2640 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2641 // Install the built-in type for 'SEL', ignoring the current definition.
2642 New->setModedTypeSourceInfo(New->getTypeSourceInfo(),
2643 Context.getObjCSelType());
2644 return;
2645 }
2646 // Fall through - the typedef name was not a builtin type.
2647 }
2648
2649 // Verify the old decl was also a type.
2650 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2651 if (!Old) {
2652 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2653 << New->getDeclName();
2654
2655 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2656 if (OldD->getLocation().isValid())
2657 notePreviousDefinition(OldD, New->getLocation());
2658
2659 return New->setInvalidDecl();
2660 }
2661
2662 // If the old declaration is invalid, just give up here.
2663 if (Old->isInvalidDecl())
2664 return New->setInvalidDecl();
2665
2666 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2667 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2668 auto *NewTag = New->getAnonDeclWithTypedefName();
2669 NamedDecl *Hidden = nullptr;
2670 if (OldTag && NewTag &&
2671 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2672 !hasVisibleDefinition(OldTag, &Hidden)) {
2673 // There is a definition of this tag, but it is not visible. Use it
2674 // instead of our tag.
2675 if (OldTD->isModed())
2676 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2677 OldTD->getUnderlyingType());
2678 else
2679 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2680
2681 // An anonymous enum is recognized as a redeclaration only when its
2682 // typedef name gets merged, at which point the new enum and its
2683 // enumerators already have a distinct canonical type. Link the enum
2684 // declarations, but also retype the new enumerators because
2685 // setPreviousDecl() does not update QualTypes built before the merge;
2686 // otherwise the merged typedef and its enumerators disagree on the type
2687 // (GH213299).
2688 //
2689 // FIXME: The global module restriction only limits the impact of this
2690 // change; relax it if the issue shows up in other contexts.
2691 if (Module *M = OldTag->getOwningModule(); M && M->isGlobalModule()) {
2692 if (auto *NewEnum = dyn_cast<EnumDecl>(NewTag)) {
2693 if (auto *OldEnum = dyn_cast<EnumDecl>(OldTag)) {
2694 NewEnum->setPreviousDecl(OldEnum);
2695 QualType EnumType = Context.getCanonicalTagType(OldEnum);
2696 for (auto *ECD : NewEnum->enumerators())
2697 ECD->setType(EnumType);
2698 }
2699 }
2700 }
2701
2702 // Make the old tag definition visible.
2704
2706 }
2707 }
2708
2709 // If the typedef types are not identical, reject them in all languages and
2710 // with any extensions enabled.
2711 if (isIncompatibleTypedef(Old, New))
2712 return;
2713
2714 // The types match. Link up the redeclaration chain and merge attributes if
2715 // the old declaration was a typedef.
2716 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2717 New->setPreviousDecl(Typedef);
2719 }
2720
2721 if (getLangOpts().MicrosoftExt)
2722 return;
2723
2724 if (getLangOpts().CPlusPlus) {
2725 // C++ [dcl.typedef]p2:
2726 // In a given non-class scope, a typedef specifier can be used to
2727 // redefine the name of any type declared in that scope to refer
2728 // to the type to which it already refers.
2730 return;
2731
2732 // C++0x [dcl.typedef]p4:
2733 // In a given class scope, a typedef specifier can be used to redefine
2734 // any class-name declared in that scope that is not also a typedef-name
2735 // to refer to the type to which it already refers.
2736 //
2737 // This wording came in via DR424, which was a correction to the
2738 // wording in DR56, which accidentally banned code like:
2739 //
2740 // struct S {
2741 // typedef struct A { } A;
2742 // };
2743 //
2744 // in the C++03 standard. We implement the C++0x semantics, which
2745 // allow the above but disallow
2746 //
2747 // struct S {
2748 // typedef int I;
2749 // typedef int I;
2750 // };
2751 //
2752 // since that was the intent of DR56.
2753 if (!isa<TypedefNameDecl>(Old))
2754 return;
2755
2756 Diag(New->getLocation(), diag::err_redefinition)
2757 << New->getDeclName();
2758 notePreviousDefinition(Old, New->getLocation());
2759 return New->setInvalidDecl();
2760 }
2761
2762 // Modules always permit redefinition of typedefs, as does C11.
2763 if (getLangOpts().Modules || getLangOpts().C11)
2764 return;
2765
2766 // If we have a redefinition of a typedef in C, emit a warning. This warning
2767 // is normally mapped to an error, but can be controlled with
2768 // -Wtypedef-redefinition. If either the original or the redefinition is
2769 // in a system header, don't emit this for compatibility with GCC.
2770 if (getDiagnostics().getSuppressSystemWarnings() &&
2771 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2772 (Old->isImplicit() ||
2773 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2774 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2775 return;
2776
2777 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2778 << New->getDeclName();
2779 notePreviousDefinition(Old, New->getLocation());
2780}
2781
2783 // If this was an unscoped enumeration, yank all of its enumerators
2784 // out of the scope.
2785 if (auto *ED = dyn_cast<EnumDecl>(New); ED && !ED->isScoped()) {
2786 Scope *EnumScope = getNonFieldDeclScope(S);
2787 for (auto *ECD : ED->enumerators()) {
2788 assert(EnumScope->isDeclScope(ECD));
2789 EnumScope->RemoveDecl(ECD);
2790 IdResolver.RemoveDecl(ECD);
2791 }
2792 }
2793}
2794
2795/// DeclhasAttr - returns true if decl Declaration already has the target
2796/// attribute.
2797static bool DeclHasAttr(const Decl *D, const Attr *A) {
2798 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2799 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2800 for (const auto *i : D->attrs())
2801 if (i->getKind() == A->getKind()) {
2802 if (Ann) {
2803 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2804 return true;
2805 continue;
2806 }
2807 // FIXME: Don't hardcode this check
2808 if (OA && isa<OwnershipAttr>(i))
2809 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2810 return true;
2811 }
2812
2813 return false;
2814}
2815
2817 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2818 return VD->isThisDeclarationADefinition();
2819 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2820 return TD->isCompleteDefinition() || TD->isBeingDefined();
2821 return true;
2822}
2823
2824/// Merge alignment attributes from \p Old to \p New, taking into account the
2825/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2826///
2827/// \return \c true if any attributes were added to \p New.
2828static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2829 // Look for alignas attributes on Old, and pick out whichever attribute
2830 // specifies the strictest alignment requirement.
2831 AlignedAttr *OldAlignasAttr = nullptr;
2832 AlignedAttr *OldStrictestAlignAttr = nullptr;
2833 unsigned OldAlign = 0;
2834 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2835 // FIXME: We have no way of representing inherited dependent alignments
2836 // in a case like:
2837 // template<int A, int B> struct alignas(A) X;
2838 // template<int A, int B> struct alignas(B) X {};
2839 // For now, we just ignore any alignas attributes which are not on the
2840 // definition in such a case.
2841 if (I->isAlignmentDependent())
2842 return false;
2843
2844 if (I->isAlignas())
2845 OldAlignasAttr = I;
2846
2847 unsigned Align = I->getAlignment(S.Context);
2848 if (Align > OldAlign) {
2849 OldAlign = Align;
2850 OldStrictestAlignAttr = I;
2851 }
2852 }
2853
2854 // Look for alignas attributes on New.
2855 AlignedAttr *NewAlignasAttr = nullptr;
2856 unsigned NewAlign = 0;
2857 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2858 if (I->isAlignmentDependent())
2859 return false;
2860
2861 if (I->isAlignas())
2862 NewAlignasAttr = I;
2863
2864 unsigned Align = I->getAlignment(S.Context);
2865 if (Align > NewAlign)
2866 NewAlign = Align;
2867 }
2868
2869 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2870 // Both declarations have 'alignas' attributes. We require them to match.
2871 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2872 // fall short. (If two declarations both have alignas, they must both match
2873 // every definition, and so must match each other if there is a definition.)
2874
2875 // If either declaration only contains 'alignas(0)' specifiers, then it
2876 // specifies the natural alignment for the type.
2877 if (OldAlign == 0 || NewAlign == 0) {
2878 QualType Ty;
2879 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2880 Ty = VD->getType();
2881 else
2883
2884 if (OldAlign == 0)
2885 OldAlign = S.Context.getTypeAlign(Ty);
2886 if (NewAlign == 0)
2887 NewAlign = S.Context.getTypeAlign(Ty);
2888 }
2889
2890 if (OldAlign != NewAlign) {
2891 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2894 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2895 }
2896 }
2897
2898 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2899 // C++11 [dcl.align]p6:
2900 // if any declaration of an entity has an alignment-specifier,
2901 // every defining declaration of that entity shall specify an
2902 // equivalent alignment.
2903 // C11 6.7.5/7:
2904 // If the definition of an object does not have an alignment
2905 // specifier, any other declaration of that object shall also
2906 // have no alignment specifier.
2907 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2908 << OldAlignasAttr;
2909 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2910 << OldAlignasAttr;
2911 }
2912
2913 bool AnyAdded = false;
2914
2915 // Ensure we have an attribute representing the strictest alignment.
2916 if (OldAlign > NewAlign) {
2917 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2918 Clone->setInherited(true);
2919 New->addAttr(Clone);
2920 AnyAdded = true;
2921 }
2922
2923 // Ensure we have an alignas attribute if the old declaration had one.
2924 if (OldAlignasAttr && !NewAlignasAttr &&
2925 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2926 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2927 Clone->setInherited(true);
2928 New->addAttr(Clone);
2929 AnyAdded = true;
2930 }
2931
2932 return AnyAdded;
2933}
2934
2935#define WANT_DECL_MERGE_LOGIC
2936#include "clang/Sema/AttrParsedAttrImpl.inc"
2937#undef WANT_DECL_MERGE_LOGIC
2938
2940 const InheritableAttr *Attr,
2942 // Diagnose any mutual exclusions between the attribute that we want to add
2943 // and attributes that already exist on the declaration.
2944 if (!DiagnoseMutualExclusions(S, D, Attr))
2945 return false;
2946
2947 // This function copies an attribute Attr from a previous declaration to the
2948 // new declaration D if the new declaration doesn't itself have that attribute
2949 // yet or if that attribute allows duplicates.
2950 // If you're adding a new attribute that requires logic different from
2951 // "use explicit attribute on decl if present, else use attribute from
2952 // previous decl", for example if the attribute needs to be consistent
2953 // between redeclarations, you need to call a custom merge function here.
2954 InheritableAttr *NewAttr = nullptr;
2955 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) {
2956 const IdentifierInfo *InferredPlatformII = nullptr;
2957 if (AvailabilityAttr *Inf = AA->getInferredAttrAs())
2958 InferredPlatformII = Inf->getPlatform();
2960 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2961 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2962 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2963 AA->getPriority(), AA->getEnvironment(), InferredPlatformII);
2964 } else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2965 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2966 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2967 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2968 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2969 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2970 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2971 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2972 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2973 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2974 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2975 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2976 FA->getFirstArg());
2977 else if (const auto *FMA = dyn_cast<FormatMatchesAttr>(Attr))
2978 NewAttr = S.mergeFormatMatchesAttr(
2979 D, *FMA, FMA->getType(), FMA->getFormatIdx(), FMA->getFormatString());
2980 else if (const auto *MFA = dyn_cast<ModularFormatAttr>(Attr))
2981 NewAttr = S.mergeModularFormatAttr(
2982 D, *MFA, MFA->getModularImplFn(), MFA->getImplName(),
2983 MutableArrayRef<StringRef>{MFA->aspects_begin(), MFA->aspects_size()});
2984 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2985 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2986 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2987 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2988 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2989 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2990 IA->getInheritanceModel());
2991 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2992 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2993 &S.Context.Idents.get(AA->getSpelling()));
2994 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2997 // CUDA target attributes are part of function signature for
2998 // overloading purposes and must not be merged.
2999 return false;
3000 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
3001 NewAttr = S.mergeMinSizeAttr(D, *MA);
3002 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
3003 NewAttr = S.Swift().mergeNameAttr(D, *SNA, SNA->getName());
3004 else if (const auto *SAA = dyn_cast<SwiftAttrAttr>(Attr))
3005 NewAttr = S.Swift().mergeAttrAttr(D, *SAA);
3006 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
3007 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
3008 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
3009 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
3010 else if (isa<AlignedAttr>(Attr))
3011 // AlignedAttrs are handled separately, because we need to handle all
3012 // such attributes on a declaration at the same time.
3013 NewAttr = nullptr;
3018 NewAttr = nullptr;
3019 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
3020 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
3021 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
3022 NewAttr = S.Wasm().mergeImportModuleAttr(D, *IMA);
3023 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
3024 NewAttr = S.Wasm().mergeImportNameAttr(D, *INA);
3025 else if (const auto *ENA = dyn_cast<WebAssemblyExportNameAttr>(Attr))
3026 NewAttr = S.Wasm().mergeExportNameAttr(D, *ENA);
3027 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
3028 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
3029 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
3030 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
3031 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
3032 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
3033 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
3034 NewAttr = S.HLSL().mergeNumThreadsAttr(D, *NT, NT->getX(), NT->getY(),
3035 NT->getZ());
3036 else if (const auto *WS = dyn_cast<HLSLWaveSizeAttr>(Attr))
3037 NewAttr = S.HLSL().mergeWaveSizeAttr(D, *WS, WS->getMin(), WS->getMax(),
3038 WS->getPreferred(),
3039 WS->getSpelledArgsCount());
3040 else if (const auto *CI = dyn_cast<HLSLVkConstantIdAttr>(Attr))
3041 NewAttr = S.HLSL().mergeVkConstantIdAttr(D, *CI, CI->getId());
3042 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
3043 NewAttr = S.HLSL().mergeShaderAttr(D, *SA, SA->getType());
3044 else if (isa<SuppressAttr>(Attr))
3045 // Do nothing. Each redeclaration should be suppressed separately.
3046 NewAttr = nullptr;
3047 else if (const auto *RD = dyn_cast<OpenACCRoutineDeclAttr>(Attr))
3048 NewAttr = S.OpenACC().mergeRoutineDeclAttr(*RD);
3049 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
3050 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
3051 else if (const auto *PA = dyn_cast<PersonalityAttr>(Attr))
3052 NewAttr = S.mergePersonalityAttr(D, PA->getRoutine(), *PA);
3053
3054 if (NewAttr) {
3055 NewAttr->setInherited(true);
3056 D->addAttr(NewAttr);
3057 if (isa<MSInheritanceAttr>(NewAttr))
3059 return true;
3060 }
3061
3062 return false;
3063}
3064
3065static const NamedDecl *getDefinition(const Decl *D) {
3066 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3067 if (const auto *Def = TD->getDefinition(); Def && !Def->isBeingDefined())
3068 return Def;
3069 return nullptr;
3070 }
3071 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3072 const VarDecl *Def = VD->getDefinition();
3073 if (Def)
3074 return Def;
3075 return VD->getActingDefinition();
3076 }
3077 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3078 const FunctionDecl *Def = nullptr;
3079 if (FD->isDefined(Def, true))
3080 return Def;
3081 }
3082 return nullptr;
3083}
3084
3085static bool hasAttribute(const Decl *D, attr::Kind Kind) {
3086 for (const auto *Attribute : D->attrs())
3087 if (Attribute->getKind() == Kind)
3088 return true;
3089 return false;
3090}
3091
3092/// checkNewAttributesAfterDef - If we already have a definition, check that
3093/// there are no new attributes in this declaration.
3094static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
3095 if (!New->hasAttrs())
3096 return;
3097
3098 const NamedDecl *Def = getDefinition(Old);
3099 if (!Def || Def == New)
3100 return;
3101
3102 AttrVec &NewAttributes = New->getAttrs();
3103 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
3104 Attr *NewAttribute = NewAttributes[I];
3105
3106 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
3107 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
3108 SkipBodyInfo SkipBody;
3109 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
3110
3111 // If we're skipping this definition, drop the "alias" attribute.
3112 if (SkipBody.ShouldSkip) {
3113 NewAttributes.erase(NewAttributes.begin() + I);
3114 --E;
3115 continue;
3116 }
3117 } else {
3118 VarDecl *VD = cast<VarDecl>(New);
3119 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
3121 ? diag::err_alias_after_tentative
3122 : diag::err_redefinition;
3123 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
3124 if (Diag == diag::err_redefinition)
3125 S.notePreviousDefinition(Def, VD->getLocation());
3126 else
3127 S.Diag(Def->getLocation(), diag::note_previous_definition);
3128 VD->setInvalidDecl();
3129 }
3130 ++I;
3131 continue;
3132 }
3133
3134 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
3135 // Tentative definitions are only interesting for the alias check above.
3136 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
3137 ++I;
3138 continue;
3139 }
3140 }
3141
3142 if (hasAttribute(Def, NewAttribute->getKind())) {
3143 ++I;
3144 continue; // regular attr merging will take care of validating this.
3145 }
3146
3147 if (NewAttribute->getLocation().isInvalid()) {
3148 // An attribute with no source location was not written by the user. API
3149 // notes, in particular, are matched against whichever declaration the
3150 // compiler reaches, which can be a redeclaration that follows the
3151 // definition, possibly in a different module. There is nothing for the
3152 // user to correct, and erasing the attribute would silently change what
3153 // the annotated API means.
3154 ++I;
3155 continue;
3156 }
3157
3158 if (isa<C11NoReturnAttr>(NewAttribute)) {
3159 // C's _Noreturn is allowed to be added to a function after it is defined.
3160 ++I;
3161 continue;
3162 } else if (isa<UuidAttr>(NewAttribute)) {
3163 // msvc will allow a subsequent definition to add an uuid to a class
3164 ++I;
3165 continue;
3167 NewAttribute) &&
3168 NewAttribute->isStandardAttributeSyntax()) {
3169 // C++14 [dcl.attr.deprecated]p3: A name or entity declared without the
3170 // deprecated attribute can later be re-declared with the attribute and
3171 // vice-versa.
3172 // C++17 [dcl.attr.unused]p4: A name or entity declared without the
3173 // maybe_unused attribute can later be redeclared with the attribute and
3174 // vice versa.
3175 // C++20 [dcl.attr.nodiscard]p2: A name or entity declared without the
3176 // nodiscard attribute can later be redeclared with the attribute and
3177 // vice-versa.
3178 // C23 6.7.13.3p3, 6.7.13.4p3. and 6.7.13.5p5 give the same allowances.
3179 ++I;
3180 continue;
3181 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
3182 if (AA->isAlignas()) {
3183 // C++11 [dcl.align]p6:
3184 // if any declaration of an entity has an alignment-specifier,
3185 // every defining declaration of that entity shall specify an
3186 // equivalent alignment.
3187 // C11 6.7.5/7:
3188 // If the definition of an object does not have an alignment
3189 // specifier, any other declaration of that object shall also
3190 // have no alignment specifier.
3191 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
3192 << AA;
3193 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
3194 << AA;
3195 NewAttributes.erase(NewAttributes.begin() + I);
3196 --E;
3197 continue;
3198 }
3199 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
3200 // If there is a C definition followed by a redeclaration with this
3201 // attribute then there are two different definitions. In C++, prefer the
3202 // standard diagnostics.
3203 if (!S.getLangOpts().CPlusPlus) {
3204 S.Diag(NewAttribute->getLocation(),
3205 diag::err_loader_uninitialized_redeclaration);
3206 S.Diag(Def->getLocation(), diag::note_previous_definition);
3207 NewAttributes.erase(NewAttributes.begin() + I);
3208 --E;
3209 continue;
3210 }
3211 } else if (isa<SelectAnyAttr>(NewAttribute) &&
3212 cast<VarDecl>(New)->isInline() &&
3213 !cast<VarDecl>(New)->isInlineSpecified()) {
3214 // Don't warn about applying selectany to implicitly inline variables.
3215 // Older compilers and language modes would require the use of selectany
3216 // to make such variables inline, and it would have no effect if we
3217 // honored it.
3218 ++I;
3219 continue;
3220 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
3221 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
3222 // declarations after definitions.
3223 ++I;
3224 continue;
3225 } else if (isa<SYCLKernelEntryPointAttr>(NewAttribute)) {
3226 // Elevate latent uses of the sycl_kernel_entry_point attribute to an
3227 // error since the definition will have already been created without
3228 // the semantic effects of the attribute having been applied.
3229 S.Diag(NewAttribute->getLocation(),
3230 diag::err_sycl_entry_point_after_definition)
3231 << NewAttribute;
3232 S.Diag(Def->getLocation(), diag::note_previous_definition);
3233 cast<SYCLKernelEntryPointAttr>(NewAttribute)->setInvalidAttr();
3234 ++I;
3235 continue;
3236 } else if (isa<SYCLExternalAttr>(NewAttribute)) {
3237 // SYCLExternalAttr may be added after a definition.
3238 ++I;
3239 continue;
3240 }
3241
3242 S.Diag(NewAttribute->getLocation(),
3243 diag::warn_attribute_precede_definition);
3244 S.Diag(Def->getLocation(), diag::note_previous_definition);
3245 NewAttributes.erase(NewAttributes.begin() + I);
3246 --E;
3247 }
3248}
3249
3250static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
3251 const ConstInitAttr *CIAttr,
3252 bool AttrBeforeInit) {
3253 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
3254
3255 // Figure out a good way to write this specifier on the old declaration.
3256 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
3257 // enough of the attribute list spelling information to extract that without
3258 // heroics.
3259 std::string SuitableSpelling;
3260 if (S.getLangOpts().CPlusPlus20)
3261 SuitableSpelling = std::string(
3262 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
3263 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3264 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3265 InsertLoc, {tok::l_square, tok::l_square,
3266 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
3267 S.PP.getIdentifierInfo("require_constant_initialization"),
3268 tok::r_square, tok::r_square}));
3269 if (SuitableSpelling.empty())
3270 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
3271 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
3272 S.PP.getIdentifierInfo("require_constant_initialization"),
3273 tok::r_paren, tok::r_paren}));
3274 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3275 SuitableSpelling = "constinit";
3276 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3277 SuitableSpelling = "[[clang::require_constant_initialization]]";
3278 if (SuitableSpelling.empty())
3279 SuitableSpelling = "__attribute__((require_constant_initialization))";
3280 SuitableSpelling += " ";
3281
3282 if (AttrBeforeInit) {
3283 // extern constinit int a;
3284 // int a = 0; // error (missing 'constinit'), accepted as extension
3285 assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3286 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3287 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3288 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3289 } else {
3290 // int a = 0;
3291 // constinit extern int a; // error (missing 'constinit')
3292 S.Diag(CIAttr->getLocation(),
3293 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3294 : diag::warn_require_const_init_added_too_late)
3295 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3296 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3297 << CIAttr->isConstinit()
3298 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3299 }
3300}
3301
3304 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3305 UsedAttr *NewAttr = OldAttr->clone(Context);
3306 NewAttr->setInherited(true);
3307 New->addAttr(NewAttr);
3308 }
3309 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3310 RetainAttr *NewAttr = OldAttr->clone(Context);
3311 NewAttr->setInherited(true);
3312 New->addAttr(NewAttr);
3313 }
3314
3315 if (!Old->hasAttrs() && !New->hasAttrs())
3316 return;
3317
3318 // [dcl.constinit]p1:
3319 // If the [constinit] specifier is applied to any declaration of a
3320 // variable, it shall be applied to the initializing declaration.
3321 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3322 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3323 if (bool(OldConstInit) != bool(NewConstInit)) {
3324 const auto *OldVD = cast<VarDecl>(Old);
3325 auto *NewVD = cast<VarDecl>(New);
3326
3327 // Find the initializing declaration. Note that we might not have linked
3328 // the new declaration into the redeclaration chain yet.
3329 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3330 if (!InitDecl &&
3331 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3332 InitDecl = NewVD;
3333
3334 if (InitDecl == NewVD) {
3335 // This is the initializing declaration. If it would inherit 'constinit',
3336 // that's ill-formed. (Note that we do not apply this to the attribute
3337 // form).
3338 if (OldConstInit && OldConstInit->isConstinit())
3339 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3340 /*AttrBeforeInit=*/true);
3341 } else if (NewConstInit) {
3342 // This is the first time we've been told that this declaration should
3343 // have a constant initializer. If we already saw the initializing
3344 // declaration, this is too late.
3345 if (InitDecl && InitDecl != NewVD) {
3346 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3347 /*AttrBeforeInit=*/false);
3348 NewVD->dropAttr<ConstInitAttr>();
3349 }
3350 }
3351 }
3352
3353 // Attributes declared post-definition are currently ignored.
3354 checkNewAttributesAfterDef(*this, New, Old);
3355
3356 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3357 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3358 if (!OldA->isEquivalent(NewA)) {
3359 // This redeclaration changes __asm__ label.
3360 Diag(New->getLocation(), diag::err_different_asm_label);
3361 Diag(OldA->getLocation(), diag::note_previous_declaration);
3362 }
3363 } else if (Old->isUsed()) {
3364 // This redeclaration adds an __asm__ label to a declaration that has
3365 // already been ODR-used.
3366 Diag(New->getLocation(), diag::err_late_asm_label_name)
3367 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3368 }
3369 }
3370
3371 // Re-declaration cannot add abi_tag's.
3372 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3373 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3374 for (const auto &NewTag : NewAbiTagAttr->tags()) {
3375 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3376 Diag(NewAbiTagAttr->getLocation(),
3377 diag::err_new_abi_tag_on_redeclaration)
3378 << NewTag;
3379 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3380 }
3381 }
3382 } else {
3383 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3384 Diag(Old->getLocation(), diag::note_previous_declaration);
3385 }
3386 }
3387
3388 // This redeclaration adds a section attribute.
3389 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3390 if (auto *VD = dyn_cast<VarDecl>(New)) {
3391 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3392 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3393 Diag(Old->getLocation(), diag::note_previous_declaration);
3394 }
3395 }
3396 }
3397
3398 // Redeclaration adds code-seg attribute.
3399 const auto *NewCSA = New->getAttr<CodeSegAttr>();
3400 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3401 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3402 Diag(New->getLocation(), diag::warn_mismatched_section)
3403 << 0 /*codeseg*/;
3404 Diag(Old->getLocation(), diag::note_previous_declaration);
3405 }
3406
3407 if (!Old->hasAttrs())
3408 return;
3409
3410 bool foundAny = New->hasAttrs();
3411
3412 // Ensure that any moving of objects within the allocated map is done before
3413 // we process them.
3414 if (!foundAny) New->setAttrs(AttrVec());
3415
3416 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3417 // Ignore deprecated/unavailable/availability attributes if requested.
3419 if (isa<DeprecatedAttr>(I) ||
3422 switch (AMK) {
3424 continue;
3425
3430 LocalAMK = AMK;
3431 break;
3432 }
3433 }
3434
3435 // Already handled.
3436 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3437 continue;
3438
3439 // Don't propagate inferred noreturn or conflicting inline attributes to
3440 // explicit specializations.
3442 isa<NoInlineAttr>(I)) {
3443 if (auto *FD = dyn_cast<FunctionDecl>(New);
3444 FD &&
3445 FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3446 continue;
3447 }
3448
3449 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3450 foundAny = true;
3451 }
3452
3453 if (mergeAlignedAttrs(*this, New, Old))
3454 foundAny = true;
3455
3456 if (!foundAny) New->dropAttrs();
3457}
3458
3460 for (const Attr *A : D->attrs())
3461 checkAttrIsTypeDependent(D, A);
3462}
3463
3464// Returns the number of added attributes.
3465template <class T>
3466static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From,
3467 Sema &S) {
3468 unsigned found = 0;
3469 for (const auto *I : From->specific_attrs<T>()) {
3470 if (!DeclHasAttr(To, I)) {
3471 T *newAttr = cast<T>(I->clone(S.Context));
3472 newAttr->setInherited(true);
3473 To->addAttr(newAttr);
3474 ++found;
3475 }
3476 }
3477 return found;
3478}
3479
3480template <class F>
3481static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From,
3482 F &&propagator) {
3483 if (!From->hasAttrs()) {
3484 return;
3485 }
3486
3487 bool foundAny = To->hasAttrs();
3488
3489 // Ensure that any moving of objects within the allocated map is
3490 // done before we process them.
3491 if (!foundAny)
3492 To->setAttrs(AttrVec());
3493
3494 foundAny |= std::forward<F>(propagator)(To, From) != 0;
3495
3496 if (!foundAny)
3497 To->dropAttrs();
3498}
3499
3500/// mergeParamDeclAttributes - Copy attributes from the old parameter
3501/// to the new one.
3503 const ParmVarDecl *oldDecl, Sema &S) {
3505 newDecl, oldDecl, [&S](ParmVarDecl *To, const ParmVarDecl *From) {
3506 unsigned found = 0;
3507 found += propagateAttribute<InheritableParamAttr>(To, From, S);
3508 // Propagate the lifetimebound attribute from parameters to the
3509 // most recent declaration. Note that this doesn't include the implicit
3510 // 'this' parameter, as the attribute is applied to the function type in
3511 // that case.
3512 found += propagateAttribute<LifetimeBoundAttr>(To, From, S);
3513 return found;
3514 });
3515}
3516
3518 const ASTContext &Ctx) {
3519
3520 auto NoSizeInfo = [&Ctx](QualType Ty) {
3521 if (Ty->isIncompleteArrayType() || Ty->isPointerType())
3522 return true;
3523 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
3524 return VAT->getSizeModifier() == ArraySizeModifier::Star;
3525 return false;
3526 };
3527
3528 // `type[]` is equivalent to `type *` and `type[*]`.
3529 if (NoSizeInfo(Old) && NoSizeInfo(New))
3530 return true;
3531
3532 // Don't try to compare VLA sizes, unless one of them has the star modifier.
3533 if (Old->isVariableArrayType() && New->isVariableArrayType()) {
3534 const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
3535 const auto *NewVAT = Ctx.getAsVariableArrayType(New);
3536 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^
3537 (NewVAT->getSizeModifier() == ArraySizeModifier::Star))
3538 return false;
3539 return true;
3540 }
3541
3542 // Only compare size, ignore Size modifiers and CVR.
3543 if (Old->isConstantArrayType() && New->isConstantArrayType()) {
3544 return Ctx.getAsConstantArrayType(Old)->getSize() ==
3546 }
3547
3548 // Don't try to compare dependent sized array
3549 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
3550 return true;
3551 }
3552
3553 return Old == New;
3554}
3555
3556static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3557 const ParmVarDecl *OldParam,
3558 Sema &S) {
3559 if (auto Oldnullability = OldParam->getType()->getNullability()) {
3560 if (auto Newnullability = NewParam->getType()->getNullability()) {
3561 if (*Oldnullability != *Newnullability) {
3562 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3564 *Newnullability,
3566 != 0))
3568 *Oldnullability,
3570 != 0));
3571 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3572 }
3573 } else {
3574 QualType NewT = NewParam->getType();
3575 NewT = S.Context.getAttributedType(*Oldnullability, NewT, NewT);
3576 NewParam->setType(NewT);
3577 }
3578 }
3579 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
3580 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
3581 if (OldParamDT && NewParamDT &&
3582 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
3583 QualType OldParamOT = OldParamDT->getOriginalType();
3584 QualType NewParamOT = NewParamDT->getOriginalType();
3585 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
3586 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
3587 << NewParam << NewParamOT;
3588 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
3589 << OldParamOT;
3590 }
3591 }
3592}
3593
3594namespace {
3595
3596/// Used in MergeFunctionDecl to keep track of function parameters in
3597/// C.
3598struct GNUCompatibleParamWarning {
3599 ParmVarDecl *OldParm;
3600 ParmVarDecl *NewParm;
3601 QualType PromotedType;
3602};
3603
3604} // end anonymous namespace
3605
3606// Determine whether the previous declaration was a definition, implicit
3607// declaration, or a declaration.
3608template <typename T>
3609static std::pair<diag::kind, SourceLocation>
3611 diag::kind PrevDiag;
3612 SourceLocation OldLocation = Old->getLocation();
3613 if (Old->isThisDeclarationADefinition())
3614 PrevDiag = diag::note_previous_definition;
3615 else if (Old->isImplicit()) {
3616 PrevDiag = diag::note_previous_implicit_declaration;
3617 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
3618 if (FD->getBuiltinID())
3619 PrevDiag = diag::note_previous_builtin_declaration;
3620 }
3621 if (OldLocation.isInvalid())
3622 OldLocation = New->getLocation();
3623 } else
3624 PrevDiag = diag::note_previous_declaration;
3625 return std::make_pair(PrevDiag, OldLocation);
3626}
3627
3628/// canRedefineFunction - checks if a function can be redefined. Currently,
3629/// only extern inline functions can be redefined, and even then only in
3630/// GNU89 mode.
3631static bool canRedefineFunction(const FunctionDecl *FD,
3632 const LangOptions& LangOpts) {
3633 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3634 !LangOpts.CPlusPlus &&
3635 FD->isInlineSpecified() &&
3636 FD->getStorageClass() == SC_Extern);
3637}
3638
3639const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3640 const AttributedType *AT = T->getAs<AttributedType>();
3641 while (AT && !AT->isCallingConv())
3642 AT = AT->getModifiedType()->getAs<AttributedType>();
3643 return AT;
3644}
3645
3646template <typename T>
3647static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3648 const DeclContext *DC = Old->getDeclContext();
3649 if (DC->isRecord())
3650 return false;
3651
3652 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3653 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3654 return true;
3655 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3656 return true;
3657 return false;
3658}
3659
3660template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3661static bool isExternC(VarTemplateDecl *) { return false; }
3662static bool isExternC(FunctionTemplateDecl *) { return false; }
3663
3664/// Check whether a redeclaration of an entity introduced by a
3665/// using-declaration is valid, given that we know it's not an overload
3666/// (nor a hidden tag declaration).
3667template<typename ExpectedDecl>
3669 ExpectedDecl *New) {
3670 // C++11 [basic.scope.declarative]p4:
3671 // Given a set of declarations in a single declarative region, each of
3672 // which specifies the same unqualified name,
3673 // -- they shall all refer to the same entity, or all refer to functions
3674 // and function templates; or
3675 // -- exactly one declaration shall declare a class name or enumeration
3676 // name that is not a typedef name and the other declarations shall all
3677 // refer to the same variable or enumerator, or all refer to functions
3678 // and function templates; in this case the class name or enumeration
3679 // name is hidden (3.3.10).
3680
3681 // C++11 [namespace.udecl]p14:
3682 // If a function declaration in namespace scope or block scope has the
3683 // same name and the same parameter-type-list as a function introduced
3684 // by a using-declaration, and the declarations do not declare the same
3685 // function, the program is ill-formed.
3686
3687 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3688 if (Old &&
3689 !Old->getDeclContext()->getRedeclContext()->Equals(
3690 New->getDeclContext()->getRedeclContext()) &&
3691 !(isExternC(Old) && isExternC(New)))
3692 Old = nullptr;
3693
3694 if (!Old) {
3695 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3696 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3697 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3698 return true;
3699 }
3700 return false;
3701}
3702
3704 const FunctionDecl *B) {
3705 assert(A->getNumParams() == B->getNumParams());
3706
3707 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3708 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3709 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3710 if (AttrA == AttrB)
3711 return true;
3712 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3713 AttrA->isDynamic() == AttrB->isDynamic();
3714 };
3715
3716 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3717}
3718
3719/// If necessary, adjust the semantic declaration context for a qualified
3720/// declaration to name the correct inline namespace within the qualifier.
3722 DeclaratorDecl *OldD) {
3723 // The only case where we need to update the DeclContext is when
3724 // redeclaration lookup for a qualified name finds a declaration
3725 // in an inline namespace within the context named by the qualifier:
3726 //
3727 // inline namespace N { int f(); }
3728 // int ::f(); // Sema DC needs adjusting from :: to N::.
3729 //
3730 // For unqualified declarations, the semantic context *can* change
3731 // along the redeclaration chain (for local extern declarations,
3732 // extern "C" declarations, and friend declarations in particular).
3733 if (!NewD->getQualifier())
3734 return;
3735
3736 // NewD is probably already in the right context.
3737 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3738 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3739 if (NamedDC->Equals(SemaDC))
3740 return;
3741
3742 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3743 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3744 "unexpected context for redeclaration");
3745
3746 auto *LexDC = NewD->getLexicalDeclContext();
3747 auto FixSemaDC = [=](NamedDecl *D) {
3748 if (!D)
3749 return;
3750 D->setDeclContext(SemaDC);
3751 D->setLexicalDeclContext(LexDC);
3752 };
3753
3754 FixSemaDC(NewD);
3755 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3756 FixSemaDC(FD->getDescribedFunctionTemplate());
3757 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3758 FixSemaDC(VD->getDescribedVarTemplate());
3759}
3760
3762 bool MergeTypeWithOld, bool NewDeclIsDefn) {
3763 // Verify the old decl was also a function.
3764 FunctionDecl *Old = OldD->getAsFunction();
3765 if (!Old) {
3766 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3767 // We don't need to check the using friend pattern from other module unit
3768 // since we should have diagnosed such cases in its unit already.
3769 if (New->getFriendObjectKind() && !OldD->isInAnotherModuleUnit()) {
3770 Diag(New->getLocation(), diag::err_using_decl_friend);
3771 Diag(Shadow->getTargetDecl()->getLocation(),
3772 diag::note_using_decl_target);
3773 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3774 << 0;
3775 return true;
3776 }
3777
3778 // Check whether the two declarations might declare the same function or
3779 // function template.
3780 if (FunctionTemplateDecl *NewTemplate =
3781 New->getDescribedFunctionTemplate()) {
3783 NewTemplate))
3784 return true;
3785 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3786 ->getAsFunction();
3787 } else {
3788 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3789 return true;
3790 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3791 }
3792 } else {
3793 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3794 << New->getDeclName();
3795 notePreviousDefinition(OldD, New->getLocation());
3796 return true;
3797 }
3798 }
3799
3800 // If the old declaration was found in an inline namespace and the new
3801 // declaration was qualified, update the DeclContext to match.
3803
3804 // If the old declaration is invalid, just give up here.
3805 if (Old->isInvalidDecl())
3806 return true;
3807
3808 // Disallow redeclaration of some builtins.
3809 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3810 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3811 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3812 << Old << Old->getType();
3813 return true;
3814 }
3815
3816 diag::kind PrevDiag;
3817 SourceLocation OldLocation;
3818 std::tie(PrevDiag, OldLocation) =
3820
3821 // Don't complain about this if we're in GNU89 mode and the old function
3822 // is an extern inline function.
3823 // Don't complain about specializations. They are not supposed to have
3824 // storage classes.
3825 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3826 New->getStorageClass() == SC_Static &&
3827 Old->hasExternalFormalLinkage() &&
3828 !New->getTemplateSpecializationInfo() &&
3830 if (getLangOpts().MicrosoftExt) {
3831 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3832 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3833 } else {
3834 Diag(New->getLocation(), diag::err_static_non_static)
3835 << New << /*MixedLinkageUB=*/false;
3836 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3837 return true;
3838 }
3839 }
3840
3841 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3842 if (!Old->hasAttr<InternalLinkageAttr>()) {
3843 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3844 << ILA;
3845 Diag(Old->getLocation(), diag::note_previous_declaration);
3846 New->dropAttr<InternalLinkageAttr>();
3847 }
3848
3849 if (auto *EA = New->getAttr<ErrorAttr>()) {
3850 if (!Old->hasAttr<ErrorAttr>()) {
3851 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3852 Diag(Old->getLocation(), diag::note_previous_declaration);
3853 New->dropAttr<ErrorAttr>();
3854 }
3855 }
3856
3858 return true;
3859
3860 if (!getLangOpts().CPlusPlus) {
3861 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3862 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3863 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3864 << New << OldOvl;
3865
3866 // Try our best to find a decl that actually has the overloadable
3867 // attribute for the note. In most cases (e.g. programs with only one
3868 // broken declaration/definition), this won't matter.
3869 //
3870 // FIXME: We could do this if we juggled some extra state in
3871 // OverloadableAttr, rather than just removing it.
3872 const Decl *DiagOld = Old;
3873 if (OldOvl) {
3874 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3875 const auto *A = D->getAttr<OverloadableAttr>();
3876 return A && !A->isImplicit();
3877 });
3878 // If we've implicitly added *all* of the overloadable attrs to this
3879 // chain, emitting a "previous redecl" note is pointless.
3880 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3881 }
3882
3883 if (DiagOld)
3884 Diag(DiagOld->getLocation(),
3885 diag::note_attribute_overloadable_prev_overload)
3886 << OldOvl;
3887
3888 if (OldOvl)
3889 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3890 else
3891 New->dropAttr<OverloadableAttr>();
3892 }
3893 }
3894
3895 // It is not permitted to redeclare an SME function with different SME
3896 // attributes.
3897 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
3898 Diag(New->getLocation(), diag::err_sme_attr_mismatch)
3899 << New->getType() << Old->getType();
3900 Diag(OldLocation, diag::note_previous_declaration);
3901 return true;
3902 }
3903
3904 // If a function is first declared with a calling convention, but is later
3905 // declared or defined without one, all following decls assume the calling
3906 // convention of the first.
3907 //
3908 // It's OK if a function is first declared without a calling convention,
3909 // but is later declared or defined with the default calling convention.
3910 //
3911 // To test if either decl has an explicit calling convention, we look for
3912 // AttributedType sugar nodes on the type as written. If they are missing or
3913 // were canonicalized away, we assume the calling convention was implicit.
3914 //
3915 // Note also that we DO NOT return at this point, because we still have
3916 // other tests to run.
3917 QualType OldQType = Context.getCanonicalType(Old->getType());
3918 QualType NewQType = Context.getCanonicalType(New->getType());
3919 const FunctionType *OldType = cast<FunctionType>(OldQType);
3920 const FunctionType *NewType = cast<FunctionType>(NewQType);
3921 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3922 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3923 bool RequiresAdjustment = false;
3924
3925 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3927 const FunctionType *FT =
3928 First->getType().getCanonicalType()->castAs<FunctionType>();
3930 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3931 if (!NewCCExplicit) {
3932 // Inherit the CC from the previous declaration if it was specified
3933 // there but not here.
3934 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3935 RequiresAdjustment = true;
3936 } else if (Old->getBuiltinID()) {
3937 // Builtin attribute isn't propagated to the new one yet at this point,
3938 // so we check if the old one is a builtin.
3939
3940 // Calling Conventions on a Builtin aren't really useful and setting a
3941 // default calling convention and cdecl'ing some builtin redeclarations is
3942 // common, so warn and ignore the calling convention on the redeclaration.
3943 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3944 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3946 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3947 RequiresAdjustment = true;
3948 } else {
3949 // Calling conventions aren't compatible, so complain.
3950 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3951 Diag(New->getLocation(), diag::err_cconv_change)
3952 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3953 << !FirstCCExplicit
3954 << (!FirstCCExplicit ? "" :
3956
3957 // Put the note on the first decl, since it is the one that matters.
3958 Diag(First->getLocation(), diag::note_previous_declaration);
3959 return true;
3960 }
3961 }
3962
3963 // FIXME: diagnose the other way around?
3964 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3965 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3966 RequiresAdjustment = true;
3967 }
3968
3969 // If the declaration is marked with cfi_unchecked_callee but the definition
3970 // isn't, the definition is also cfi_unchecked_callee.
3971 if (auto *FPT1 = OldType->getAs<FunctionProtoType>()) {
3972 if (auto *FPT2 = NewType->getAs<FunctionProtoType>()) {
3973 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
3974 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
3975
3976 if (EPI1.CFIUncheckedCallee && !EPI2.CFIUncheckedCallee) {
3977 EPI2.CFIUncheckedCallee = true;
3978 NewQType = Context.getFunctionType(FPT2->getReturnType(),
3979 FPT2->getParamTypes(), EPI2);
3980 NewType = cast<FunctionType>(NewQType);
3981 New->setType(NewQType);
3982 }
3983 }
3984 }
3985
3986 // Merge regparm attribute.
3987 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3988 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3989 if (NewTypeInfo.getHasRegParm()) {
3990 Diag(New->getLocation(), diag::err_regparm_mismatch)
3991 << NewType->getRegParmType()
3992 << OldType->getRegParmType();
3993 Diag(OldLocation, diag::note_previous_declaration);
3994 return true;
3995 }
3996
3997 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3998 RequiresAdjustment = true;
3999 }
4000
4001 // Merge ns_returns_retained attribute.
4002 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
4003 if (NewTypeInfo.getProducesResult()) {
4004 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
4005 << "'ns_returns_retained'";
4006 Diag(OldLocation, diag::note_previous_declaration);
4007 return true;
4008 }
4009
4010 NewTypeInfo = NewTypeInfo.withProducesResult(true);
4011 RequiresAdjustment = true;
4012 }
4013
4014 if (OldTypeInfo.getNoCallerSavedRegs() !=
4015 NewTypeInfo.getNoCallerSavedRegs()) {
4016 if (NewTypeInfo.getNoCallerSavedRegs()) {
4017 AnyX86NoCallerSavedRegistersAttr *Attr =
4018 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
4019 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
4020 Diag(OldLocation, diag::note_previous_declaration);
4021 return true;
4022 }
4023
4024 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
4025 RequiresAdjustment = true;
4026 }
4027
4028 if (RequiresAdjustment) {
4029 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
4030 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
4031 New->setType(QualType(AdjustedType, 0));
4032 NewQType = Context.getCanonicalType(New->getType());
4033 }
4034
4035 // If this redeclaration makes the function inline, we may need to add it to
4036 // UndefinedButUsed.
4037 if (!Old->isInlined() && New->isInlined() && !New->hasAttr<GNUInlineAttr>() &&
4038 !getLangOpts().GNUInline && Old->isUsed(false) && !Old->isDefined() &&
4039 !New->isThisDeclarationADefinition() && !Old->isInAnotherModuleUnit())
4040 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4041 SourceLocation()));
4042
4043 // If this redeclaration makes it newly gnu_inline, we don't want to warn
4044 // about it.
4045 if (New->hasAttr<GNUInlineAttr>() &&
4046 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
4047 UndefinedButUsed.erase(Old->getCanonicalDecl());
4048 }
4049
4050 // If pass_object_size params don't match up perfectly, this isn't a valid
4051 // redeclaration.
4052 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
4054 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
4055 << New->getDeclName();
4056 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4057 return true;
4058 }
4059
4060 QualType OldQTypeForComparison = OldQType;
4061 if (Context.hasAnyFunctionEffects()) {
4062 const auto OldFX = Old->getFunctionEffects();
4063 const auto NewFX = New->getFunctionEffects();
4064 if (OldFX != NewFX) {
4065 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
4066 for (const auto &Diff : Diffs) {
4067 if (Diff.shouldDiagnoseRedeclaration(*Old, OldFX, *New, NewFX)) {
4068 Diag(New->getLocation(),
4069 diag::warn_mismatched_func_effect_redeclaration)
4070 << Diff.effectName();
4071 Diag(Old->getLocation(), diag::note_previous_declaration);
4072 }
4073 }
4074 // Following a warning, we could skip merging effects from the previous
4075 // declaration, but that would trigger an additional "conflicting types"
4076 // error.
4077 if (const auto *NewFPT = NewQType->getAs<FunctionProtoType>()) {
4079 FunctionEffectSet MergedFX =
4080 FunctionEffectSet::getUnion(OldFX, NewFX, MergeErrs);
4081 if (!MergeErrs.empty())
4082 diagnoseFunctionEffectMergeConflicts(MergeErrs, New->getLocation(),
4083 Old->getLocation());
4084
4085 FunctionProtoType::ExtProtoInfo EPI = NewFPT->getExtProtoInfo();
4086 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4087 QualType ModQT = Context.getFunctionType(NewFPT->getReturnType(),
4088 NewFPT->getParamTypes(), EPI);
4089
4090 New->setType(ModQT);
4091 NewQType = New->getType();
4092
4093 // Revise OldQTForComparison to include the merged effects,
4094 // so as not to fail due to differences later.
4095 if (const auto *OldFPT = OldQType->getAs<FunctionProtoType>()) {
4096 EPI = OldFPT->getExtProtoInfo();
4097 EPI.FunctionEffects = FunctionEffectsRef(MergedFX);
4098 OldQTypeForComparison = Context.getFunctionType(
4099 OldFPT->getReturnType(), OldFPT->getParamTypes(), EPI);
4100 }
4101 if (OldFX.empty()) {
4102 // A redeclaration may add the attribute to a previously seen function
4103 // body which needs to be verified.
4104 maybeAddDeclWithEffects(Old, MergedFX);
4105 }
4106 }
4107 }
4108 }
4109
4110 if (getLangOpts().CPlusPlus) {
4111 OldQType = Context.getCanonicalType(Old->getType());
4112 NewQType = Context.getCanonicalType(New->getType());
4113
4114 // Go back to the type source info to compare the declared return types,
4115 // per C++1y [dcl.type.auto]p13:
4116 // Redeclarations or specializations of a function or function template
4117 // with a declared return type that uses a placeholder type shall also
4118 // use that placeholder, not a deduced type.
4119 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
4120 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
4121 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
4122 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
4123 OldDeclaredReturnType)) {
4124 QualType ResQT;
4125 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
4126 OldDeclaredReturnType->isObjCObjectPointerType())
4127 // FIXME: This does the wrong thing for a deduced return type.
4128 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
4129 if (ResQT.isNull()) {
4130 if (New->isCXXClassMember() && New->isOutOfLine())
4131 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
4132 << New << New->getReturnTypeSourceRange();
4133 else if (Old->isExternC() && New->isExternC() &&
4134 !Old->hasAttr<OverloadableAttr>() &&
4135 !New->hasAttr<OverloadableAttr>())
4136 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4137 else
4138 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
4139 << New->getReturnTypeSourceRange();
4140 Diag(OldLocation, PrevDiag) << Old << Old->getType()
4141 << Old->getReturnTypeSourceRange();
4142 return true;
4143 }
4144 else
4145 NewQType = ResQT;
4146 }
4147
4148 QualType OldReturnType = OldType->getReturnType();
4149 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
4150 if (OldReturnType != NewReturnType) {
4151 // If this function has a deduced return type and has already been
4152 // defined, copy the deduced value from the old declaration.
4153 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
4154 if (OldAT && OldAT->isDeduced()) {
4155 QualType DT = OldAT->getDeducedType();
4156 if (DT.isNull()) {
4157 New->setType(SubstAutoTypeDependent(New->getType()));
4158 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
4159 } else {
4160 New->setType(SubstAutoType(New->getType(), DT));
4161 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
4162 }
4163 }
4164 }
4165
4166 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
4167 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
4168 if (OldMethod && NewMethod) {
4169 // Preserve triviality.
4170 NewMethod->setTrivial(OldMethod->isTrivial());
4171
4172 // MSVC allows explicit template specialization at class scope:
4173 // 2 CXXMethodDecls referring to the same function will be injected.
4174 // We don't want a redeclaration error.
4175 bool IsClassScopeExplicitSpecialization =
4176 OldMethod->isFunctionTemplateSpecialization() &&
4178 bool isFriend = NewMethod->getFriendObjectKind();
4179
4180 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
4181 !IsClassScopeExplicitSpecialization) {
4182 // -- Member function declarations with the same name and the
4183 // same parameter types cannot be overloaded if any of them
4184 // is a static member function declaration.
4185 if (OldMethod->isStatic() != NewMethod->isStatic()) {
4186 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
4187 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4188 return true;
4189 }
4190
4191 // C++ [class.mem]p1:
4192 // [...] A member shall not be declared twice in the
4193 // member-specification, except that a nested class or member
4194 // class template can be declared and then later defined.
4195 if (!inTemplateInstantiation()) {
4196 unsigned NewDiag;
4197 if (isa<CXXConstructorDecl>(OldMethod))
4198 NewDiag = diag::err_constructor_redeclared;
4199 else if (isa<CXXDestructorDecl>(NewMethod))
4200 NewDiag = diag::err_destructor_redeclared;
4201 else if (isa<CXXConversionDecl>(NewMethod))
4202 NewDiag = diag::err_conv_function_redeclared;
4203 else
4204 NewDiag = diag::err_member_redeclared;
4205
4206 Diag(New->getLocation(), NewDiag);
4207 } else {
4208 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
4209 << New << New->getType();
4210 }
4211 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4212 return true;
4213
4214 // Complain if this is an explicit declaration of a special
4215 // member that was initially declared implicitly.
4216 //
4217 // As an exception, it's okay to befriend such methods in order
4218 // to permit the implicit constructor/destructor/operator calls.
4219 } else if (OldMethod->isImplicit()) {
4220 if (isFriend) {
4221 NewMethod->setImplicit();
4222 } else {
4223 Diag(NewMethod->getLocation(),
4224 diag::err_definition_of_implicitly_declared_member)
4225 << New << OldMethod->getSpecialMemberKind();
4226 return true;
4227 }
4228 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
4229 Diag(NewMethod->getLocation(),
4230 diag::err_definition_of_explicitly_defaulted_member)
4231 << OldMethod->getSpecialMemberKind();
4232 return true;
4233 }
4234 }
4235
4236 // C++1z [over.load]p2
4237 // Certain function declarations cannot be overloaded:
4238 // -- Function declarations that differ only in the return type,
4239 // the exception specification, or both cannot be overloaded.
4240
4241 // Check the exception specifications match. This may recompute the type of
4242 // both Old and New if it resolved exception specifications, so grab the
4243 // types again after this. Because this updates the type, we do this before
4244 // any of the other checks below, which may update the "de facto" NewQType
4245 // but do not necessarily update the type of New.
4247 return true;
4248
4249 // C++11 [dcl.attr.noreturn]p1:
4250 // The first declaration of a function shall specify the noreturn
4251 // attribute if any declaration of that function specifies the noreturn
4252 // attribute.
4253 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
4254 if (!Old->hasAttr<CXX11NoReturnAttr>()) {
4255 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
4256 << NRA;
4257 Diag(Old->getLocation(), diag::note_previous_declaration);
4258 }
4259
4260 // SYCL 2020 section 5.10.1, "SYCL functions and member functions linkage":
4261 // When a function is declared with SYCL_EXTERNAL, that macro must be
4262 // used on the first declaration of that function in the translation unit.
4263 // Redeclarations of the function in the same translation unit may
4264 // optionally use SYCL_EXTERNAL, but this is not required.
4265 const SYCLExternalAttr *SEA = New->getAttr<SYCLExternalAttr>();
4266 if (SEA && !Old->hasAttr<SYCLExternalAttr>()) {
4267 Diag(SEA->getLocation(), diag::warn_sycl_external_missing_on_first_decl)
4268 << SEA;
4269 Diag(Old->getLocation(), diag::note_previous_declaration);
4270 }
4271
4272 // (C++98 8.3.5p3):
4273 // All declarations for a function shall agree exactly in both the
4274 // return type and the parameter-type-list.
4275 // We also want to respect all the extended bits except noreturn.
4276
4277 // noreturn should now match unless the old type info didn't have it.
4278 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
4279 auto *OldType = OldQTypeForComparison->castAs<FunctionProtoType>();
4280 const FunctionType *OldTypeForComparison
4281 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
4282 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
4283 assert(OldQTypeForComparison.isCanonical());
4284 }
4285
4287 // As a special case, retain the language linkage from previous
4288 // declarations of a friend function as an extension.
4289 //
4290 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
4291 // and is useful because there's otherwise no way to specify language
4292 // linkage within class scope.
4293 //
4294 // Check cautiously as the friend object kind isn't yet complete.
4295 if (New->getFriendObjectKind() != Decl::FOK_None) {
4296 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
4297 Diag(OldLocation, PrevDiag);
4298 } else {
4299 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4300 Diag(OldLocation, PrevDiag);
4301 return true;
4302 }
4303 }
4304
4305 // HLSL check parameters for matching ABI specifications.
4306 if (getLangOpts().HLSL) {
4307 if (HLSL().CheckCompatibleParameterABI(New, Old))
4308 return true;
4309
4310 // If no errors are generated when checking parameter ABIs we can check if
4311 // the two declarations have the same type ignoring the ABIs and if so,
4312 // the declarations can be merged. This case for merging is only valid in
4313 // HLSL because there are no valid cases of merging mismatched parameter
4314 // ABIs except the HLSL implicit in and explicit in.
4315 if (Context.hasSameFunctionTypeIgnoringParamABI(OldQTypeForComparison,
4316 NewQType))
4317 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4318 // Fall through for conflicting redeclarations and redefinitions.
4319 }
4320
4321 // If the function types are compatible, merge the declarations. Ignore the
4322 // exception specifier because it was already checked above in
4323 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
4324 // about incompatible types under -fms-compatibility.
4325 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
4326 NewQType))
4327 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4328
4329 // If the types are imprecise (due to dependent constructs in friends or
4330 // local extern declarations), it's OK if they differ. We'll check again
4331 // during instantiation.
4332 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
4333 return false;
4334
4335 // Fall through for conflicting redeclarations and redefinitions.
4336 }
4337
4338 // C: Function types need to be compatible, not identical. This handles
4339 // duplicate function decls like "void f(int); void f(enum X);" properly.
4340 if (!getLangOpts().CPlusPlus) {
4341 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
4342 // type is specified by a function definition that contains a (possibly
4343 // empty) identifier list, both shall agree in the number of parameters
4344 // and the type of each parameter shall be compatible with the type that
4345 // results from the application of default argument promotions to the
4346 // type of the corresponding identifier. ...
4347 // This cannot be handled by ASTContext::typesAreCompatible() because that
4348 // doesn't know whether the function type is for a definition or not when
4349 // eventually calling ASTContext::mergeFunctionTypes(). The only situation
4350 // we need to cover here is that the number of arguments agree as the
4351 // default argument promotion rules were already checked by
4352 // ASTContext::typesAreCompatible().
4353 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
4354 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
4355 if (Old->hasInheritedPrototype())
4356 Old = Old->getCanonicalDecl();
4357 Diag(New->getLocation(), diag::err_conflicting_types) << New;
4358 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
4359 return true;
4360 }
4361
4362 // If we are merging two functions where only one of them has a prototype,
4363 // we may have enough information to decide to issue a diagnostic that the
4364 // function without a prototype will change behavior in C23. This handles
4365 // cases like:
4366 // void i(); void i(int j);
4367 // void i(int j); void i();
4368 // void i(); void i(int j) {}
4369 // See ActOnFinishFunctionBody() for other cases of the behavior change
4370 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
4371 // type without a prototype.
4372 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
4373 !New->isImplicit() && !Old->isImplicit()) {
4374 const FunctionDecl *WithProto, *WithoutProto;
4375 if (New->hasWrittenPrototype()) {
4376 WithProto = New;
4377 WithoutProto = Old;
4378 } else {
4379 WithProto = Old;
4380 WithoutProto = New;
4381 }
4382
4383 if (WithProto->getNumParams() != 0) {
4384 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
4385 // The one without the prototype will be changing behavior in C23, so
4386 // warn about that one so long as it's a user-visible declaration.
4387 bool IsWithoutProtoADef = false, IsWithProtoADef = false;
4388 if (WithoutProto == New)
4389 IsWithoutProtoADef = NewDeclIsDefn;
4390 else
4391 IsWithProtoADef = NewDeclIsDefn;
4392 Diag(WithoutProto->getLocation(),
4393 diag::warn_non_prototype_changes_behavior)
4394 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
4395 << (WithoutProto == Old) << IsWithProtoADef;
4396
4397 // The reason the one without the prototype will be changing behavior
4398 // is because of the one with the prototype, so note that so long as
4399 // it's a user-visible declaration. There is one exception to this:
4400 // when the new declaration is a definition without a prototype, the
4401 // old declaration with a prototype is not the cause of the issue,
4402 // and that does not need to be noted because the one with a
4403 // prototype will not change behavior in C23.
4404 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
4405 !IsWithoutProtoADef)
4406 Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
4407 }
4408 }
4409 }
4410
4411 if (Context.typesAreCompatible(OldQType, NewQType)) {
4412 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
4413 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
4414 const FunctionProtoType *OldProto = nullptr;
4415 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
4416 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
4417 // The old declaration provided a function prototype, but the
4418 // new declaration does not. Merge in the prototype.
4419 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
4420 NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
4421 OldProto->getParamTypes(),
4422 OldProto->getExtProtoInfo());
4423 New->setType(NewQType);
4424 New->setHasInheritedPrototype();
4425
4426 // Synthesize parameters with the same types.
4428 for (const auto &ParamType : OldProto->param_types()) {
4430 Context, New, SourceLocation(), SourceLocation(), nullptr,
4431 ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
4432 Param->setScopeInfo(0, Params.size());
4433 Param->setImplicit();
4434 Params.push_back(Param);
4435 }
4436
4437 New->setParams(Params);
4438 }
4439
4440 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4441 }
4442 }
4443
4444 // Check if the function types are compatible when pointer size address
4445 // spaces are ignored.
4446 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
4447 return false;
4448
4449 // GNU C permits a K&R definition to follow a prototype declaration
4450 // if the declared types of the parameters in the K&R definition
4451 // match the types in the prototype declaration, even when the
4452 // promoted types of the parameters from the K&R definition differ
4453 // from the types in the prototype. GCC then keeps the types from
4454 // the prototype.
4455 //
4456 // If a variadic prototype is followed by a non-variadic K&R definition,
4457 // the K&R definition becomes variadic. This is sort of an edge case, but
4458 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
4459 // C99 6.9.1p8.
4460 if (!getLangOpts().CPlusPlus &&
4461 Old->hasPrototype() && !New->hasPrototype() &&
4462 New->getType()->getAs<FunctionProtoType>() &&
4463 Old->getNumParams() == New->getNumParams()) {
4466 const FunctionProtoType *OldProto
4467 = Old->getType()->getAs<FunctionProtoType>();
4468 const FunctionProtoType *NewProto
4469 = New->getType()->getAs<FunctionProtoType>();
4470
4471 // Determine whether this is the GNU C extension.
4472 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
4473 NewProto->getReturnType());
4474 bool LooseCompatible = !MergedReturn.isNull();
4475 for (unsigned Idx = 0, End = Old->getNumParams();
4476 LooseCompatible && Idx != End; ++Idx) {
4477 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
4478 ParmVarDecl *NewParm = New->getParamDecl(Idx);
4479 if (Context.typesAreCompatible(OldParm->getType(),
4480 NewProto->getParamType(Idx))) {
4481 ArgTypes.push_back(NewParm->getType());
4482 } else if (Context.typesAreCompatible(OldParm->getType(),
4483 NewParm->getType(),
4484 /*CompareUnqualified=*/true)) {
4485 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
4486 NewProto->getParamType(Idx) };
4487 Warnings.push_back(Warn);
4488 ArgTypes.push_back(NewParm->getType());
4489 } else
4490 LooseCompatible = false;
4491 }
4492
4493 if (LooseCompatible) {
4494 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
4495 Diag(Warnings[Warn].NewParm->getLocation(),
4496 diag::ext_param_promoted_not_compatible_with_prototype)
4497 << Warnings[Warn].PromotedType
4498 << Warnings[Warn].OldParm->getType();
4499 if (Warnings[Warn].OldParm->getLocation().isValid())
4500 Diag(Warnings[Warn].OldParm->getLocation(),
4501 diag::note_previous_declaration);
4502 }
4503
4504 if (MergeTypeWithOld)
4505 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4506 OldProto->getExtProtoInfo()));
4507 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4508 }
4509
4510 // Fall through to diagnose conflicting types.
4511 }
4512
4513 // A function that has already been declared has been redeclared or
4514 // defined with a different type; show an appropriate diagnostic.
4515
4516 // If the previous declaration was an implicitly-generated builtin
4517 // declaration, then at the very least we should use a specialized note.
4518 unsigned BuiltinID;
4519 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4520 // If it's actually a library-defined builtin function like 'malloc'
4521 // or 'printf', just warn about the incompatible redeclaration.
4522 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4523 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4524 Diag(OldLocation, diag::note_previous_builtin_declaration)
4525 << Old << Old->getType();
4526 return false;
4527 }
4528
4529 PrevDiag = diag::note_previous_builtin_declaration;
4530 }
4531
4532 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4533 Diag(OldLocation, PrevDiag) << Old << Old->getType();
4534 return true;
4535}
4536
4538 Scope *S, bool MergeTypeWithOld) {
4539 // Merge the attributes
4541
4542 // Merge "pure" flag.
4543 if (Old->isPureVirtual())
4544 New->setIsPureVirtual();
4545
4546 // Merge "used" flag.
4547 if (Old->getMostRecentDecl()->isUsed(false))
4548 New->setIsUsed();
4549
4550 // Merge attributes from the parameters. These can mismatch with K&R
4551 // declarations.
4552 if (New->getNumParams() == Old->getNumParams())
4553 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4554 ParmVarDecl *NewParam = New->getParamDecl(i);
4555 ParmVarDecl *OldParam = Old->getParamDecl(i);
4556 mergeParamDeclAttributes(NewParam, OldParam, *this);
4557 mergeParamDeclTypes(NewParam, OldParam, *this);
4558 }
4559
4560 if (getLangOpts().CPlusPlus)
4561 return MergeCXXFunctionDecl(New, Old, S);
4562
4563 // Merge the function types so the we get the composite types for the return
4564 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4565 // was visible.
4566 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4567 if (!Merged.isNull() && MergeTypeWithOld)
4568 New->setType(Merged);
4569
4570 return false;
4571}
4572
4574 ObjCMethodDecl *oldMethod) {
4575 // Merge the attributes, including deprecated/unavailable
4576 AvailabilityMergeKind MergeKind =
4578 ? (oldMethod->isOptional()
4581 : isa<ObjCImplDecl>(newMethod->getDeclContext())
4584
4585 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4586
4587 // Merge attributes from the parameters.
4589 oe = oldMethod->param_end();
4591 ni = newMethod->param_begin(), ne = newMethod->param_end();
4592 ni != ne && oi != oe; ++ni, ++oi)
4593 mergeParamDeclAttributes(*ni, *oi, *this);
4594
4595 ObjC().CheckObjCMethodOverride(newMethod, oldMethod);
4596}
4597
4599 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4600
4601 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
4602 ? diag::err_redefinition_different_type
4603 : diag::err_redeclaration_different_type)
4604 << New->getDeclName() << New->getType() << Old->getType();
4605
4606 diag::kind PrevDiag;
4607 SourceLocation OldLocation;
4608 std::tie(PrevDiag, OldLocation)
4610 S.Diag(OldLocation, PrevDiag) << Old << Old->getType();
4611 New->setInvalidDecl();
4612}
4613
4615 bool MergeTypeWithOld) {
4616 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors())
4617 return;
4618
4619 QualType MergedT;
4620 if (getLangOpts().CPlusPlus) {
4621 if (New->getType()->isUndeducedType()) {
4622 // We don't know what the new type is until the initializer is attached.
4623 return;
4624 } else if (Context.hasSameType(New->getType(), Old->getType())) {
4625 // These could still be something that needs exception specs checked.
4626 return MergeVarDeclExceptionSpecs(New, Old);
4627 }
4628 // C++ [basic.link]p10:
4629 // [...] the types specified by all declarations referring to a given
4630 // object or function shall be identical, except that declarations for an
4631 // array object can specify array types that differ by the presence or
4632 // absence of a major array bound (8.3.4).
4633 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4634 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4635 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4636
4637 // We are merging a variable declaration New into Old. If it has an array
4638 // bound, and that bound differs from Old's bound, we should diagnose the
4639 // mismatch.
4640 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4641 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4642 PrevVD = PrevVD->getPreviousDecl()) {
4643 QualType PrevVDTy = PrevVD->getType();
4644 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4645 continue;
4646
4647 if (!Context.hasSameType(New->getType(), PrevVDTy))
4648 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4649 }
4650 }
4651
4652 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4653 if (Context.hasSameType(OldArray->getElementType(),
4654 NewArray->getElementType()))
4655 MergedT = New->getType();
4656 }
4657 // FIXME: Check visibility. New is hidden but has a complete type. If New
4658 // has no array bound, it should not inherit one from Old, if Old is not
4659 // visible.
4660 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4661 if (Context.hasSameType(OldArray->getElementType(),
4662 NewArray->getElementType()))
4663 MergedT = Old->getType();
4664 }
4665 }
4666 else if (New->getType()->isObjCObjectPointerType() &&
4667 Old->getType()->isObjCObjectPointerType()) {
4668 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4669 Old->getType());
4670 }
4671 } else {
4672 // C 6.2.7p2:
4673 // All declarations that refer to the same object or function shall have
4674 // compatible type.
4675 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4676 }
4677 if (MergedT.isNull()) {
4678 // It's OK if we couldn't merge types if either type is dependent, for a
4679 // block-scope variable. In other cases (static data members of class
4680 // templates, variable templates, ...), we require the types to be
4681 // equivalent.
4682 // FIXME: The C++ standard doesn't say anything about this.
4683 if ((New->getType()->isDependentType() ||
4684 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4685 // If the old type was dependent, we can't merge with it, so the new type
4686 // becomes dependent for now. We'll reproduce the original type when we
4687 // instantiate the TypeSourceInfo for the variable.
4688 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4689 New->setType(Context.DependentTy);
4690 return;
4691 }
4692 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4693 }
4694
4695 // Don't actually update the type on the new declaration if the old
4696 // declaration was an extern declaration in a different scope.
4697 if (MergeTypeWithOld)
4698 New->setType(MergedT);
4699}
4700
4701static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4703 // C11 6.2.7p4:
4704 // For an identifier with internal or external linkage declared
4705 // in a scope in which a prior declaration of that identifier is
4706 // visible, if the prior declaration specifies internal or
4707 // external linkage, the type of the identifier at the later
4708 // declaration becomes the composite type.
4709 //
4710 // If the variable isn't visible, we do not merge with its type.
4711 if (Previous.isShadowed())
4712 return false;
4713
4714 if (S.getLangOpts().CPlusPlus) {
4715 // C++11 [dcl.array]p3:
4716 // If there is a preceding declaration of the entity in the same
4717 // scope in which the bound was specified, an omitted array bound
4718 // is taken to be the same as in that earlier declaration.
4719 return NewVD->isPreviousDeclInSameBlockScope() ||
4720 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4722 } else {
4723 // If the old declaration was function-local, don't merge with its
4724 // type unless we're in the same function.
4725 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4726 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4727 }
4728}
4729
4731 // If the new decl is already invalid, don't do any other checking.
4732 if (New->isInvalidDecl())
4733 return;
4734
4735 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4736 return;
4737
4738 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4739
4740 // Verify the old decl was also a variable or variable template.
4741 VarDecl *Old = nullptr;
4742 VarTemplateDecl *OldTemplate = nullptr;
4743 if (Previous.isSingleResult()) {
4744 if (NewTemplate) {
4745 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4746 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4747
4748 if (auto *Shadow =
4749 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4750 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4751 return New->setInvalidDecl();
4752 } else {
4753 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4754
4755 if (auto *Shadow =
4756 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4757 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4758 return New->setInvalidDecl();
4759 }
4760 }
4761 if (!Old) {
4762 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4763 << New->getDeclName();
4764 notePreviousDefinition(Previous.getRepresentativeDecl(),
4765 New->getLocation());
4766 return New->setInvalidDecl();
4767 }
4768
4769 // If the old declaration was found in an inline namespace and the new
4770 // declaration was qualified, update the DeclContext to match.
4772
4773 // Ensure the template parameters are compatible.
4774 if (NewTemplate &&
4776 OldTemplate->getTemplateParameters(),
4777 /*Complain=*/true, TPL_TemplateMatch))
4778 return New->setInvalidDecl();
4779
4780 // C++ [class.mem]p1:
4781 // A member shall not be declared twice in the member-specification [...]
4782 //
4783 // Here, we need only consider static data members.
4784 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4785 Diag(New->getLocation(), diag::err_duplicate_member)
4786 << New->getIdentifier();
4787 Diag(Old->getLocation(), diag::note_previous_declaration);
4788 New->setInvalidDecl();
4789 }
4790
4791 if (NewTemplate && OldTemplate)
4792 mergeDeclAttributes(NewTemplate, OldTemplate);
4793
4795
4796 // Warn if an already-defined variable is made a weak_import in a subsequent
4797 // declaration
4798 if (New->hasAttr<WeakImportAttr>())
4799 for (auto *D = Old; D; D = D->getPreviousDecl()) {
4800 if (D->isThisDeclarationADefinition() != VarDecl::DeclarationOnly) {
4801 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4802 Diag(D->getLocation(), diag::note_previous_definition);
4803 // Remove weak_import attribute on new declaration.
4804 New->dropAttr<WeakImportAttr>();
4805 break;
4806 }
4807 }
4808
4809 if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4810 if (!Old->hasAttr<InternalLinkageAttr>()) {
4811 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4812 << ILA;
4813 Diag(Old->getLocation(), diag::note_previous_declaration);
4814 New->dropAttr<InternalLinkageAttr>();
4815 }
4816
4817 // Merge the types.
4818 VarDecl *MostRecent = Old->getMostRecentDecl();
4819 if (MostRecent != Old) {
4820 MergeVarDeclTypes(New, MostRecent,
4821 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4822 if (New->isInvalidDecl())
4823 return;
4824 }
4825
4827 if (New->isInvalidDecl())
4828 return;
4829
4830 diag::kind PrevDiag;
4831 SourceLocation OldLocation;
4832 std::tie(PrevDiag, OldLocation) =
4834
4835 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4836 if (New->getStorageClass() == SC_Static &&
4837 !New->isStaticDataMember() &&
4838 Old->hasExternalFormalLinkage()) {
4839 if (getLangOpts().MicrosoftExt) {
4840 Diag(New->getLocation(), diag::ext_static_non_static)
4841 << New->getDeclName();
4842 Diag(OldLocation, PrevDiag);
4843 } else {
4844 // This is the same internal/external linkage conflict as C2y 6.7.1p7;
4845 // before C2y it was undefined behavior (C11 6.2.2p7), so note that in
4846 // the older C language modes.
4847 Diag(New->getLocation(), diag::err_static_non_static)
4848 << New->getDeclName()
4849 << (!getLangOpts().CPlusPlus && !getLangOpts().C2y);
4850 Diag(OldLocation, PrevDiag);
4851 return New->setInvalidDecl();
4852 }
4853 }
4854
4855 // C2y 6.7.1p7: an identifier shall not appear with both internal and
4856 // external linkage within a translation unit. Before C2y this was UB
4857 // (C11 6.2.2p7).
4858 //
4859 // In C, a local shadow prevents a block-scope extern from inheriting the
4860 // file-scope static's internal linkage (C2y 6.2.2p6), so it defaults to
4861 // external linkage, creating the conflict.
4862 //
4863 // In C++, block-scope extern declarations target the enclosing namespace
4864 // scope ([dcl.meaning.general]/3.5), bypassing local shadows entirely, so
4865 // the extern always inherits internal linkage. No conflict arises.
4866 if (!getLangOpts().CPlusPlus && New->isLocalVarDecl() &&
4867 New->hasExternalStorage() && Previous.isShadowed() &&
4869 Diag(New->getLocation(), diag::err_internal_extern_mismatch)
4870 << New->getDeclName() << getLangOpts().C2y;
4871 Diag(OldLocation, diag::note_previous_declaration);
4872 return New->setInvalidDecl();
4873 }
4874
4875 // C99 6.2.2p4:
4876 // For an identifier declared with the storage-class specifier
4877 // extern in a scope in which a prior declaration of that
4878 // identifier is visible,23) if the prior declaration specifies
4879 // internal or external linkage, the linkage of the identifier at
4880 // the later declaration is the same as the linkage specified at
4881 // the prior declaration. If no prior declaration is visible, or
4882 // if the prior declaration specifies no linkage, then the
4883 // identifier has external linkage.
4884 if (New->hasExternalStorage() && Old->hasLinkage())
4885 /* Okay */;
4886 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4887 !New->isStaticDataMember() &&
4889 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4890 Diag(OldLocation, PrevDiag);
4891 return New->setInvalidDecl();
4892 }
4893
4894 // Check if extern is followed by non-extern and vice-versa.
4895 if (New->hasExternalStorage() &&
4896 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4897 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4898 Diag(OldLocation, PrevDiag);
4899 return New->setInvalidDecl();
4900 }
4901 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4902 !New->hasExternalStorage()) {
4903 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4904 Diag(OldLocation, PrevDiag);
4905 return New->setInvalidDecl();
4906 }
4907
4909 return;
4910
4911 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4912
4913 // FIXME: The test for external storage here seems wrong? We still
4914 // need to check for mismatches.
4915 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4916 // Don't complain about out-of-line definitions of static members.
4917 !(Old->getLexicalDeclContext()->isRecord() &&
4918 !New->getLexicalDeclContext()->isRecord())) {
4919 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4920 Diag(OldLocation, PrevDiag);
4921 return New->setInvalidDecl();
4922 }
4923
4924 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4925 if (VarDecl *Def = Old->getDefinition()) {
4926 // C++1z [dcl.fcn.spec]p4:
4927 // If the definition of a variable appears in a translation unit before
4928 // its first declaration as inline, the program is ill-formed.
4929 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4930 Diag(Def->getLocation(), diag::note_previous_definition);
4931 }
4932 }
4933
4934 // If this redeclaration makes the variable inline, we may need to add it to
4935 // UndefinedButUsed.
4936 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4937 !Old->getDefinition() && !New->isThisDeclarationADefinition() &&
4938 !Old->isInAnotherModuleUnit())
4939 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4940 SourceLocation()));
4941
4942 if (New->getTLSKind() != Old->getTLSKind()) {
4943 if (!Old->getTLSKind()) {
4944 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4945 Diag(OldLocation, PrevDiag);
4946 } else if (!New->getTLSKind()) {
4947 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4948 Diag(OldLocation, PrevDiag);
4949 } else {
4950 // Do not allow redeclaration to change the variable between requiring
4951 // static and dynamic initialization.
4952 // FIXME: GCC allows this, but uses the TLS keyword on the first
4953 // declaration to determine the kind. Do we need to be compatible here?
4954 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4955 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4956 Diag(OldLocation, PrevDiag);
4957 }
4958 }
4959
4960 // C++ doesn't have tentative definitions, so go right ahead and check here.
4961 if (getLangOpts().CPlusPlus) {
4962 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4963 Old->getCanonicalDecl()->isConstexpr()) {
4964 // This definition won't be a definition any more once it's been merged.
4965 Diag(New->getLocation(),
4966 diag::warn_deprecated_redundant_constexpr_static_def);
4967 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
4968 VarDecl *Def = Old->getDefinition();
4969 if (Def && checkVarDeclRedefinition(Def, New))
4970 return;
4971 if (Old->isInvalidDecl())
4972 New->setInvalidDecl();
4973 }
4974 } else {
4975 // C++ may not have a tentative definition rule, but it has a different
4976 // rule about what constitutes a definition in the first place. See
4977 // [basic.def]p2 for details, but the basic idea is: if the old declaration
4978 // contains the extern specifier and doesn't have an initializer, it's fine
4979 // in C++.
4980 if (Old->getStorageClass() != SC_Extern || Old->hasInit()) {
4981 Diag(New->getLocation(), diag::warn_cxx_compat_tentative_definition)
4982 << New;
4983 Diag(Old->getLocation(), diag::note_previous_declaration);
4984 }
4985 }
4986
4988 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4989 Diag(OldLocation, PrevDiag);
4990 New->setInvalidDecl();
4991 return;
4992 }
4993
4994 // Merge "used" flag.
4995 if (Old->getMostRecentDecl()->isUsed(false))
4996 New->setIsUsed();
4997
4998 // Keep a chain of previous declarations.
4999 New->setPreviousDecl(Old);
5000 if (NewTemplate)
5001 NewTemplate->setPreviousDecl(OldTemplate);
5002
5003 // Inherit access appropriately.
5004 New->setAccess(Old->getAccess());
5005 if (NewTemplate)
5006 NewTemplate->setAccess(New->getAccess());
5007
5008 if (Old->isInline())
5009 New->setImplicitlyInline();
5010}
5011
5014 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
5015 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
5016 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
5017 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first);
5018 auto &HSI = PP.getHeaderSearchInfo();
5019 StringRef HdrFilename =
5020 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
5021
5022 auto noteFromModuleOrInclude = [&](Module *Mod,
5023 SourceLocation IncLoc) -> bool {
5024 // Redefinition errors with modules are common with non modular mapped
5025 // headers, example: a non-modular header H in module A that also gets
5026 // included directly in a TU. Pointing twice to the same header/definition
5027 // is confusing, try to get better diagnostics when modules is on.
5028 if (IncLoc.isValid()) {
5029 if (Mod) {
5030 Diag(IncLoc, diag::note_redefinition_modules_same_file)
5031 << HdrFilename.str() << Mod->getFullModuleName();
5032 if (!Mod->DefinitionLoc.isInvalid())
5033 Diag(Mod->DefinitionLoc, diag::note_defined_here)
5034 << Mod->getFullModuleName();
5035 } else {
5036 Diag(IncLoc, diag::note_redefinition_include_same_file)
5037 << HdrFilename.str();
5038 }
5039 return true;
5040 }
5041
5042 return false;
5043 };
5044
5045 // Is it the same file and same offset? Provide more information on why
5046 // this leads to a redefinition error.
5047 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
5048 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
5049 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
5050 bool EmittedDiag =
5051 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
5052 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
5053
5054 // If the header has no guards, emit a note suggesting one.
5055 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld))
5056 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
5057
5058 if (EmittedDiag)
5059 return;
5060 }
5061
5062 // Redefinition coming from different files or couldn't do better above.
5063 if (Old->getLocation().isValid())
5064 Diag(Old->getLocation(), diag::note_previous_definition);
5065}
5066
5068 if ((!hasVisibleDefinition(Old) ||
5069 isFromSameSingleIncludeHeader(Old, New->getLocation())) &&
5070 (New->getFormalLinkage() == Linkage::Internal || New->isInline() ||
5072 New->getDescribedVarTemplate() ||
5073 !New->getTemplateParameterLists().empty() ||
5074 New->getDeclContext()->isDependentContext() ||
5075 New->hasAttr<SelectAnyAttr>())) {
5076 // The previous definition is hidden, and multiple definitions are
5077 // permitted (in separate TUs). Demote this to a declaration.
5078 New->demoteThisDefinitionToDeclaration();
5079
5080 // Make the canonical definition visible.
5081 if (auto *OldTD = Old->getDescribedVarTemplate())
5084 return false;
5085 } else {
5086 Diag(New->getLocation(), diag::err_redefinition) << New;
5087 notePreviousDefinition(Old, New->getLocation());
5088 New->setInvalidDecl();
5089 return true;
5090 }
5091}
5092
5094 DeclSpec &DS,
5095 const ParsedAttributesView &DeclAttrs,
5096 RecordDecl *&AnonRecord) {
5098 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
5099}
5100
5101// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
5102// disambiguate entities defined in different scopes.
5103// While the VS2015 ABI fixes potential miscompiles, it is also breaks
5104// compatibility.
5105// We will pick our mangling number depending on which version of MSVC is being
5106// targeted.
5107static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
5111}
5112
5113void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
5114 if (!Context.getLangOpts().CPlusPlus)
5115 return;
5116
5117 if (isa<CXXRecordDecl>(Tag->getParent())) {
5118 // If this tag is the direct child of a class, number it if
5119 // it is anonymous.
5120 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
5121 return;
5123 Context.getManglingNumberContext(Tag->getParent());
5124 Context.setManglingNumber(
5125 Tag, MCtx.getManglingNumber(
5126 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5127 return;
5128 }
5129
5130 // If this tag isn't a direct child of a class, number it if it is local.
5132 Decl *ManglingContextDecl;
5133 std::tie(MCtx, ManglingContextDecl) =
5134 getCurrentMangleNumberContext(Tag->getDeclContext());
5135 if (MCtx) {
5136 Context.setManglingNumber(
5137 Tag, MCtx->getManglingNumber(
5138 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
5139 }
5140}
5141
5142namespace {
5143struct NonCLikeKind {
5144 enum {
5145 None,
5146 BaseClass,
5147 DefaultMemberInit,
5148 Lambda,
5149 Friend,
5150 OtherMember,
5151 Invalid,
5152 } Kind = None;
5153 SourceRange Range;
5154
5155 explicit operator bool() { return Kind != None; }
5156};
5157}
5158
5159/// Determine whether a class is C-like, according to the rules of C++
5160/// [dcl.typedef] for anonymous classes with typedef names for linkage.
5161static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
5162 if (RD->isInvalidDecl())
5163 return {NonCLikeKind::Invalid, {}};
5164
5165 // C++ [dcl.typedef]p9: [P1766R1]
5166 // An unnamed class with a typedef name for linkage purposes shall not
5167 //
5168 // -- have any base classes
5169 if (RD->getNumBases())
5170 return {NonCLikeKind::BaseClass,
5172 RD->bases_end()[-1].getEndLoc())};
5173 bool Invalid = false;
5174 for (Decl *D : RD->decls()) {
5175 // Don't complain about things we already diagnosed.
5176 if (D->isInvalidDecl()) {
5177 Invalid = true;
5178 continue;
5179 }
5180
5181 // -- have any [...] default member initializers
5182 if (auto *FD = dyn_cast<FieldDecl>(D)) {
5183 if (FD->hasInClassInitializer()) {
5184 auto *Init = FD->getInClassInitializer();
5185 return {NonCLikeKind::DefaultMemberInit,
5186 Init ? Init->getSourceRange() : D->getSourceRange()};
5187 }
5188 continue;
5189 }
5190
5191 // FIXME: We don't allow friend declarations. This violates the wording of
5192 // P1766, but not the intent.
5193 if (isa<FriendDecl>(D))
5194 return {NonCLikeKind::Friend, D->getSourceRange()};
5195
5196 // -- declare any members other than non-static data members, member
5197 // enumerations, or member classes,
5199 isa<EnumDecl>(D))
5200 continue;
5201 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
5202 if (!MemberRD) {
5203 if (D->isImplicit())
5204 continue;
5205 return {NonCLikeKind::OtherMember, D->getSourceRange()};
5206 }
5207
5208 // -- contain a lambda-expression,
5209 if (MemberRD->isLambda())
5210 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
5211
5212 // and all member classes shall also satisfy these requirements
5213 // (recursively).
5214 if (MemberRD->isThisDeclarationADefinition()) {
5215 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
5216 return Kind;
5217 }
5218 }
5219
5220 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
5221}
5222
5224 TypedefNameDecl *NewTD) {
5225 if (TagFromDeclSpec->isInvalidDecl())
5226 return;
5227
5228 // Do nothing if the tag already has a name for linkage purposes.
5229 if (TagFromDeclSpec->hasNameForLinkage())
5230 return;
5231
5232 // A well-formed anonymous tag must always be a TagUseKind::Definition.
5233 assert(TagFromDeclSpec->isThisDeclarationADefinition());
5234
5235 // The type must match the tag exactly; no qualifiers allowed.
5236 if (!Context.hasSameType(NewTD->getUnderlyingType(),
5237 Context.getCanonicalTagType(TagFromDeclSpec))) {
5238 if (getLangOpts().CPlusPlus)
5239 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
5240 return;
5241 }
5242
5243 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
5244 // An unnamed class with a typedef name for linkage purposes shall [be
5245 // C-like].
5246 //
5247 // FIXME: Also diagnose if we've already computed the linkage. That ideally
5248 // shouldn't happen, but there are constructs that the language rule doesn't
5249 // disallow for which we can't reasonably avoid computing linkage early.
5250 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
5251 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
5252 : NonCLikeKind();
5253 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
5254 if (NonCLike || ChangesLinkage) {
5255 if (NonCLike.Kind == NonCLikeKind::Invalid)
5256 return;
5257
5258 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
5259 if (ChangesLinkage) {
5260 // If the linkage changes, we can't accept this as an extension.
5261 if (NonCLike.Kind == NonCLikeKind::None)
5262 DiagID = diag::err_typedef_changes_linkage;
5263 else
5264 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
5265 }
5266
5267 SourceLocation FixitLoc =
5268 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
5269 llvm::SmallString<40> TextToInsert;
5270 TextToInsert += ' ';
5271 TextToInsert += NewTD->getIdentifier()->getName();
5272
5273 Diag(FixitLoc, DiagID)
5274 << isa<TypeAliasDecl>(NewTD)
5275 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
5276 if (NonCLike.Kind != NonCLikeKind::None) {
5277 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
5278 << NonCLike.Kind - 1 << NonCLike.Range;
5279 }
5280 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
5281 << NewTD << isa<TypeAliasDecl>(NewTD);
5282
5283 if (ChangesLinkage)
5284 return;
5285 }
5286
5287 // Otherwise, set this as the anon-decl typedef for the tag.
5288 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
5289
5290 // Now that we have a name for the tag, process API notes again.
5291 ProcessAPINotes(TagFromDeclSpec);
5292}
5293
5294static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) {
5296 switch (T) {
5298 return 0;
5300 return 1;
5302 return 2;
5304 return 3;
5305 case DeclSpec::TST_enum:
5306 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) {
5307 if (ED->isScopedUsingClassTag())
5308 return 5;
5309 if (ED->isScoped())
5310 return 6;
5311 }
5312 return 4;
5313 default:
5314 llvm_unreachable("unexpected type specifier");
5315 }
5316}
5317
5319 DeclSpec &DS,
5320 const ParsedAttributesView &DeclAttrs,
5321 MultiTemplateParamsArg TemplateParams,
5322 bool IsExplicitInstantiation,
5323 RecordDecl *&AnonRecord,
5324 SourceLocation EllipsisLoc) {
5325 Decl *TagD = nullptr;
5326 TagDecl *Tag = nullptr;
5332 TagD = DS.getRepAsDecl();
5333
5334 if (!TagD) // We probably had an error
5335 return nullptr;
5336
5337 // Note that the above type specs guarantee that the
5338 // type rep is a Decl, whereas in many of the others
5339 // it's a Type.
5340 if (isa<TagDecl>(TagD))
5341 Tag = cast<TagDecl>(TagD);
5342 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
5343 Tag = CTD->getTemplatedDecl();
5344 }
5345
5346 if (Tag) {
5347 handleTagNumbering(Tag, S);
5348 Tag->setFreeStanding();
5349 if (Tag->isInvalidDecl())
5350 return Tag;
5351 }
5352
5353 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
5354 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
5355 // or incomplete types shall not be restrict-qualified."
5356 if (TypeQuals & DeclSpec::TQ_restrict)
5358 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
5359 << DS.getSourceRange();
5360 }
5361
5362 if (DS.isInlineSpecified())
5363 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5364 << getLangOpts().CPlusPlus17;
5365
5366 if (DS.hasConstexprSpecifier()) {
5367 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
5368 // and definitions of functions and variables.
5369 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
5370 // the declaration of a function or function template
5371 if (Tag)
5372 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
5374 << static_cast<int>(DS.getConstexprSpecifier());
5375 else if (getLangOpts().C23)
5376 Diag(DS.getConstexprSpecLoc(), diag::err_c23_constexpr_not_variable);
5377 else
5378 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
5379 << static_cast<int>(DS.getConstexprSpecifier());
5380 // Don't emit warnings after this error.
5381 return TagD;
5382 }
5383
5385
5386 if (DS.isFriendSpecified()) {
5387 // If we're dealing with a decl but not a TagDecl, assume that
5388 // whatever routines created it handled the friendship aspect.
5389 if (TagD && !Tag)
5390 return nullptr;
5391 return ActOnFriendTypeDecl(S, DS, TemplateParams, EllipsisLoc);
5392 }
5393
5394 assert(EllipsisLoc.isInvalid() &&
5395 "Friend ellipsis but not friend-specified?");
5396
5397 // Track whether this decl-specifier declares anything.
5398 bool DeclaresAnything = true;
5399
5400 // Handle anonymous struct definitions.
5401 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
5402 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
5404 if (getLangOpts().CPlusPlus ||
5405 Record->getDeclContext()->isRecord()) {
5406 // If CurContext is a DeclContext that can contain statements,
5407 // RecursiveASTVisitor won't visit the decls that
5408 // BuildAnonymousStructOrUnion() will put into CurContext.
5409 // Also store them here so that they can be part of the
5410 // DeclStmt that gets created in this case.
5411 // FIXME: Also return the IndirectFieldDecls created by
5412 // BuildAnonymousStructOr union, for the same reason?
5413 if (CurContext->isFunctionOrMethod())
5414 AnonRecord = Record;
5415 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
5416 Context.getPrintingPolicy());
5417 }
5418
5419 DeclaresAnything = false;
5420 }
5421 }
5422
5423 // C11 6.7.2.1p2:
5424 // A struct-declaration that does not declare an anonymous structure or
5425 // anonymous union shall contain a struct-declarator-list.
5426 //
5427 // This rule also existed in C89 and C99; the grammar for struct-declaration
5428 // did not permit a struct-declaration without a struct-declarator-list.
5429 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
5431 // Check for Microsoft C extension: anonymous struct/union member.
5432 // Handle 2 kinds of anonymous struct/union:
5433 // struct STRUCT;
5434 // union UNION;
5435 // and
5436 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
5437 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
5438 if ((Tag && Tag->getDeclName()) ||
5440 RecordDecl *Record = Tag ? dyn_cast<RecordDecl>(Tag)
5441 : DS.getRepAsType().get()->getAsRecordDecl();
5442 if (Record && getLangOpts().MSAnonymousStructs) {
5443 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
5444 << Record->isUnion() << DS.getSourceRange();
5446 }
5447
5448 DeclaresAnything = false;
5449 }
5450 }
5451
5452 // Skip all the checks below if we have a type error.
5454 (TagD && TagD->isInvalidDecl()))
5455 return TagD;
5456
5457 if (getLangOpts().CPlusPlus &&
5459 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
5460 if (Enum->enumerators().empty() && !Enum->getIdentifier() &&
5461 !Enum->isInvalidDecl())
5462 DeclaresAnything = false;
5463
5464 if (!DS.isMissingDeclaratorOk()) {
5465 // Customize diagnostic for a typedef missing a name.
5467 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
5468 << DS.getSourceRange();
5469 else
5470 DeclaresAnything = false;
5471 }
5472
5473 if (DS.isModulePrivateSpecified() &&
5474 Tag && Tag->getDeclContext()->isFunctionOrMethod())
5475 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
5476 << Tag->getTagKind()
5478
5480
5481 // C 6.7/2:
5482 // A declaration [...] shall declare at least a declarator [...], a tag,
5483 // or the members of an enumeration.
5484 // C++ [dcl.dcl]p3:
5485 // [If there are no declarators], and except for the declaration of an
5486 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5487 // names into the program, or shall redeclare a name introduced by a
5488 // previous declaration.
5489 if (!DeclaresAnything) {
5490 // In C, we allow this as a (popular) extension / bug. Don't bother
5491 // producing further diagnostics for redundant qualifiers after this.
5492 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
5493 ? diag::err_no_declarators
5494 : diag::ext_no_declarators)
5495 << DS.getSourceRange();
5496 return TagD;
5497 }
5498
5499 // C++ [dcl.stc]p1:
5500 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
5501 // init-declarator-list of the declaration shall not be empty.
5502 // C++ [dcl.fct.spec]p1:
5503 // If a cv-qualifier appears in a decl-specifier-seq, the
5504 // init-declarator-list of the declaration shall not be empty.
5505 //
5506 // Spurious qualifiers here appear to be valid in C.
5507 unsigned DiagID = diag::warn_standalone_specifier;
5508 if (getLangOpts().CPlusPlus)
5509 DiagID = diag::ext_standalone_specifier;
5510
5511 // Note that a linkage-specification sets a storage class, but
5512 // 'extern "C" struct foo;' is actually valid and not theoretically
5513 // useless.
5514 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5515 if (SCS == DeclSpec::SCS_mutable)
5516 // Since mutable is not a viable storage class specifier in C, there is
5517 // no reason to treat it as an extension. Instead, diagnose as an error.
5518 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5519 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5520 Diag(DS.getStorageClassSpecLoc(), DiagID)
5522 }
5523
5527 if (DS.getTypeQualifiers()) {
5529 Diag(DS.getConstSpecLoc(), DiagID) << "const";
5531 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5532 // Restrict is covered above.
5534 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5536 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5537 }
5538
5539 // Warn about ignored type attributes, for example:
5540 // __attribute__((aligned)) struct A;
5541 // Attributes should be placed after tag to apply to type declaration.
5542 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
5543 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5544 if (TypeSpecType == DeclSpec::TST_class ||
5545 TypeSpecType == DeclSpec::TST_struct ||
5546 TypeSpecType == DeclSpec::TST_interface ||
5547 TypeSpecType == DeclSpec::TST_union ||
5548 TypeSpecType == DeclSpec::TST_enum) {
5549
5550 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) {
5551 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored;
5552 if (AL.isAlignas() && !getLangOpts().CPlusPlus)
5553 DiagnosticId = diag::warn_attribute_ignored;
5554 else if (AL.isRegularKeywordAttribute())
5555 DiagnosticId = diag::err_declspec_keyword_has_no_effect;
5556 else
5557 DiagnosticId = diag::warn_declspec_attribute_ignored;
5558 Diag(AL.getLoc(), DiagnosticId)
5559 << AL << GetDiagnosticTypeSpecifierID(DS);
5560 };
5561
5562 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic);
5563 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic);
5564 }
5565 }
5566
5567 return TagD;
5568}
5569
5570/// We are trying to inject an anonymous member into the given scope;
5571/// check if there's an existing declaration that can't be overloaded.
5572///
5573/// \return true if this is a forbidden redeclaration
5574static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S,
5575 DeclContext *Owner,
5576 DeclarationName Name,
5577 SourceLocation NameLoc, bool IsUnion,
5578 StorageClass SC) {
5579 LookupResult R(SemaRef, Name, NameLoc,
5583 if (!SemaRef.LookupName(R, S)) return false;
5584
5585 // Pick a representative declaration.
5586 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
5587 assert(PrevDecl && "Expected a non-null Decl");
5588
5589 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5590 return false;
5591
5592 if (SC == StorageClass::SC_None &&
5593 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) &&
5594 (Owner->isFunctionOrMethod() || Owner->isRecord())) {
5595 if (!Owner->isRecord())
5596 SemaRef.DiagPlaceholderVariableDefinition(NameLoc);
5597 return false;
5598 }
5599
5600 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5601 << IsUnion << Name;
5602 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5603
5604 return true;
5605}
5606
5608 if (auto *RD = dyn_cast_if_present<RecordDecl>(D))
5610}
5611
5613 if (!getLangOpts().CPlusPlus)
5614 return;
5615
5616 // This function can be parsed before we have validated the
5617 // structure as an anonymous struct
5618 if (Record->isAnonymousStructOrUnion())
5619 return;
5620
5621 const NamedDecl *First = 0;
5622 for (const Decl *D : Record->decls()) {
5623 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5624 if (!ND || !ND->isPlaceholderVar(getLangOpts()))
5625 continue;
5626 if (!First)
5627 First = ND;
5628 else
5630 }
5631}
5632
5633/// InjectAnonymousStructOrUnionMembers - Inject the members of the
5634/// anonymous struct or union AnonRecord into the owning context Owner
5635/// and scope S. This routine will be invoked just after we realize
5636/// that an unnamed union or struct is actually an anonymous union or
5637/// struct, e.g.,
5638///
5639/// @code
5640/// union {
5641/// int i;
5642/// float f;
5643/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5644/// // f into the surrounding scope.x
5645/// @endcode
5646///
5647/// This routine is recursive, injecting the names of nested anonymous
5648/// structs/unions into the owning context and scope as well.
5649static bool
5651 RecordDecl *AnonRecord, AccessSpecifier AS,
5652 StorageClass SC,
5653 SmallVectorImpl<NamedDecl *> &Chaining) {
5654 bool Invalid = false;
5655
5656 // Look every FieldDecl and IndirectFieldDecl with a name.
5657 for (auto *D : AnonRecord->decls()) {
5658 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5659 cast<NamedDecl>(D)->getDeclName()) {
5660 ValueDecl *VD = cast<ValueDecl>(D);
5661 // C++ [class.union]p2:
5662 // The names of the members of an anonymous union shall be
5663 // distinct from the names of any other entity in the
5664 // scope in which the anonymous union is declared.
5665
5666 bool FieldInvalid = CheckAnonMemberRedeclaration(
5667 SemaRef, S, Owner, VD->getDeclName(), VD->getLocation(),
5668 AnonRecord->isUnion(), SC);
5669 if (FieldInvalid)
5670 Invalid = true;
5671
5672 // Inject the IndirectFieldDecl even if invalid, because later
5673 // diagnostics may depend on it being present, see findDefaultInitializer.
5674
5675 // C++ [class.union]p2:
5676 // For the purpose of name lookup, after the anonymous union
5677 // definition, the members of the anonymous union are
5678 // considered to have been defined in the scope in which the
5679 // anonymous union is declared.
5680 unsigned OldChainingSize = Chaining.size();
5681 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5682 Chaining.append(IF->chain_begin(), IF->chain_end());
5683 else
5684 Chaining.push_back(VD);
5685
5686 assert(Chaining.size() >= 2);
5687 NamedDecl **NamedChain =
5688 new (SemaRef.Context) NamedDecl *[Chaining.size()];
5689 for (unsigned i = 0; i < Chaining.size(); i++)
5690 NamedChain[i] = Chaining[i];
5691
5693 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5694 VD->getType(), {NamedChain, Chaining.size()});
5695
5696 for (const auto *Attr : VD->attrs())
5697 IndirectField->addAttr(Attr->clone(SemaRef.Context));
5698
5699 IndirectField->setAccess(AS);
5700 IndirectField->setImplicit();
5701 IndirectField->setInvalidDecl(FieldInvalid);
5702 SemaRef.PushOnScopeChains(IndirectField, S);
5703
5704 // That includes picking up the appropriate access specifier.
5705 if (AS != AS_none)
5706 IndirectField->setAccess(AS);
5707
5708 Chaining.resize(OldChainingSize);
5709 }
5710 }
5711
5712 return Invalid;
5713}
5714
5715/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5716/// a VarDecl::StorageClass. Any error reporting is up to the caller:
5717/// illegal input values are mapped to SC_None.
5718static StorageClass
5720 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5721 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5722 "Parser allowed 'typedef' as storage class VarDecl.");
5723 switch (StorageClassSpec) {
5726 if (DS.isExternInLinkageSpec())
5727 return SC_None;
5728 return SC_Extern;
5729 case DeclSpec::SCS_static: return SC_Static;
5730 case DeclSpec::SCS_auto: return SC_Auto;
5733 // Illegal SCSs map to None: error reporting is up to the caller.
5734 case DeclSpec::SCS_mutable: // Fall through.
5735 case DeclSpec::SCS_typedef: return SC_None;
5736 }
5737 llvm_unreachable("unknown storage class specifier");
5738}
5739
5741 assert(Record->hasInClassInitializer());
5742
5743 for (const auto *I : Record->decls()) {
5744 const auto *FD = dyn_cast<FieldDecl>(I);
5745 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5746 FD = IFD->getAnonField();
5747 if (FD && FD->hasInClassInitializer())
5748 return FD->getLocation();
5749 }
5750
5751 llvm_unreachable("couldn't find in-class initializer");
5752}
5753
5755 SourceLocation DefaultInitLoc) {
5756 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5757 return;
5758
5759 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5760 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5761}
5762
5764 CXXRecordDecl *AnonUnion) {
5765 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5766 return;
5767
5769}
5770
5772 AccessSpecifier AS,
5774 const PrintingPolicy &Policy) {
5775 DeclContext *Owner = Record->getDeclContext();
5776
5777 // Diagnose whether this anonymous struct/union is an extension.
5778 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5779 Diag(Record->getLocation(), diag::ext_anonymous_union);
5780 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5781 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5782 else if (!Record->isUnion() && !getLangOpts().C11)
5783 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5784
5785 // C and C++ require different kinds of checks for anonymous
5786 // structs/unions.
5787 bool Invalid = false;
5788 if (getLangOpts().CPlusPlus) {
5789 const char *PrevSpec = nullptr;
5790 if (Record->isUnion()) {
5791 // C++ [class.union]p6:
5792 // C++17 [class.union.anon]p2:
5793 // Anonymous unions declared in a named namespace or in the
5794 // global namespace shall be declared static.
5795 unsigned DiagID;
5796 DeclContext *OwnerScope = Owner->getRedeclContext();
5798 (OwnerScope->isTranslationUnit() ||
5799 (OwnerScope->isNamespace() &&
5800 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5801 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5802 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5803
5804 // Recover by adding 'static'.
5806 PrevSpec, DiagID, Policy);
5807 }
5808 // C++ [class.union]p6:
5809 // A storage class is not allowed in a declaration of an
5810 // anonymous union in a class scope.
5812 isa<RecordDecl>(Owner)) {
5814 diag::err_anonymous_union_with_storage_spec)
5816
5817 // Recover by removing the storage specifier.
5820 PrevSpec, DiagID, Context.getPrintingPolicy());
5821 }
5822 }
5823
5824 // Ignore const/volatile/restrict qualifiers.
5825 if (DS.getTypeQualifiers()) {
5827 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5828 << Record->isUnion() << "const"
5832 diag::ext_anonymous_struct_union_qualified)
5833 << Record->isUnion() << "volatile"
5837 diag::ext_anonymous_struct_union_qualified)
5838 << Record->isUnion() << "restrict"
5842 diag::ext_anonymous_struct_union_qualified)
5843 << Record->isUnion() << "_Atomic"
5847 diag::ext_anonymous_struct_union_qualified)
5848 << Record->isUnion() << "__unaligned"
5850
5852 }
5853
5854 // C++ [class.union]p2:
5855 // The member-specification of an anonymous union shall only
5856 // define non-static data members. [Note: nested types and
5857 // functions cannot be declared within an anonymous union. ]
5858 for (auto *Mem : Record->decls()) {
5859 // Ignore invalid declarations; we already diagnosed them.
5860 if (Mem->isInvalidDecl())
5861 continue;
5862
5863 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5864 // C++ [class.union]p3:
5865 // An anonymous union shall not have private or protected
5866 // members (clause 11).
5867 assert(FD->getAccess() != AS_none);
5868 if (FD->getAccess() != AS_public) {
5869 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5870 << Record->isUnion() << (FD->getAccess() == AS_protected);
5871 Invalid = true;
5872 }
5873
5874 // C++ [class.union]p1
5875 // An object of a class with a non-trivial constructor, a non-trivial
5876 // copy constructor, a non-trivial destructor, or a non-trivial copy
5877 // assignment operator cannot be a member of a union, nor can an
5878 // array of such objects.
5879 if (CheckNontrivialField(FD))
5880 Invalid = true;
5881 } else if (Mem->isImplicit()) {
5882 // Any implicit members are fine.
5883 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5884 // This is a type that showed up in an
5885 // elaborated-type-specifier inside the anonymous struct or
5886 // union, but which actually declares a type outside of the
5887 // anonymous struct or union. It's okay.
5888 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5889 if (!MemRecord->isAnonymousStructOrUnion() &&
5890 MemRecord->getDeclName()) {
5891 // Visual C++ allows type definition in anonymous struct or union.
5892 if (getLangOpts().MicrosoftExt)
5893 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5894 << Record->isUnion();
5895 else {
5896 // This is a nested type declaration.
5897 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5898 << Record->isUnion();
5899 Invalid = true;
5900 }
5901 } else {
5902 // This is an anonymous type definition within another anonymous type.
5903 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5904 // not part of standard C++.
5905 Diag(MemRecord->getLocation(),
5906 diag::ext_anonymous_record_with_anonymous_type)
5907 << Record->isUnion();
5908 }
5909 } else if (isa<AccessSpecDecl>(Mem)) {
5910 // Any access specifier is fine.
5911 } else if (isa<StaticAssertDecl>(Mem)) {
5912 // In C++1z, static_assert declarations are also fine.
5913 } else {
5914 // We have something that isn't a non-static data
5915 // member. Complain about it.
5916 unsigned DK = diag::err_anonymous_record_bad_member;
5917 if (isa<TypeDecl>(Mem))
5918 DK = diag::err_anonymous_record_with_type;
5919 else if (isa<FunctionDecl>(Mem))
5920 DK = diag::err_anonymous_record_with_function;
5921 else if (isa<VarDecl>(Mem))
5922 DK = diag::err_anonymous_record_with_static;
5923
5924 // Visual C++ allows type definition in anonymous struct or union.
5925 if (getLangOpts().MicrosoftExt &&
5926 DK == diag::err_anonymous_record_with_type)
5927 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5928 << Record->isUnion();
5929 else {
5930 Diag(Mem->getLocation(), DK) << Record->isUnion();
5931 Invalid = true;
5932 }
5933 }
5934 }
5935
5936 // C++11 [class.union]p8 (DR1460):
5937 // At most one variant member of a union may have a
5938 // brace-or-equal-initializer.
5939 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5940 Owner->isRecord())
5943 }
5944
5945 if (!Record->isUnion() && !Owner->isRecord()) {
5946 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5947 << getLangOpts().CPlusPlus;
5948 Invalid = true;
5949 }
5950
5951 // C++ [dcl.dcl]p3:
5952 // [If there are no declarators], and except for the declaration of an
5953 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5954 // names into the program
5955 // C++ [class.mem]p2:
5956 // each such member-declaration shall either declare at least one member
5957 // name of the class or declare at least one unnamed bit-field
5958 //
5959 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5960 if (getLangOpts().CPlusPlus && Record->field_empty())
5961 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5962
5963 // Mock up a declarator.
5967 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5968
5969 // Create a declaration for this anonymous struct/union.
5970 NamedDecl *Anon = nullptr;
5971 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5972 Anon = FieldDecl::Create(
5973 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5974 /*IdentifierInfo=*/nullptr, Context.getCanonicalTagType(Record), TInfo,
5975 /*BitWidth=*/nullptr, /*Mutable=*/false,
5976 /*InitStyle=*/ICIS_NoInit);
5977 Anon->setAccess(AS);
5978 ProcessDeclAttributes(S, Anon, Dc);
5979
5980 if (getLangOpts().CPlusPlus)
5981 FieldCollector->Add(cast<FieldDecl>(Anon));
5982 } else {
5983 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5984 if (SCSpec == DeclSpec::SCS_mutable) {
5985 // mutable can only appear on non-static class members, so it's always
5986 // an error here
5987 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5988 Invalid = true;
5989 SC = SC_None;
5990 }
5991
5992 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5993 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5994 Context.getCanonicalTagType(Record), TInfo, SC);
5995 if (Invalid)
5996 Anon->setInvalidDecl();
5997
5998 ProcessDeclAttributes(S, Anon, Dc);
5999
6000 // Default-initialize the implicit variable. This initialization will be
6001 // trivial in almost all cases, except if a union member has an in-class
6002 // initializer:
6003 // union { int n = 0; };
6005 }
6006 Anon->setImplicit();
6007
6008 // Mark this as an anonymous struct/union type.
6009 Record->setAnonymousStructOrUnion(true);
6010
6011 // Add the anonymous struct/union object to the current
6012 // context. We'll be referencing this object when we refer to one of
6013 // its members.
6014 Owner->addDecl(Anon);
6015
6016 // Inject the members of the anonymous struct/union into the owning
6017 // context and into the identifier resolver chain for name lookup
6018 // purposes.
6020 Chain.push_back(Anon);
6021
6022 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC,
6023 Chain))
6024 Invalid = true;
6025
6026 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
6027 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6029 Decl *ManglingContextDecl;
6030 std::tie(MCtx, ManglingContextDecl) =
6031 getCurrentMangleNumberContext(NewVD->getDeclContext());
6032 if (MCtx) {
6033 Context.setManglingNumber(
6034 NewVD, MCtx->getManglingNumber(
6035 NewVD, getMSManglingNumber(getLangOpts(), S)));
6036 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6037 }
6038 }
6039 }
6040
6041 if (Invalid)
6042 Anon->setInvalidDecl();
6043
6044 return Anon;
6045}
6046
6048 RecordDecl *Record) {
6049 assert(Record && "expected a record!");
6050
6051 // Mock up a declarator.
6054 assert(TInfo && "couldn't build declarator info for anonymous struct");
6055
6056 auto *ParentDecl = cast<RecordDecl>(CurContext);
6057 CanQualType RecTy = Context.getCanonicalTagType(Record);
6058
6059 // Create a declaration for this anonymous struct.
6060 NamedDecl *Anon =
6061 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
6062 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
6063 /*BitWidth=*/nullptr, /*Mutable=*/false,
6064 /*InitStyle=*/ICIS_NoInit);
6065 Anon->setImplicit();
6066
6067 // Add the anonymous struct object to the current context.
6068 CurContext->addDecl(Anon);
6069
6070 // Inject the members of the anonymous struct into the current
6071 // context and into the identifier resolver chain for name lookup
6072 // purposes.
6074 Chain.push_back(Anon);
6075
6076 RecordDecl *RecordDef = Record->getDefinition();
6077 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
6078 diag::err_field_incomplete_or_sizeless) ||
6080 *this, S, CurContext, RecordDef, AS_none,
6082 Anon->setInvalidDecl();
6083 ParentDecl->setInvalidDecl();
6084 }
6085
6086 return Anon;
6087}
6088
6092
6095 DeclarationNameInfo NameInfo;
6096 NameInfo.setLoc(Name.StartLocation);
6097
6098 switch (Name.getKind()) {
6099
6102 NameInfo.setName(Name.Identifier);
6103 return NameInfo;
6104
6106 // C++ [temp.deduct.guide]p3:
6107 // The simple-template-id shall name a class template specialization.
6108 // The template-name shall be the same identifier as the template-name
6109 // of the simple-template-id.
6110 // These together intend to imply that the template-name shall name a
6111 // class template.
6112 // FIXME: template<typename T> struct X {};
6113 // template<typename T> using Y = X<T>;
6114 // Y(int) -> Y<int>;
6115 // satisfies these rules but does not name a class template.
6116 TemplateName TN = Name.TemplateName.get().get();
6117 auto *Template = TN.getAsTemplateDecl();
6119 Diag(Name.StartLocation,
6120 diag::err_deduction_guide_name_not_class_template)
6121 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
6122 if (Template)
6124 return DeclarationNameInfo();
6125 }
6126
6127 NameInfo.setName(
6128 Context.DeclarationNames.getCXXDeductionGuideName(Template));
6129 return NameInfo;
6130 }
6131
6133 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
6137 return NameInfo;
6138
6140 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
6141 Name.Identifier));
6143 return NameInfo;
6144
6146 TypeSourceInfo *TInfo;
6148 if (Ty.isNull())
6149 return DeclarationNameInfo();
6150 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
6151 Context.getCanonicalType(Ty)));
6152 NameInfo.setNamedTypeInfo(TInfo);
6153 return NameInfo;
6154 }
6155
6157 TypeSourceInfo *TInfo;
6158 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
6159 if (Ty.isNull())
6160 return DeclarationNameInfo();
6161 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
6162 Context.getCanonicalType(Ty)));
6163 NameInfo.setNamedTypeInfo(TInfo);
6164 return NameInfo;
6165 }
6166
6168 // In well-formed code, we can only have a constructor
6169 // template-id that refers to the current context, so go there
6170 // to find the actual type being constructed.
6171 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
6172 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
6173 return DeclarationNameInfo();
6174
6175 // Determine the type of the class being constructed.
6176 CanQualType CurClassType = Context.getCanonicalTagType(CurClass);
6177
6178 // FIXME: Check two things: that the template-id names the same type as
6179 // CurClassType, and that the template-id does not occur when the name
6180 // was qualified.
6181
6182 NameInfo.setName(
6183 Context.DeclarationNames.getCXXConstructorName(CurClassType));
6184 // FIXME: should we retrieve TypeSourceInfo?
6185 NameInfo.setNamedTypeInfo(nullptr);
6186 return NameInfo;
6187 }
6188
6190 TypeSourceInfo *TInfo;
6191 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
6192 if (Ty.isNull())
6193 return DeclarationNameInfo();
6194 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
6195 Context.getCanonicalType(Ty)));
6196 NameInfo.setNamedTypeInfo(TInfo);
6197 return NameInfo;
6198 }
6199
6201 TemplateName TName = Name.TemplateId->Template.get();
6202 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
6203 return Context.getNameForTemplate(TName, TNameLoc);
6204 }
6205
6206 } // switch (Name.getKind())
6207
6208 llvm_unreachable("Unknown name kind");
6209}
6210
6212 do {
6213 if (Ty->isPointerOrReferenceType())
6214 Ty = Ty->getPointeeType();
6215 else if (Ty->isArrayType())
6217 else
6218 return Ty.withoutLocalFastQualifiers();
6219 } while (true);
6220}
6221
6222/// hasSimilarParameters - Determine whether the C++ functions Declaration
6223/// and Definition have "nearly" matching parameters. This heuristic is
6224/// used to improve diagnostics in the case where an out-of-line function
6225/// definition doesn't match any declaration within the class or namespace.
6226/// Also sets Params to the list of indices to the parameters that differ
6227/// between the declaration and the definition. If hasSimilarParameters
6228/// returns true and Params is empty, then all of the parameters match.
6232 SmallVectorImpl<unsigned> &Params) {
6233 Params.clear();
6234 if (Declaration->param_size() != Definition->param_size())
6235 return false;
6236 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
6237 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
6238 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
6239
6240 // The parameter types are identical
6241 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
6242 continue;
6243
6244 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
6245 QualType DefParamBaseTy = getCoreType(DefParamTy);
6246 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
6247 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
6248
6249 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
6250 (DeclTyName && DeclTyName == DefTyName))
6251 Params.push_back(Idx);
6252 else // The two parameters aren't even close
6253 return false;
6254 }
6255
6256 return true;
6257}
6258
6259/// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
6260/// declarator needs to be rebuilt in the current instantiation.
6261/// Any bits of declarator which appear before the name are valid for
6262/// consideration here. That's specifically the type in the decl spec
6263/// and the base type in any member-pointer chunks.
6265 DeclarationName Name) {
6266 // The types we specifically need to rebuild are:
6267 // - typenames, typeofs, and decltypes
6268 // - types which will become injected class names
6269 // Of course, we also need to rebuild any type referencing such a
6270 // type. It's safest to just say "dependent", but we call out a
6271 // few cases here.
6272
6273 DeclSpec &DS = D.getMutableDeclSpec();
6274 switch (DS.getTypeSpecType()) {
6278#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
6279#include "clang/Basic/BuiltinTraits.inc"
6280 case DeclSpec::TST_atomic: {
6281 // Grab the type from the parser.
6282 TypeSourceInfo *TSI = nullptr;
6283 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
6284 if (T.isNull() || !T->isInstantiationDependentType()) break;
6285
6286 // Make sure there's a type source info. This isn't really much
6287 // of a waste; most dependent types should have type source info
6288 // attached already.
6289 if (!TSI)
6291
6292 // Rebuild the type in the current instantiation.
6294 if (!TSI) return true;
6295
6296 // Store the new type back in the decl spec.
6297 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
6298 DS.UpdateTypeRep(LocType);
6299 break;
6300 }
6301
6305 Expr *E = DS.getRepAsExpr();
6307 if (Result.isInvalid()) return true;
6308 DS.UpdateExprRep(Result.get());
6309 break;
6310 }
6311
6312 default:
6313 // Nothing to do for these decl specs.
6314 break;
6315 }
6316
6317 // It doesn't matter what order we do this in.
6318 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
6319 DeclaratorChunk &Chunk = D.getTypeObject(I);
6320
6321 // The only type information in the declarator which can come
6322 // before the declaration name is the base type of a member
6323 // pointer.
6325 continue;
6326
6327 // Rebuild the scope specifier in-place.
6328 CXXScopeSpec &SS = Chunk.Mem.Scope();
6330 return true;
6331 }
6332
6333 return false;
6334}
6335
6336/// Returns true if the declaration is declared in a system header or from a
6337/// system macro.
6338static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
6339 return SM.isInSystemHeader(D->getLocation()) ||
6341}
6342
6344 // Avoid warning twice on the same identifier, and don't warn on redeclaration
6345 // of system decl.
6346 if (D->getPreviousDecl() || D->isImplicit())
6347 return;
6350 !isFromSystemHeader(Context.getSourceManager(), D)) {
6351 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
6352 << D << static_cast<int>(Status);
6353 }
6354}
6355
6358
6359 // Check if we are in an `omp begin/end declare variant` scope. Handle this
6360 // declaration only if the `bind_to_declaration` extension is set.
6362 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
6363 if (OpenMP().getOMPTraitInfoForSurroundingScope()->isExtensionActive(
6364 llvm::omp::TraitProperty::
6365 implementation_extension_bind_to_declaration))
6367 S, D, MultiTemplateParamsArg(), Bases);
6368
6370
6371 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
6372 Dcl && Dcl->getDeclContext()->isFileContext())
6374
6375 if (!Bases.empty())
6377 Bases);
6378
6379 return Dcl;
6380}
6381
6383 DeclarationNameInfo NameInfo) {
6384 DeclarationName Name = NameInfo.getName();
6385
6386 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
6387 while (Record && Record->isAnonymousStructOrUnion())
6388 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
6389 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
6390 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
6391 return true;
6392 }
6393
6394 return false;
6395}
6396
6398 DeclarationName Name,
6399 SourceLocation Loc,
6400 TemplateIdAnnotation *TemplateId,
6401 bool IsMemberSpecialization) {
6402 assert(SS.isValid() && "diagnoseQualifiedDeclaration called for declaration "
6403 "without nested-name-specifier");
6404 DeclContext *Cur = CurContext;
6405 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
6406 Cur = Cur->getParent();
6407
6408 // If the user provided a superfluous scope specifier that refers back to the
6409 // class in which the entity is already declared, diagnose and ignore it.
6410 //
6411 // class X {
6412 // void X::f();
6413 // };
6414 //
6415 // Note, it was once ill-formed to give redundant qualification in all
6416 // contexts, but that rule was removed by DR482.
6417 if (Cur->Equals(DC)) {
6418 if (Cur->isRecord()) {
6419 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
6420 : diag::err_member_extra_qualification)
6421 << Name << FixItHint::CreateRemoval(SS.getRange());
6422 SS.clear();
6423 } else {
6424 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
6425 }
6426 return false;
6427 }
6428
6429 // Check whether the qualifying scope encloses the scope of the original
6430 // declaration. For a template-id, we perform the checks in
6431 // CheckTemplateSpecializationScope.
6432 if (!Cur->Encloses(DC) && !(TemplateId || IsMemberSpecialization)) {
6434 if (Cur->isRecord())
6435 Diag(Loc, diag::err_member_qualification)
6436 << Name << SS.getRange();
6437 else if (isa<TranslationUnitDecl>(DC))
6438 Diag(Loc, diag::err_invalid_declarator_global_scope)
6439 << Name << SS.getRange();
6440 else if (isa<FunctionDecl>(Cur))
6441 Diag(Loc, diag::err_invalid_declarator_in_function)
6442 << Name << SS.getRange();
6443 else if (isa<BlockDecl>(Cur))
6444 Diag(Loc, diag::err_invalid_declarator_in_block)
6445 << Name << SS.getRange();
6446 else if (isa<ExportDecl>(Cur)) {
6447 if (!isa<NamespaceDecl>(DC))
6448 Diag(Loc, diag::err_export_non_namespace_scope_name)
6449 << Name << SS.getRange();
6450 else
6451 // The cases that DC is not NamespaceDecl should be handled in
6452 // CheckRedeclarationExported.
6453 return false;
6454 } else
6455 Diag(Loc, diag::err_invalid_declarator_scope)
6456 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
6457
6458 return true;
6459 }
6460
6461 if (Cur->isRecord()) {
6462 // C++26 [temp.expl.spec]p3 (Adopted as a DR in CWG727):
6463 // An explicit specialization may be declared in any scope in which the
6464 // corresponding primary template may be defined.
6465 if (IsMemberSpecialization)
6466 return false;
6467
6468 // Cannot qualify members within a class.
6469 Diag(Loc, diag::err_member_qualification)
6470 << Name << SS.getRange();
6471 SS.clear();
6472
6473 // C++ constructors and destructors with incorrect scopes can break
6474 // our AST invariants by having the wrong underlying types. If
6475 // that's the case, then drop this declaration entirely.
6478 !Context.hasSameType(
6479 Name.getCXXNameType(),
6480 Context.getCanonicalTagType(cast<CXXRecordDecl>(Cur))))
6481 return true;
6482
6483 return false;
6484 }
6485
6486 // C++23 [temp.names]p5:
6487 // The keyword template shall not appear immediately after a declarative
6488 // nested-name-specifier.
6489 //
6490 // First check the template-id (if any), and then check each component of the
6491 // nested-name-specifier in reverse order.
6492 //
6493 // FIXME: nested-name-specifiers in friend declarations are declarative,
6494 // but we don't call diagnoseQualifiedDeclaration for them. We should.
6495 if (TemplateId && TemplateId->TemplateKWLoc.isValid())
6496 Diag(Loc, diag::ext_template_after_declarative_nns)
6498
6500 for (TypeLoc TL = SpecLoc.getAsTypeLoc(), NextTL; TL;
6501 TL = std::exchange(NextTL, TypeLoc())) {
6502 SourceLocation TemplateKeywordLoc;
6503 switch (TL.getTypeLocClass()) {
6504 case TypeLoc::TemplateSpecialization: {
6505 auto TST = TL.castAs<TemplateSpecializationTypeLoc>();
6506 TemplateKeywordLoc = TST.getTemplateKeywordLoc();
6507 if (auto *T = TST.getTypePtr(); T->isDependentType() && T->isTypeAlias())
6508 Diag(Loc, diag::ext_alias_template_in_declarative_nns)
6509 << TST.getLocalSourceRange();
6510 break;
6511 }
6512 case TypeLoc::Decltype:
6513 case TypeLoc::PackIndexing: {
6514 const Type *T = TL.getTypePtr();
6515 // C++23 [expr.prim.id.qual]p2:
6516 // [...] A declarative nested-name-specifier shall not have a
6517 // computed-type-specifier.
6518 //
6519 // CWG2858 changed this from 'decltype-specifier' to
6520 // 'computed-type-specifier'.
6521 Diag(Loc, diag::err_computed_type_in_declarative_nns)
6522 << T->isDecltypeType() << TL.getSourceRange();
6523 break;
6524 }
6525 case TypeLoc::DependentName:
6526 NextTL =
6527 TL.castAs<DependentNameTypeLoc>().getQualifierLoc().getAsTypeLoc();
6528 break;
6529 default:
6530 break;
6531 }
6532 if (TemplateKeywordLoc.isValid())
6533 Diag(Loc, diag::ext_template_after_declarative_nns)
6534 << FixItHint::CreateRemoval(TemplateKeywordLoc);
6535 }
6536
6537 return false;
6538}
6539
6541 MultiTemplateParamsArg TemplateParamLists) {
6542 // TODO: consider using NameInfo for diagnostic.
6544 DeclarationName Name = NameInfo.getName();
6545
6546 // All of these full declarators require an identifier. If it doesn't have
6547 // one, the ParsedFreeStandingDeclSpec action should be used.
6548 if (D.isDecompositionDeclarator()) {
6549 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
6550 } else if (!Name) {
6551 if (!D.isInvalidType()) // Reject this if we think it is valid.
6552 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
6554 return nullptr;
6556 return nullptr;
6557
6558 DeclContext *DC = CurContext;
6559 if (D.getCXXScopeSpec().isInvalid())
6560 D.setInvalidType();
6561 else if (D.getCXXScopeSpec().isSet()) {
6564 return nullptr;
6565
6566 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
6567 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
6568 if (!DC || isa<EnumDecl>(DC)) {
6569 // If we could not compute the declaration context, it's because the
6570 // declaration context is dependent but does not refer to a class,
6571 // class template, or class template partial specialization. Complain
6572 // and return early, to avoid the coming semantic disaster.
6574 diag::err_template_qualified_declarator_no_match)
6576 << D.getCXXScopeSpec().getRange();
6577 return nullptr;
6578 }
6579 bool IsDependentContext = DC->isDependentContext();
6580
6581 if (!IsDependentContext &&
6583 return nullptr;
6584
6585 // If a class is incomplete, do not parse entities inside it.
6588 diag::err_member_def_undefined_record)
6589 << Name << DC << D.getCXXScopeSpec().getRange();
6590 return nullptr;
6591 }
6592 if (!D.getDeclSpec().isFriendSpecified()) {
6593 TemplateIdAnnotation *TemplateId =
6595 ? D.getName().TemplateId
6596 : nullptr;
6598 D.getIdentifierLoc(), TemplateId,
6599 /*IsMemberSpecialization=*/false)) {
6600 if (DC->isRecord())
6601 return nullptr;
6602
6603 D.setInvalidType();
6604 } else if (CurContext->isRecord() && !CurContext->Equals(DC)) {
6605 D.setInvalidType();
6606 }
6607 }
6608
6609 // Check whether we need to rebuild the type of the given
6610 // declaration in the current instantiation.
6611 if (EnteringContext && IsDependentContext &&
6612 TemplateParamLists.size() != 0) {
6613 ContextRAII SavedContext(*this, DC);
6614 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6615 D.setInvalidType();
6616 }
6617 }
6618
6620 QualType R = TInfo->getType();
6621
6624 D.setInvalidType();
6625
6626 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6628
6629 // See if this is a redefinition of a variable in the same scope.
6630 if (!D.getCXXScopeSpec().isSet()) {
6631 bool IsLinkageLookup = false;
6632 bool CreateBuiltins = false;
6633
6634 // If the declaration we're planning to build will be a function
6635 // or object with linkage, then look for another declaration with
6636 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6637 //
6638 // If the declaration we're planning to build will be declared with
6639 // external linkage in the translation unit, create any builtin with
6640 // the same name.
6642 /* Do nothing*/;
6643 else if (CurContext->isFunctionOrMethod() &&
6645 R->isFunctionType())) {
6646 IsLinkageLookup = true;
6647 CreateBuiltins =
6648 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6649 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6651 CreateBuiltins = true;
6652
6653 if (IsLinkageLookup) {
6655 Previous.setRedeclarationKind(
6657 }
6658
6659 LookupName(Previous, S, CreateBuiltins);
6660 } else { // Something like "int foo::x;"
6662
6663 // C++ [dcl.meaning]p1:
6664 // When the declarator-id is qualified, the declaration shall refer to a
6665 // previously declared member of the class or namespace to which the
6666 // qualifier refers (or, in the case of a namespace, of an element of the
6667 // inline namespace set of that namespace (7.3.1)) or to a specialization
6668 // thereof; [...]
6669 //
6670 // Note that we already checked the context above, and that we do not have
6671 // enough information to make sure that Previous contains the declaration
6672 // we want to match. For example, given:
6673 //
6674 // class X {
6675 // void f();
6676 // void f(float);
6677 // };
6678 //
6679 // void X::f(int) { } // ill-formed
6680 //
6681 // In this case, Previous will point to the overload set
6682 // containing the two f's declared in X, but neither of them
6683 // matches.
6684
6686 }
6687
6688 if (auto *TPD = Previous.getAsSingle<NamedDecl>();
6689 TPD && TPD->isTemplateParameter()) {
6690 // Older versions of clang allowed the names of function/variable templates
6691 // to shadow the names of their template parameters. For the compatibility
6692 // purposes we detect such cases and issue a default-to-error warning that
6693 // can be disabled with -Wno-strict-primary-template-shadow.
6694 if (!D.isInvalidType()) {
6695 bool AllowForCompatibility = false;
6696 if (Scope *DeclParent = S->getDeclParent();
6697 Scope *TemplateParamParent = S->getTemplateParamParent()) {
6698 AllowForCompatibility = DeclParent->Contains(*TemplateParamParent) &&
6699 TemplateParamParent->isDeclScope(TPD);
6700 }
6702 AllowForCompatibility);
6703 }
6704
6705 // Just pretend that we didn't see the previous declaration.
6706 Previous.clear();
6707 }
6708
6709 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6710 // Forget that the previous declaration is the injected-class-name.
6711 Previous.clear();
6712
6713 // In C++, the previous declaration we find might be a tag type
6714 // (class or enum). In this case, the new declaration will hide the
6715 // tag type. Note that this applies to functions, function templates, and
6716 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6717 if (Previous.isSingleTagDecl() &&
6719 (TemplateParamLists.size() == 0 || R->isFunctionType()))
6720 Previous.clear();
6721
6722 // Check that there are no default arguments other than in the parameters
6723 // of a function declaration (C++ only).
6724 if (getLangOpts().CPlusPlus)
6726
6727 /// Get the innermost enclosing declaration scope.
6728 S = S->getDeclParent();
6729
6730 NamedDecl *New;
6731
6732 bool AddToScope = true;
6734 if (TemplateParamLists.size()) {
6735 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6736 return nullptr;
6737 }
6738
6739 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6740 } else if (R->isFunctionType()) {
6741 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6742 TemplateParamLists,
6743 AddToScope);
6744 } else {
6745 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6746 AddToScope);
6747 }
6748
6749 if (!New)
6750 return nullptr;
6751
6753
6754 // If this has an identifier and is not a function template specialization,
6755 // add it to the scope stack.
6756 if (New->getDeclName() && AddToScope)
6758
6759 if (OpenMP().isInOpenMPDeclareTargetContext())
6761
6762 return New;
6763}
6764
6765/// Helper method to turn variable array types into constant array
6766/// types in certain situations which would otherwise be errors (for
6767/// GCC compatibility).
6769 ASTContext &Context,
6770 bool &SizeIsNegative,
6771 llvm::APSInt &Oversized) {
6772 // This method tries to turn a variable array into a constant
6773 // array even when the size isn't an ICE. This is necessary
6774 // for compatibility with code that depends on gcc's buggy
6775 // constant expression folding, like struct {char x[(int)(char*)2];}
6776 SizeIsNegative = false;
6777 Oversized = 0;
6778
6779 if (T->isDependentType())
6780 return QualType();
6781
6783 const Type *Ty = Qs.strip(T);
6784
6785 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6786 QualType Pointee = PTy->getPointeeType();
6787 QualType FixedType =
6788 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6789 Oversized);
6790 if (FixedType.isNull()) return FixedType;
6791 FixedType = Context.getPointerType(FixedType);
6792 return Qs.apply(Context, FixedType);
6793 }
6794 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6795 QualType Inner = PTy->getInnerType();
6796 QualType FixedType =
6797 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6798 Oversized);
6799 if (FixedType.isNull()) return FixedType;
6800 FixedType = Context.getParenType(FixedType);
6801 return Qs.apply(Context, FixedType);
6802 }
6803
6804 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6805 if (!VLATy)
6806 return QualType();
6807
6808 QualType ElemTy = VLATy->getElementType();
6809 if (ElemTy->isVariablyModifiedType()) {
6810 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6811 SizeIsNegative, Oversized);
6812 if (ElemTy.isNull())
6813 return QualType();
6814 }
6815
6817 if (!VLATy->getSizeExpr() ||
6818 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6819 return QualType();
6820
6821 llvm::APSInt Res = Result.Val.getInt();
6822
6823 // Check whether the array size is negative.
6824 if (Res.isSigned() && Res.isNegative()) {
6825 SizeIsNegative = true;
6826 return QualType();
6827 }
6828
6829 // Check whether the array is too large to be addressed.
6830 unsigned ActiveSizeBits =
6831 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6832 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6833 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6834 : Res.getActiveBits();
6835 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6836 Oversized = std::move(Res);
6837 return QualType();
6838 }
6839
6840 QualType FoldedArrayType = Context.getConstantArrayType(
6841 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0);
6842 return Qs.apply(Context, FoldedArrayType);
6843}
6844
6845static void
6847 SrcTL = SrcTL.getUnqualifiedLoc();
6848 DstTL = DstTL.getUnqualifiedLoc();
6849 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6850 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6851 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6852 DstPTL.getPointeeLoc());
6853 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6854 return;
6855 }
6856 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6857 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6858 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6859 DstPTL.getInnerLoc());
6860 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6861 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6862 return;
6863 }
6864 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6865 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6866 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6867 TypeLoc DstElemTL = DstATL.getElementLoc();
6868 if (VariableArrayTypeLoc SrcElemATL =
6869 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6870 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6871 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6872 } else {
6873 DstElemTL.initializeFullCopy(SrcElemTL);
6874 }
6875 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6876 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6877 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6878}
6879
6880/// Helper method to turn variable array types into constant array
6881/// types in certain situations which would otherwise be errors (for
6882/// GCC compatibility).
6883static TypeSourceInfo*
6885 ASTContext &Context,
6886 bool &SizeIsNegative,
6887 llvm::APSInt &Oversized) {
6888 QualType FixedTy
6889 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6890 SizeIsNegative, Oversized);
6891 if (FixedTy.isNull())
6892 return nullptr;
6893 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6895 FixedTInfo->getTypeLoc());
6896 return FixedTInfo;
6897}
6898
6901 unsigned FailedFoldDiagID) {
6902 bool SizeIsNegative;
6903 llvm::APSInt Oversized;
6905 TInfo, Context, SizeIsNegative, Oversized);
6906 if (FixedTInfo) {
6907 Diag(Loc, diag::ext_vla_folded_to_constant);
6908 TInfo = FixedTInfo;
6909 T = FixedTInfo->getType();
6910 return true;
6911 }
6912
6913 if (SizeIsNegative)
6914 Diag(Loc, diag::err_typecheck_negative_array_size);
6915 else if (Oversized.getBoolValue())
6916 Diag(Loc, diag::err_array_too_large) << toString(
6917 Oversized, 10, Oversized.isSigned(), /*formatAsCLiteral=*/false,
6918 /*UpperCase=*/false, /*InsertSeparators=*/true);
6919 else if (FailedFoldDiagID)
6920 Diag(Loc, FailedFoldDiagID);
6921 return false;
6922}
6923
6924void
6926 if (!getLangOpts().CPlusPlus &&
6928 // Don't need to track declarations in the TU in C.
6929 return;
6930
6931 // Note that we have a locally-scoped external with this name.
6932 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6933}
6934
6936 // FIXME: We can have multiple results via __attribute__((overloadable)).
6937 auto Result = Context.getExternCContextDecl()->lookup(Name);
6938 return Result.empty() ? nullptr : *Result.begin();
6939}
6940
6942 // FIXME: We should probably indicate the identifier in question to avoid
6943 // confusion for constructs like "virtual int a(), b;"
6944 if (DS.isVirtualSpecified())
6946 diag::err_virtual_non_function);
6947
6948 if (DS.hasExplicitSpecifier())
6950 diag::err_explicit_non_function);
6951
6952 if (DS.isNoreturnSpecified())
6954 diag::err_noreturn_non_function);
6955}
6956
6957NamedDecl*
6960 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6961 if (D.getCXXScopeSpec().isSet()) {
6962 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6963 << D.getCXXScopeSpec().getRange();
6964 D.setInvalidType();
6965 // Pretend we didn't see the scope specifier.
6966 DC = CurContext;
6967 Previous.clear();
6968 }
6969
6971
6974 (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus)
6975 ? diag::warn_ms_inline_non_function
6976 : diag::err_inline_non_function)
6977 << getLangOpts().CPlusPlus17;
6979 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6980 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6981
6985 diag::err_deduction_guide_invalid_specifier)
6986 << "typedef";
6987 else
6988 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6989 << D.getName().getSourceRange();
6990 return nullptr;
6991 }
6992
6993 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6994 if (!NewTD) return nullptr;
6995
6996 // Handle attributes prior to checking for duplicates in MergeVarDecl
6997 ProcessDeclAttributes(S, NewTD, D);
6998
7000
7001 bool Redeclaration = D.isRedeclaration();
7004 return ND;
7005}
7006
7007void
7009 // C99 6.7.7p2: If a typedef name specifies a variably modified type
7010 // then it shall have block scope.
7011 // Note that variably modified types must be fixed before merging the decl so
7012 // that redeclarations will match.
7013 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
7014 QualType T = TInfo->getType();
7015 if (T->isVariablyModifiedType()) {
7017
7018 if (S->getFnParent() == nullptr) {
7019 bool SizeIsNegative;
7020 llvm::APSInt Oversized;
7021 TypeSourceInfo *FixedTInfo =
7023 SizeIsNegative,
7024 Oversized);
7025 if (FixedTInfo) {
7026 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
7027 NewTD->setTypeSourceInfo(FixedTInfo);
7028 } else {
7029 if (SizeIsNegative)
7030 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
7031 else if (T->isVariableArrayType())
7032 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
7033 else if (Oversized.getBoolValue())
7034 Diag(NewTD->getLocation(), diag::err_array_too_large)
7035 << toString(Oversized, 10);
7036 else
7037 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
7038 NewTD->setInvalidDecl();
7039 }
7040 }
7041 }
7042}
7043
7044NamedDecl*
7047
7048 // Find the shadowed declaration before filtering for scope.
7049 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
7050
7051 // Merge the decl with the existing one if appropriate. If the decl is
7052 // in an outer scope, it isn't the same thing.
7053 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
7054 /*AllowInlineNamespace*/false);
7056 if (!Previous.empty()) {
7057 Redeclaration = true;
7058 MergeTypedefNameDecl(S, NewTD, Previous);
7059 } else {
7061 }
7062
7063 if (ShadowedDecl && !Redeclaration)
7064 CheckShadow(NewTD, ShadowedDecl, Previous);
7065
7066 // If this is the C FILE type, notify the AST context.
7067 if (IdentifierInfo *II = NewTD->getIdentifier())
7068 if (!NewTD->isInvalidDecl() &&
7070 switch (II->getNotableIdentifierID()) {
7071 case tok::NotableIdentifierKind::FILE:
7072 Context.setFILEDecl(NewTD);
7073 break;
7074 case tok::NotableIdentifierKind::jmp_buf:
7075 Context.setjmp_bufDecl(NewTD);
7076 break;
7077 case tok::NotableIdentifierKind::sigjmp_buf:
7078 Context.setsigjmp_bufDecl(NewTD);
7079 break;
7080 case tok::NotableIdentifierKind::ucontext_t:
7081 Context.setucontext_tDecl(NewTD);
7082 break;
7083 case tok::NotableIdentifierKind::float_t:
7084 case tok::NotableIdentifierKind::double_t:
7085 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context));
7086 break;
7087 default:
7088 break;
7089 }
7090 }
7091
7092 return NewTD;
7093}
7094
7095/// Determines whether the given declaration is an out-of-scope
7096/// previous declaration.
7097///
7098/// This routine should be invoked when name lookup has found a
7099/// previous declaration (PrevDecl) that is not in the scope where a
7100/// new declaration by the same name is being introduced. If the new
7101/// declaration occurs in a local scope, previous declarations with
7102/// linkage may still be considered previous declarations (C99
7103/// 6.2.2p4-5, C++ [basic.link]p6).
7104///
7105/// \param PrevDecl the previous declaration found by name
7106/// lookup
7107///
7108/// \param DC the context in which the new declaration is being
7109/// declared.
7110///
7111/// \returns true if PrevDecl is an out-of-scope previous declaration
7112/// for a new delcaration with the same name.
7113static bool
7115 ASTContext &Context) {
7116 if (!PrevDecl)
7117 return false;
7118
7119 if (!PrevDecl->hasLinkage())
7120 return false;
7121
7122 if (Context.getLangOpts().CPlusPlus) {
7123 // C++ [basic.link]p6:
7124 // If there is a visible declaration of an entity with linkage
7125 // having the same name and type, ignoring entities declared
7126 // outside the innermost enclosing namespace scope, the block
7127 // scope declaration declares that same entity and receives the
7128 // linkage of the previous declaration.
7129 DeclContext *OuterContext = DC->getRedeclContext();
7130 if (!OuterContext->isFunctionOrMethod())
7131 // This rule only applies to block-scope declarations.
7132 return false;
7133
7134 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
7135 if (PrevOuterContext->isRecord())
7136 // We found a member function: ignore it.
7137 return false;
7138
7139 // Find the innermost enclosing namespace for the new and
7140 // previous declarations.
7141 OuterContext = OuterContext->getEnclosingNamespaceContext();
7142 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
7143
7144 // The previous declaration is in a different namespace, so it
7145 // isn't the same function.
7146 if (!OuterContext->Equals(PrevOuterContext))
7147 return false;
7148 }
7149
7150 return true;
7151}
7152
7154 CXXScopeSpec &SS = D.getCXXScopeSpec();
7155 if (!SS.isSet()) return;
7157}
7158
7161 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
7162 // __opencl_c_program_scope_global_variables feature, the address space
7163 // for a variable at program scope or a static or extern variable inside
7164 // a function are inferred to be __global.
7165 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
7166 Var->hasGlobalStorage())
7167 ImplAS = LangAS::opencl_global;
7168 Var->assignAddressSpace(Context, ImplAS);
7169}
7170
7171static void checkWeakAttr(Sema &S, NamedDecl &ND) {
7172 // 'weak' only applies to declarations with external linkage.
7173 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
7174 if (!ND.isExternallyVisible()) {
7175 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
7176 ND.dropAttr<WeakAttr>();
7177 }
7178 }
7179}
7180
7181static void checkWeakRefAttr(Sema &S, NamedDecl &ND) {
7182 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
7183 if (ND.isExternallyVisible()) {
7184 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
7185 ND.dropAttrs<WeakRefAttr, AliasAttr>();
7186 }
7187 }
7188}
7189
7190static void checkAliasAttr(Sema &S, NamedDecl &ND) {
7191 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
7192 if (VD->hasInit()) {
7193 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
7194 assert(VD->isThisDeclarationADefinition() &&
7195 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
7196 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
7197 VD->dropAttr<AliasAttr>();
7198 }
7199 }
7200 }
7201}
7202
7203static void checkSelectAnyAttr(Sema &S, NamedDecl &ND) {
7204 // 'selectany' only applies to externally visible variable declarations.
7205 // It does not apply to functions.
7206 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
7207 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
7208 S.Diag(Attr->getLocation(),
7209 diag::err_attribute_selectany_non_extern_data);
7210 ND.dropAttr<SelectAnyAttr>();
7211 }
7212 }
7213}
7214
7216 if (HybridPatchableAttr *Attr = ND.getAttr<HybridPatchableAttr>()) {
7217 if (!ND.isExternallyVisible())
7218 S.Diag(Attr->getLocation(),
7219 diag::warn_attribute_hybrid_patchable_non_extern);
7220 }
7221}
7222
7224 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
7225 auto *VD = dyn_cast<VarDecl>(&ND);
7226 bool IsAnonymousNS = false;
7227 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
7228 if (VD) {
7229 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
7230 while (NS && !IsAnonymousNS) {
7231 IsAnonymousNS = NS->isAnonymousNamespace();
7232 NS = dyn_cast<NamespaceDecl>(NS->getParent());
7233 }
7234 }
7235 // dll attributes require external linkage. Static locals may have external
7236 // linkage but still cannot be explicitly imported or exported.
7237 // In Microsoft mode, a variable defined in anonymous namespace must have
7238 // external linkage in order to be exported.
7239 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
7240 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
7241 (!AnonNSInMicrosoftMode &&
7242 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
7243 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
7244 << &ND << Attr;
7245 ND.setInvalidDecl();
7246 }
7247 }
7248}
7249
7251 // Check the attributes on the function type and function params, if any.
7252 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
7253 FD = FD->getMostRecentDecl();
7254 // Don't declare this variable in the second operand of the for-statement;
7255 // GCC miscompiles that by ending its lifetime before evaluating the
7256 // third operand. See gcc.gnu.org/PR86769.
7258 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
7259 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
7260 TL = ATL.getModifiedLoc()) {
7261 // The [[lifetimebound]] attribute can be applied to the implicit object
7262 // parameter of a non-static member function (other than a ctor or dtor)
7263 // by applying it to the function type.
7264 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
7265 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
7266 int NoImplicitObjectError = -1;
7267 if (!MD)
7268 NoImplicitObjectError = 0;
7269 else if (MD->isStatic())
7270 NoImplicitObjectError = 1;
7271 else if (MD->isExplicitObjectMemberFunction())
7272 NoImplicitObjectError = 2;
7273 if (NoImplicitObjectError != -1) {
7274 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
7275 << NoImplicitObjectError << A->getRange();
7276 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
7277 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
7278 << isa<CXXDestructorDecl>(MD) << A->getRange();
7279 } else if (MD->getReturnType()->isVoidType()) {
7280 S.Diag(
7281 MD->getLocation(),
7282 diag::
7283 err_lifetimebound_implicit_object_parameter_void_return_type);
7284 }
7285 }
7286 }
7287
7288 for (unsigned int I = 0; I < FD->getNumParams(); ++I) {
7289 const ParmVarDecl *P = FD->getParamDecl(I);
7290
7291 // The [[lifetimebound]] attribute can be applied to a function parameter
7292 // only if the function returns a value.
7293 if (auto *A = P->getAttr<LifetimeBoundAttr>()) {
7294 if (!isa<CXXConstructorDecl>(FD) && FD->getReturnType()->isVoidType()) {
7295 S.Diag(A->getLocation(),
7296 diag::err_lifetimebound_parameter_void_return_type);
7297 }
7298 }
7299 }
7300 }
7301}
7302
7304 if (ND.hasAttr<ModularFormatAttr>() && !ND.hasAttr<FormatAttr>())
7305 S.Diag(ND.getLocation(), diag::err_modular_format_attribute_no_format);
7306}
7307
7309 // Ensure that an auto decl is deduced otherwise the checks below might cache
7310 // the wrong linkage.
7311 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
7312
7313 checkWeakAttr(S, ND);
7314 checkWeakRefAttr(S, ND);
7315 checkAliasAttr(S, ND);
7316 checkSelectAnyAttr(S, ND);
7318 checkInheritableAttr(S, ND);
7320}
7321
7323 NamedDecl *NewDecl,
7324 bool IsSpecialization,
7325 bool IsDefinition) {
7326 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
7327 return;
7328
7329 bool IsTemplate = false;
7330 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
7331 OldDecl = OldTD->getTemplatedDecl();
7332 IsTemplate = true;
7333 if (!IsSpecialization)
7334 IsDefinition = false;
7335 }
7336 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
7337 NewDecl = NewTD->getTemplatedDecl();
7338 IsTemplate = true;
7339 }
7340
7341 if (!OldDecl || !NewDecl)
7342 return;
7343
7344 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
7345 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
7346 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
7347 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
7348
7349 // dllimport and dllexport are inheritable attributes so we have to exclude
7350 // inherited attribute instances.
7351 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
7352 (NewExportAttr && !NewExportAttr->isInherited());
7353
7354 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
7355 // the only exception being explicit specializations.
7356 // Implicitly generated declarations are also excluded for now because there
7357 // is no other way to switch these to use dllimport or dllexport.
7358 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
7359
7360 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
7361 // Allow with a warning for free functions and global variables.
7362 bool JustWarn = false;
7363 if (!OldDecl->isCXXClassMember()) {
7364 auto *VD = dyn_cast<VarDecl>(OldDecl);
7365 if (VD && !VD->getDescribedVarTemplate())
7366 JustWarn = true;
7367 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
7368 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
7369 JustWarn = true;
7370 }
7371
7372 // We cannot change a declaration that's been used because IR has already
7373 // been emitted. Dllimported functions will still work though (modulo
7374 // address equality) as they can use the thunk.
7375 if (OldDecl->isUsed())
7376 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
7377 JustWarn = false;
7378
7379 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
7380 : diag::err_attribute_dll_redeclaration;
7381 S.Diag(NewDecl->getLocation(), DiagID)
7382 << NewDecl
7383 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
7384 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7385 if (!JustWarn) {
7386 NewDecl->setInvalidDecl();
7387 return;
7388 }
7389 }
7390
7391 // A redeclaration is not allowed to drop a dllimport attribute, the only
7392 // exceptions being inline function definitions (except for function
7393 // templates), local extern declarations, qualified friend declarations or
7394 // special MSVC extension: in the last case, the declaration is treated as if
7395 // it were marked dllexport.
7396 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
7397 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
7398 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
7399 // Ignore static data because out-of-line definitions are diagnosed
7400 // separately.
7401 IsStaticDataMember = VD->isStaticDataMember();
7402 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
7404 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
7405 IsInline = FD->isInlined();
7406 IsQualifiedFriend = FD->getQualifier() &&
7407 FD->getFriendObjectKind() == Decl::FOK_Declared;
7408 }
7409
7410 if (OldImportAttr && !HasNewAttr &&
7411 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
7412 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
7413 if (IsMicrosoftABI && IsDefinition) {
7414 if (IsSpecialization) {
7415 S.Diag(
7416 NewDecl->getLocation(),
7417 diag::err_attribute_dllimport_function_specialization_definition);
7418 S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
7419 NewDecl->dropAttr<DLLImportAttr>();
7420 } else {
7421 S.Diag(NewDecl->getLocation(),
7422 diag::warn_redeclaration_without_import_attribute)
7423 << NewDecl;
7424 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7425 NewDecl->dropAttr<DLLImportAttr>();
7426 NewDecl->addAttr(DLLExportAttr::CreateImplicit(
7427 S.Context, NewImportAttr->getRange()));
7428 }
7429 } else if (IsMicrosoftABI && IsSpecialization) {
7430 assert(!IsDefinition);
7431 // MSVC allows this. Keep the inherited attribute.
7432 } else {
7433 S.Diag(NewDecl->getLocation(),
7434 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7435 << NewDecl << OldImportAttr;
7436 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
7437 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
7438 OldDecl->dropAttr<DLLImportAttr>();
7439 NewDecl->dropAttr<DLLImportAttr>();
7440 }
7441 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
7442 // In MinGW, seeing a function declared inline drops the dllimport
7443 // attribute.
7444 OldDecl->dropAttr<DLLImportAttr>();
7445 NewDecl->dropAttr<DLLImportAttr>();
7446 S.Diag(NewDecl->getLocation(),
7447 diag::warn_dllimport_dropped_from_inline_function)
7448 << NewDecl << OldImportAttr;
7449 }
7450
7451 // A specialization of a class template member function is processed here
7452 // since it's a redeclaration. If the parent class is dllexport, the
7453 // specialization inherits that attribute. This doesn't happen automatically
7454 // since the parent class isn't instantiated until later.
7455 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
7456 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
7457 !NewImportAttr && !NewExportAttr) {
7458 if (const DLLExportAttr *ParentExportAttr =
7459 MD->getParent()->getAttr<DLLExportAttr>()) {
7460 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
7461 NewAttr->setInherited(true);
7462 NewDecl->addAttr(NewAttr);
7463 }
7464 }
7465 }
7466}
7467
7468/// Given that we are within the definition of the given function,
7469/// will that definition behave like C99's 'inline', where the
7470/// definition is discarded except for optimization purposes?
7472 // Try to avoid calling GetGVALinkageForFunction.
7473
7474 // All cases of this require the 'inline' keyword.
7475 if (!FD->isInlined()) return false;
7476
7477 // This is only possible in C++ with the gnu_inline attribute.
7478 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
7479 return false;
7480
7481 // Okay, go ahead and call the relatively-more-expensive function.
7483}
7484
7485/// Determine whether a variable is extern "C" prior to attaching
7486/// an initializer. We can't just call isExternC() here, because that
7487/// will also compute and cache whether the declaration is externally
7488/// visible, which might change when we attach the initializer.
7489///
7490/// This can only be used if the declaration is known to not be a
7491/// redeclaration of an internal linkage declaration.
7492///
7493/// For instance:
7494///
7495/// auto x = []{};
7496///
7497/// Attaching the initializer here makes this declaration not externally
7498/// visible, because its type has internal linkage.
7499///
7500/// FIXME: This is a hack.
7501template<typename T>
7502static bool isIncompleteDeclExternC(Sema &S, const T *D) {
7503 if (S.getLangOpts().CPlusPlus) {
7504 // In C++, the overloadable attribute negates the effects of extern "C".
7505 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
7506 return false;
7507
7508 // So do CUDA's host/device attributes.
7509 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
7510 D->template hasAttr<CUDAHostAttr>()))
7511 return false;
7512 }
7513 return D->isExternC();
7514}
7515
7516static bool shouldConsiderLinkage(const VarDecl *VD) {
7517 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
7520 return VD->hasExternalStorage();
7521 if (DC->isFileContext())
7522 return true;
7523 if (DC->isRecord())
7524 return false;
7525 if (DC->getDeclKind() == Decl::HLSLBuffer)
7526 return false;
7527
7529 return false;
7530 llvm_unreachable("Unexpected context");
7531}
7532
7533static bool shouldConsiderLinkage(const FunctionDecl *FD) {
7534 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
7535 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
7537 return true;
7538 if (DC->isRecord() || isa<CXXExpansionStmtDecl>(DC))
7539 return false;
7540 llvm_unreachable("Unexpected context");
7541}
7542
7543static bool hasParsedAttr(Scope *S, const Declarator &PD,
7544 ParsedAttr::Kind Kind) {
7545 // Check decl attributes on the DeclSpec.
7546 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
7547 return true;
7548
7549 // Walk the declarator structure, checking decl attributes that were in a type
7550 // position to the decl itself.
7551 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
7552 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
7553 return true;
7554 }
7555
7556 // Finally, check attributes on the decl itself.
7557 return PD.getAttributes().hasAttribute(Kind) ||
7559}
7560
7562 if (!DC->isFunctionOrMethod())
7563 return false;
7564
7565 // If this is a local extern function or variable declared within a function
7566 // template, don't add it into the enclosing namespace scope until it is
7567 // instantiated; it might have a dependent type right now.
7568 if (DC->isDependentContext())
7569 return true;
7570
7571 // C++11 [basic.link]p7:
7572 // When a block scope declaration of an entity with linkage is not found to
7573 // refer to some other declaration, then that entity is a member of the
7574 // innermost enclosing namespace.
7575 //
7576 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
7577 // semantically-enclosing namespace, not a lexically-enclosing one.
7578 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
7579 DC = DC->getParent();
7580 return true;
7581}
7582
7583/// Returns true if given declaration has external C language linkage.
7584static bool isDeclExternC(const Decl *D) {
7585 if (const auto *FD = dyn_cast<FunctionDecl>(D))
7586 return FD->isExternC();
7587 if (const auto *VD = dyn_cast<VarDecl>(D))
7588 return VD->isExternC();
7589
7590 llvm_unreachable("Unknown type of decl!");
7591}
7592
7593/// Returns true if there hasn't been any invalid type diagnosed.
7594static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
7595 DeclContext *DC = NewVD->getDeclContext();
7596 QualType R = NewVD->getType();
7597
7598 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
7599 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
7600 // argument.
7601 if (R->isImageType() || R->isPipeType()) {
7602 Se.Diag(NewVD->getLocation(),
7603 diag::err_opencl_type_can_only_be_used_as_function_parameter)
7604 << R;
7605 NewVD->setInvalidDecl();
7606 return false;
7607 }
7608
7609 // OpenCL v1.2 s6.9.r:
7610 // The event type cannot be used to declare a program scope variable.
7611 // OpenCL v2.0 s6.9.q:
7612 // The clk_event_t and reserve_id_t types cannot be declared in program
7613 // scope.
7614 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
7615 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
7616 Se.Diag(NewVD->getLocation(),
7617 diag::err_invalid_type_for_program_scope_var)
7618 << R;
7619 NewVD->setInvalidDecl();
7620 return false;
7621 }
7622 }
7623
7624 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7625 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7626 Se.getLangOpts())) {
7627 QualType NR = R.getCanonicalType();
7628 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7629 NR->isReferenceType()) {
7632 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7633 << NR->isReferenceType();
7634 NewVD->setInvalidDecl();
7635 return false;
7636 }
7637 NR = NR->getPointeeType();
7638 }
7639 }
7640
7641 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7642 Se.getLangOpts())) {
7643 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7644 // half array type (unless the cl_khr_fp16 extension is enabled).
7645 if (Se.Context.getBaseElementType(R)->isHalfType()) {
7646 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7647 NewVD->setInvalidDecl();
7648 return false;
7649 }
7650 }
7651
7652 // OpenCL v1.2 s6.9.r:
7653 // The event type cannot be used with the __local, __constant and __global
7654 // address space qualifiers.
7655 if (R->isEventT()) {
7656 if (R.getAddressSpace() != LangAS::opencl_private) {
7657 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7658 NewVD->setInvalidDecl();
7659 return false;
7660 }
7661 }
7662
7663 if (R->isSamplerT()) {
7664 // OpenCL v1.2 s6.9.b p4:
7665 // The sampler type cannot be used with the __local and __global address
7666 // space qualifiers.
7667 if (R.getAddressSpace() == LangAS::opencl_local ||
7668 R.getAddressSpace() == LangAS::opencl_global) {
7669 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7670 NewVD->setInvalidDecl();
7671 }
7672
7673 // OpenCL v1.2 s6.12.14.1:
7674 // A global sampler must be declared with either the constant address
7675 // space qualifier or with the const qualifier.
7676 if (DC->isTranslationUnit() &&
7677 !(R.getAddressSpace() == LangAS::opencl_constant ||
7678 R.isConstQualified())) {
7679 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7680 NewVD->setInvalidDecl();
7681 }
7682 if (NewVD->isInvalidDecl())
7683 return false;
7684 }
7685
7686 return true;
7687}
7688
7689template <typename AttrTy>
7690static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7691 const TypedefNameDecl *TND = TT->getDecl();
7692 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7693 AttrTy *Clone = Attribute->clone(S.Context);
7694 Clone->setInherited(true);
7695 D->addAttr(Clone);
7696 }
7697}
7698
7699// This function emits warning and a corresponding note based on the
7700// ReadOnlyPlacementAttr attribute. The warning checks that all global variable
7701// declarations of an annotated type must be const qualified.
7703 QualType VarType = VD->getType().getCanonicalType();
7704
7705 // Ignore local declarations (for now) and those with const qualification.
7706 // TODO: Local variables should not be allowed if their type declaration has
7707 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
7708 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
7709 return;
7710
7711 if (VarType->isArrayType()) {
7712 // Retrieve element type for array declarations.
7713 VarType = S.getASTContext().getBaseElementType(VarType);
7714 }
7715
7716 const RecordDecl *RD = VarType->getAsRecordDecl();
7717
7718 // Check if the record declaration is present and if it has any attributes.
7719 if (RD == nullptr)
7720 return;
7721
7722 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
7723 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
7724 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
7725 return;
7726 }
7727}
7728
7730 assert((isa<FunctionDecl>(NewD) || isa<VarDecl>(NewD)) &&
7731 "NewD is not a function or variable");
7732
7733 if (PendingExportedNames.empty())
7734 return;
7735 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(NewD)) {
7736 if (getLangOpts().CPlusPlus && !FD->isExternC())
7737 return;
7738 }
7739 IdentifierInfo *IdentName = NewD->getIdentifier();
7740 if (IdentName == nullptr)
7741 return;
7742 auto PendingName = PendingExportedNames.find(IdentName);
7743 if (PendingName != PendingExportedNames.end()) {
7744 auto &Label = PendingName->second;
7745 if (!Label.Used) {
7746 Label.Used = true;
7747 if (NewD->hasExternalFormalLinkage())
7748 mergeVisibilityType(NewD, Label.NameLoc, VisibilityAttr::Default);
7749 else
7750 Diag(Label.NameLoc, diag::warn_pragma_not_applied) << "export" << NewD;
7751 }
7752 }
7753}
7754
7755// Checks if VD is declared at global scope or with C language linkage.
7756static bool isMainVar(DeclarationName Name, VarDecl *VD) {
7757 return Name.getAsIdentifierInfo() &&
7758 Name.getAsIdentifierInfo()->isStr("main") &&
7759 !VD->getDescribedVarTemplate() &&
7760 (VD->getDeclContext()->getRedeclContext()->isTranslationUnit() ||
7761 VD->isExternC());
7762}
7763
7764void Sema::CheckAsmLabel(Scope *S, Expr *E, StorageClass SC,
7765 TypeSourceInfo *TInfo, VarDecl *NewVD) {
7766
7767 // Quickly return if the function does not have an `asm` attribute.
7768 if (E == nullptr)
7769 return;
7770
7771 // The parser guarantees this is a string.
7772 StringLiteral *SE = cast<StringLiteral>(E);
7773 StringRef Label = SE->getString();
7774 QualType R = TInfo->getType();
7775 if (R->isIncompleteType())
7776 return;
7777 if (S->getFnParent() != nullptr) {
7778 switch (SC) {
7779 case SC_None:
7780 case SC_Auto:
7781 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7782 break;
7783 case SC_Register:
7784 // Local Named register
7785 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7787 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7788 break;
7789 case SC_Static:
7790 case SC_Extern:
7791 case SC_PrivateExtern:
7792 break;
7793 }
7794 } else if (SC == SC_Register) {
7795 // Global Named register
7796 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7797 const auto &TI = Context.getTargetInfo();
7798 bool HasSizeMismatch;
7799
7800 if (!TI.isValidGCCRegisterName(Label))
7801 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7802 else if (!TI.validateGlobalRegisterVariable(Label, Context.getTypeSize(R),
7803 HasSizeMismatch))
7804 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7805 else if (HasSizeMismatch)
7806 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7807 }
7808
7809 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7810 Diag(TInfo->getTypeLoc().getBeginLoc(),
7811 diag::err_asm_unsupported_register_type)
7812 << TInfo->getTypeLoc().getSourceRange();
7813 NewVD->setInvalidDecl(true);
7814 }
7815 }
7816}
7817
7819 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7820 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7821 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7822 QualType R = TInfo->getType();
7824
7826 bool IsPlaceholderVariable = false;
7827
7828 if (D.isDecompositionDeclarator()) {
7829 // Take the name of the first declarator as our name for diagnostic
7830 // purposes.
7831 auto &Decomp = D.getDecompositionDeclarator();
7832 if (!Decomp.bindings().empty()) {
7833 II = Decomp.bindings()[0].Name;
7834 Name = II;
7835 }
7836 } else if (!II) {
7837 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7838 return nullptr;
7839 }
7840
7841
7844 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) &&
7845 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) {
7846
7847 IsPlaceholderVariable = true;
7848
7849 if (!Previous.empty()) {
7850 NamedDecl *PrevDecl = *Previous.begin();
7851 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals(
7852 DC->getRedeclContext());
7853 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) {
7854 IsPlaceholderVariable = !isa<ParmVarDecl>(PrevDecl);
7855 if (IsPlaceholderVariable)
7857 }
7858 }
7859 }
7860
7861 // dllimport globals without explicit storage class are treated as extern. We
7862 // have to change the storage class this early to get the right DeclContext.
7863 if (SC == SC_None && !DC->isRecord() &&
7864 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7865 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7866 SC = SC_Extern;
7867
7868 DeclContext *OriginalDC = DC;
7869 bool IsLocalExternDecl = SC == SC_Extern &&
7871
7872 if (SCSpec == DeclSpec::SCS_mutable) {
7873 // mutable can only appear on non-static class members, so it's always
7874 // an error here
7875 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7876 D.setInvalidType();
7877 SC = SC_None;
7878 }
7879
7880 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7881 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7883 // In C++11, the 'register' storage class specifier is deprecated.
7884 // Suppress the warning in system macros, it's used in macros in some
7885 // popular C system headers, such as in glibc's htonl() macro.
7887 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7888 : diag::warn_deprecated_register)
7890 }
7891
7893
7894 if (!DC->isRecord() && S->getFnParent() == nullptr) {
7895 // C99 6.9p2: The storage-class specifiers auto and register shall not
7896 // appear in the declaration specifiers in an external declaration.
7897 // Global Register+Asm is a GNU extension we support.
7898 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7899 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7900 D.setInvalidType();
7901 }
7902 }
7903
7904 // If this variable has a VLA type and an initializer, try to
7905 // fold to a constant-sized type. This is otherwise invalid.
7906 if (D.hasInitializer() && R->isVariableArrayType())
7908 /*DiagID=*/0);
7909
7910 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
7911 const AutoType *AT = TL.getTypePtr();
7912 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
7913 }
7914
7915 bool IsMemberSpecialization = false;
7916 bool IsVariableTemplateSpecialization = false;
7917 bool IsPartialSpecialization = false;
7918 bool IsVariableTemplate = false;
7919 VarDecl *NewVD = nullptr;
7920 VarTemplateDecl *NewTemplate = nullptr;
7921 TemplateParameterList *TemplateParams = nullptr;
7922 if (!getLangOpts().CPlusPlus) {
7924 II, R, TInfo, SC);
7925
7926 if (R->getContainedDeducedType())
7927 ParsingInitForAutoVars.insert(NewVD);
7928
7929 if (D.isInvalidType())
7930 NewVD->setInvalidDecl();
7931
7933 NewVD->hasLocalStorage())
7934 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7936 } else {
7937 bool Invalid = false;
7938 // Match up the template parameter lists with the scope specifier, then
7939 // determine whether we have a template or a template specialization.
7942 D.getCXXScopeSpec(),
7944 ? D.getName().TemplateId
7945 : nullptr,
7946 TemplateParamLists,
7947 /*never a friend*/ false, IsMemberSpecialization, Invalid);
7948
7949 if (TemplateParams) {
7950 if (DC->isDependentContext()) {
7951 ContextRAII SavedContext(*this, DC);
7953 Invalid = true;
7954 }
7955
7956 if (!TemplateParams->size() &&
7958 // There is an extraneous 'template<>' for this variable. Complain
7959 // about it, but allow the declaration of the variable.
7960 Diag(TemplateParams->getTemplateLoc(),
7961 diag::err_template_variable_noparams)
7962 << II
7963 << SourceRange(TemplateParams->getTemplateLoc(),
7964 TemplateParams->getRAngleLoc());
7965 TemplateParams = nullptr;
7966 } else {
7967 // Check that we can declare a template here.
7968 if (CheckTemplateDeclScope(S, TemplateParams))
7969 return nullptr;
7970
7972 // This is an explicit specialization or a partial specialization.
7973 IsVariableTemplateSpecialization = true;
7974 IsPartialSpecialization = TemplateParams->size() > 0;
7975 } else { // if (TemplateParams->size() > 0)
7976 // This is a template declaration.
7977 IsVariableTemplate = true;
7978
7979 // Only C++1y supports variable templates (N3651).
7980 DiagCompat(D.getIdentifierLoc(), diag_compat::variable_template);
7981 }
7982 }
7983 } else {
7984 // Check that we can declare a member specialization here.
7985 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7986 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7987 return nullptr;
7988 assert((Invalid ||
7990 "should have a 'template<>' for this decl");
7991 }
7992
7993 bool IsExplicitSpecialization =
7994 IsVariableTemplateSpecialization && !IsPartialSpecialization;
7995
7996 // C++ [temp.expl.spec]p2:
7997 // The declaration in an explicit-specialization shall not be an
7998 // export-declaration. An explicit specialization shall not use a
7999 // storage-class-specifier other than thread_local.
8000 //
8001 // We use the storage-class-specifier from DeclSpec because we may have
8002 // added implicit 'extern' for declarations with __declspec(dllimport)!
8003 if (SCSpec != DeclSpec::SCS_unspecified &&
8004 (IsExplicitSpecialization || IsMemberSpecialization)) {
8006 diag::ext_explicit_specialization_storage_class)
8008 }
8009
8010 if (CurContext->isRecord()) {
8011 if (SC == SC_Static) {
8012 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
8013 // Walk up the enclosing DeclContexts to check for any that are
8014 // incompatible with static data members.
8015 const DeclContext *FunctionOrMethod = nullptr;
8016 const CXXRecordDecl *AnonStruct = nullptr;
8017 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
8018 if (Ctxt->isFunctionOrMethod()) {
8019 FunctionOrMethod = Ctxt;
8020 break;
8021 }
8022 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
8023 if (ParentDecl && !ParentDecl->getDeclName()) {
8024 AnonStruct = ParentDecl;
8025 break;
8026 }
8027 }
8028 if (FunctionOrMethod) {
8029 // C++ [class.static.data]p5: A local class shall not have static
8030 // data members.
8032 diag::err_static_data_member_not_allowed_in_local_class)
8033 << Name << RD->getDeclName() << RD->getTagKind();
8034 Invalid = true;
8035 } else if (AnonStruct) {
8036 // C++ [class.static.data]p4: Unnamed classes and classes contained
8037 // directly or indirectly within unnamed classes shall not contain
8038 // static data members.
8040 diag::err_static_data_member_not_allowed_in_anon_struct)
8041 << Name << AnonStruct->getTagKind();
8042 Invalid = true;
8043 } else if (RD->isUnion()) {
8044 // C++98 [class.union]p1: If a union contains a static data member,
8045 // the program is ill-formed. C++11 drops this restriction.
8047 diag_compat::static_data_member_in_union)
8048 << Name;
8049 }
8050 }
8051 } else if (IsVariableTemplate || IsPartialSpecialization) {
8052 // There is no such thing as a member field template.
8053 Diag(D.getIdentifierLoc(), diag::err_template_member)
8054 << II << TemplateParams->getSourceRange();
8055 // Recover by pretending this is a static data member template.
8056 SC = SC_Static;
8057 }
8058 } else if (DC->isRecord()) {
8059 // This is an out-of-line definition of a static data member.
8060 switch (SC) {
8061 case SC_None:
8062 break;
8063 case SC_Static:
8065 diag::err_static_out_of_line)
8068 break;
8069 case SC_Auto:
8070 case SC_Register:
8071 case SC_Extern:
8072 // [dcl.stc] p2: The auto or register specifiers shall be applied only
8073 // to names of variables declared in a block or to function parameters.
8074 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
8075 // of class members
8076
8078 diag::err_storage_class_for_static_member)
8081 break;
8082 case SC_PrivateExtern:
8083 llvm_unreachable("C storage class in c++!");
8084 }
8085 }
8086
8087 if (IsVariableTemplateSpecialization) {
8088 SourceLocation TemplateKWLoc =
8089 TemplateParamLists.size() > 0
8090 ? TemplateParamLists[0]->getTemplateLoc()
8091 : SourceLocation();
8093 S, D, TInfo, Previous, TemplateKWLoc, TemplateParams, SC,
8095 if (Res.isInvalid())
8096 return nullptr;
8097 NewVD = cast<VarDecl>(Res.get());
8098 AddToScope = false;
8099 } else if (D.isDecompositionDeclarator()) {
8101 D.getIdentifierLoc(), D.getEndLoc(), R,
8102 TInfo, SC, Bindings);
8103 } else
8104 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
8105 D.getIdentifierLoc(), II, R, TInfo, SC);
8106
8107 // If this is supposed to be a variable template, create it as such.
8108 if (IsVariableTemplate) {
8109 NewTemplate =
8111 TemplateParams, NewVD);
8112 NewVD->setDescribedVarTemplate(NewTemplate);
8113 }
8114
8115 // If this decl has an auto type in need of deduction, make a note of the
8116 // Decl so we can diagnose uses of it in its own initializer.
8117 if (R->getContainedDeducedType())
8118 ParsingInitForAutoVars.insert(NewVD);
8119
8120 if (D.isInvalidType() || Invalid) {
8121 NewVD->setInvalidDecl();
8122 if (NewTemplate)
8123 NewTemplate->setInvalidDecl();
8124 }
8125
8126 SetNestedNameSpecifier(*this, NewVD, D);
8127
8128 // If we have any template parameter lists that don't directly belong to
8129 // the variable (matching the scope specifier), store them.
8130 // An explicit variable template specialization does not own any template
8131 // parameter lists.
8132 unsigned VDTemplateParamLists =
8133 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0;
8134 if (TemplateParamLists.size() > VDTemplateParamLists)
8136 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
8137 }
8138
8139 if (D.getDeclSpec().isInlineSpecified()) {
8140 if (!getLangOpts().CPlusPlus) {
8141 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
8142 << 0;
8143 } else if (CurContext->isFunctionOrMethod()) {
8144 // 'inline' is not allowed on block scope variable declaration.
8146 diag::err_inline_declaration_block_scope) << Name
8148 } else {
8150 getLangOpts().CPlusPlus17 ? diag::compat_cxx17_inline_variable
8151 : diag::compat_pre_cxx17_inline_variable);
8152 NewVD->setInlineSpecified();
8153 }
8154 }
8155
8156 // Set the lexical context. If the declarator has a C++ scope specifier, the
8157 // lexical context will be different from the semantic context.
8159 if (NewTemplate)
8160 NewTemplate->setLexicalDeclContext(CurContext);
8161
8162 if (IsLocalExternDecl) {
8164 for (auto *B : Bindings)
8165 B->setLocalExternDecl();
8166 else
8167 NewVD->setLocalExternDecl();
8168 }
8169
8170 bool EmitTLSUnsupportedError = false;
8172 // C++11 [dcl.stc]p4:
8173 // When thread_local is applied to a variable of block scope the
8174 // storage-class-specifier static is implied if it does not appear
8175 // explicitly.
8176 // Core issue: 'static' is not implied if the variable is declared
8177 // 'extern'.
8178 if (NewVD->hasLocalStorage() &&
8179 (SCSpec != DeclSpec::SCS_unspecified ||
8181 !DC->isFunctionOrMethod()))
8183 diag::err_thread_non_global)
8185 else if (!Context.getTargetInfo().isTLSSupported()) {
8186 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8187 // Postpone error emission until we've collected attributes required to
8188 // figure out whether it's a host or device variable and whether the
8189 // error should be ignored.
8190 EmitTLSUnsupportedError = true;
8191 // We still need to mark the variable as TLS so it shows up in AST with
8192 // proper storage class for other tools to use even if we're not going
8193 // to emit any code for it.
8194 NewVD->setTSCSpec(TSCS);
8195 } else
8197 diag::err_thread_unsupported);
8198 } else
8199 NewVD->setTSCSpec(TSCS);
8200 }
8201
8202 switch (D.getDeclSpec().getConstexprSpecifier()) {
8204 break;
8205
8208 diag::err_constexpr_wrong_decl_kind)
8209 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
8210 [[fallthrough]];
8211
8213 NewVD->setConstexpr(true);
8214 // C++1z [dcl.spec.constexpr]p1:
8215 // A static data member declared with the constexpr specifier is
8216 // implicitly an inline variable.
8217 if (NewVD->isStaticDataMember() &&
8219 Context.getTargetInfo().getCXXABI().isMicrosoft()))
8220 NewVD->setImplicitlyInline();
8221 break;
8222
8224 if (!NewVD->hasGlobalStorage())
8226 diag::err_constinit_local_variable);
8227 else
8228 NewVD->addAttr(
8229 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(),
8230 ConstInitAttr::Keyword_constinit));
8231 break;
8232 }
8233
8234 // C99 6.7.4p3
8235 // An inline definition of a function with external linkage shall
8236 // not contain a definition of a modifiable object with static or
8237 // thread storage duration...
8238 // We only apply this when the function is required to be defined
8239 // elsewhere, i.e. when the function is not 'extern inline'. Note
8240 // that a local variable with thread storage duration still has to
8241 // be marked 'static'. Also note that it's possible to get these
8242 // semantics in C++ using __attribute__((gnu_inline)).
8243 if (SC == SC_Static && S->getFnParent() != nullptr &&
8244 !NewVD->getType().isConstQualified()) {
8246 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
8248 diag::warn_static_local_in_extern_inline);
8250 }
8251 }
8252
8254 if (IsVariableTemplateSpecialization)
8255 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8256 << (IsPartialSpecialization ? 1 : 0)
8259 else if (IsMemberSpecialization)
8260 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
8261 << 2
8263 else if (NewVD->hasLocalStorage())
8264 Diag(NewVD->getLocation(), diag::err_module_private_local)
8265 << 0 << NewVD
8269 else {
8270 NewVD->setModulePrivate();
8271 if (NewTemplate)
8272 NewTemplate->setModulePrivate();
8273 for (auto *B : Bindings)
8274 B->setModulePrivate();
8275 }
8276 }
8277
8278 if (getLangOpts().OpenCL) {
8280
8282 if (TSC != TSCS_unspecified) {
8284 diag::err_opencl_unknown_type_specifier)
8286 << DeclSpec::getSpecifierName(TSC) << 1;
8287 NewVD->setInvalidDecl();
8288 }
8289 }
8290
8291 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply
8292 // address space if the table has local storage (semantic checks elsewhere
8293 // will produce an error anyway).
8294 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) {
8295 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() &&
8296 !NewVD->hasLocalStorage()) {
8297 QualType Type = Context.getAddrSpaceQualType(
8298 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1));
8299 NewVD->setType(Type);
8300 }
8301 }
8302
8304
8305 if (Expr *E = D.getAsmLabel()) {
8306 // The parser guarantees this is a string.
8308 StringRef Label = SE->getString();
8309
8310 // Insert the asm attribute.
8311 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, SE->getStrTokenLoc(0)));
8312 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8313 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
8315 if (I != ExtnameUndeclaredIdentifiers.end()) {
8316 if (isDeclExternC(NewVD)) {
8317 NewVD->addAttr(I->second);
8319 } else if (NewVD->getDeclContext()
8322 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
8323 << /*Variable*/ 1 << NewVD;
8324 }
8325 }
8326
8327 // Handle attributes prior to checking for duplicates in MergeVarDecl
8328 ProcessDeclAttributes(S, NewVD, D);
8329
8330 if (getLangOpts().HLSL)
8332
8333 if (getLangOpts().OpenACC)
8335
8336 // FIXME: This is probably the wrong location to be doing this and we should
8337 // probably be doing this for more attributes (especially for function
8338 // pointer attributes such as format, warn_unused_result, etc.). Ideally
8339 // the code to copy attributes would be generated by TableGen.
8340 if (R->isFunctionPointerType())
8341 if (const auto *TT = R->getAs<TypedefType>())
8343
8344 if (getLangOpts().CUDA || getLangOpts().isTargetDevice()) {
8345 if (EmitTLSUnsupportedError &&
8347 (getLangOpts().OpenMPIsTargetDevice &&
8348 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
8350 diag::err_thread_unsupported);
8351
8352 if (EmitTLSUnsupportedError &&
8353 (LangOpts.SYCLIsDevice ||
8354 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)))
8355 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
8356 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
8357 // storage [duration]."
8358 if (SC == SC_None && S->getFnParent() != nullptr &&
8359 (NewVD->hasAttr<CUDASharedAttr>() ||
8360 NewVD->hasAttr<CUDAConstantAttr>())) {
8361 NewVD->setStorageClass(SC_Static);
8362 }
8363 }
8364
8365 // Ensure that dllimport globals without explicit storage class are treated as
8366 // extern. The storage class is set above using parsed attributes. Now we can
8367 // check the VarDecl itself.
8368 assert(!NewVD->hasAttr<DLLImportAttr>() ||
8369 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
8370 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
8371
8372 // In auto-retain/release, infer strong retension for variables of
8373 // retainable type.
8374 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewVD))
8375 NewVD->setInvalidDecl();
8376
8377 // Check the ASM label here, as we need to know all other attributes of the
8378 // Decl first. Otherwise, we can't know if the asm label refers to the
8379 // host or device in a CUDA context. The device has other registers than
8380 // host and we must know where the function will be placed.
8381 CheckAsmLabel(S, D.getAsmLabel(), SC, TInfo, NewVD);
8382
8383 // Find the shadowed declaration before filtering for scope.
8384 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
8386 : nullptr;
8387
8388 // Don't consider existing declarations that are in a different
8389 // scope and are out-of-semantic-context declarations (if the new
8390 // declaration has linkage).
8393 IsMemberSpecialization ||
8394 IsVariableTemplateSpecialization);
8395
8396 // Check whether the previous declaration is in the same block scope. This
8397 // affects whether we merge types with it, per C++11 [dcl.array]p3.
8398 if (getLangOpts().CPlusPlus &&
8399 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
8401 Previous.isSingleResult() && !Previous.isShadowed() &&
8402 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
8403
8404 if (!getLangOpts().CPlusPlus) {
8406 } else {
8407 // If this is an explicit specialization of a static data member, check it.
8408 if (IsMemberSpecialization && !IsVariableTemplate &&
8409 !IsVariableTemplateSpecialization && !NewVD->isInvalidDecl() &&
8411 NewVD->setInvalidDecl();
8412
8413 // Merge the decl with the existing one if appropriate.
8414 if (!Previous.empty()) {
8415 if (Previous.isSingleResult() &&
8416 isa<FieldDecl>(Previous.getFoundDecl()) &&
8417 D.getCXXScopeSpec().isSet()) {
8418 // The user tried to define a non-static data member
8419 // out-of-line (C++ [dcl.meaning]p1).
8420 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
8421 << D.getCXXScopeSpec().getRange();
8422 Previous.clear();
8423 NewVD->setInvalidDecl();
8424 }
8425 } else if (D.getCXXScopeSpec().isSet() &&
8426 !IsVariableTemplateSpecialization) {
8427 // No previous declaration in the qualifying scope.
8428 Diag(D.getIdentifierLoc(), diag::err_no_member)
8429 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
8430 << D.getCXXScopeSpec().getRange();
8431 NewVD->setInvalidDecl();
8432
8433 // if this is a member specialization, we don't have any primary template
8434 // to be instantiated from. We set ourselves to a 'fake' clone of this so
8435 // that anything that attempts to refer to this invalid declaration can
8436 // act as if there IS a primary instantiation.
8437 if (NewTemplate && IsMemberSpecialization) {
8438 VarDecl *FakeVD =
8440 II, R, TInfo, SC);
8441 FakeVD->setInvalidDecl();
8442 VarTemplateDecl *FakeInstantiatedFrom = VarTemplateDecl::Create(
8443 Context, DC, D.getIdentifierLoc(), Name, TemplateParams, FakeVD);
8444 FakeInstantiatedFrom->setInvalidDecl();
8445 NewTemplate->setInstantiatedFromMemberTemplate(FakeInstantiatedFrom);
8446 }
8447 }
8448
8449 if (!IsPlaceholderVariable)
8451
8452 // CheckVariableDeclaration will set NewVD as invalid if something is in
8453 // error like WebAssembly tables being declared as arrays with a non-zero
8454 // size, but then parsing continues and emits further errors on that line.
8455 // To avoid that we check here if it happened and return nullptr.
8456 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl())
8457 return nullptr;
8458
8459 if (NewTemplate) {
8460 VarTemplateDecl *PrevVarTemplate =
8461 NewVD->getPreviousDecl()
8463 : nullptr;
8464
8465 // Check the template parameter list of this declaration, possibly
8466 // merging in the template parameter list from the previous variable
8467 // template declaration.
8469 TemplateParams,
8470 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
8471 : nullptr,
8472 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
8473 DC->isDependentContext())
8475 : TPC_Other))
8476 NewVD->setInvalidDecl();
8477 }
8478 }
8479
8480 if (IsMemberSpecialization) {
8481 if (NewTemplate && NewVD->getPreviousDecl()) {
8482 NewTemplate->setMemberSpecialization();
8483 } else if (IsPartialSpecialization) {
8485 ->setMemberSpecialization();
8486 }
8487 }
8488
8489 // Diagnose shadowed variables iff this isn't a redeclaration.
8490 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration())
8491 CheckShadow(NewVD, ShadowedDecl, Previous);
8492
8493 ProcessPragmaWeak(S, NewVD);
8494 ProcessPragmaExport(NewVD);
8495
8496 // If this is the first declaration of an extern C variable, update
8497 // the map of such variables.
8498 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
8499 isIncompleteDeclExternC(*this, NewVD))
8501
8502 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
8504 Decl *ManglingContextDecl;
8505 std::tie(MCtx, ManglingContextDecl) =
8507 if (MCtx) {
8508 Context.setManglingNumber(
8509 NewVD, MCtx->getManglingNumber(
8510 NewVD, getMSManglingNumber(getLangOpts(), S)));
8511 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
8512 }
8513 }
8514
8515 // Special handling of variable named 'main'.
8516 if (!getLangOpts().Freestanding && isMainVar(Name, NewVD)) {
8517 // C++ [basic.start.main]p3:
8518 // A program that declares
8519 // - a variable main at global scope, or
8520 // - an entity named main with C language linkage (in any namespace)
8521 // is ill-formed
8522 if (getLangOpts().CPlusPlus)
8523 Diag(D.getBeginLoc(), diag::err_main_global_variable)
8524 << NewVD->isExternC();
8525
8526 // In C, and external-linkage variable named main results in undefined
8527 // behavior.
8528 else if (NewVD->hasExternalFormalLinkage())
8529 Diag(D.getBeginLoc(), diag::warn_main_redefined);
8530 }
8531
8532 if (D.isRedeclaration() && !Previous.empty()) {
8533 NamedDecl *Prev = Previous.getRepresentativeDecl();
8534 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
8536 }
8537
8538 if (NewTemplate) {
8539 if (NewVD->isInvalidDecl())
8540 NewTemplate->setInvalidDecl();
8541 ActOnDocumentableDecl(NewTemplate);
8542 return NewTemplate;
8543 }
8544
8545 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
8547
8549
8550 return NewVD;
8551}
8552
8553/// Enum describing the %select options in diag::warn_decl_shadow.
8563
8564/// Determine what kind of declaration we're shadowing.
8566 const DeclContext *OldDC) {
8567 if (isa<TypeAliasDecl>(ShadowedDecl))
8568 return SDK_Using;
8569 else if (isa<TypedefDecl>(ShadowedDecl))
8570 return SDK_Typedef;
8571 else if (isa<BindingDecl>(ShadowedDecl))
8572 return SDK_StructuredBinding;
8573 else if (isa<RecordDecl>(OldDC))
8574 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
8575
8576 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
8577}
8578
8579/// Return the location of the capture if the given lambda captures the given
8580/// variable \p VD, or an invalid source location otherwise.
8582 const ValueDecl *VD) {
8583 for (const Capture &Capture : LSI->Captures) {
8585 return Capture.getLocation();
8586 }
8587 return SourceLocation();
8588}
8589
8591 const LookupResult &R) {
8592 // Only diagnose if we're shadowing an unambiguous field or variable.
8593 if (R.getResultKind() != LookupResultKind::Found)
8594 return false;
8595
8596 // Return false if warning is ignored.
8597 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
8598}
8599
8601 const LookupResult &R) {
8603 return nullptr;
8604
8605 // Don't diagnose declarations at file scope.
8606 if (D->hasGlobalStorage() && !D->isStaticLocal())
8607 return nullptr;
8608
8609 NamedDecl *ShadowedDecl = R.getFoundDecl();
8610 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8611 : nullptr;
8612}
8613
8615 const LookupResult &R) {
8616 // Don't warn if typedef declaration is part of a class
8617 if (D->getDeclContext()->isRecord())
8618 return nullptr;
8619
8621 return nullptr;
8622
8623 NamedDecl *ShadowedDecl = R.getFoundDecl();
8624 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
8625}
8626
8628 const LookupResult &R) {
8630 return nullptr;
8631
8632 NamedDecl *ShadowedDecl = R.getFoundDecl();
8633 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
8634 : nullptr;
8635}
8636
8638 const LookupResult &R) {
8639 DeclContext *NewDC = D->getDeclContext();
8640
8641 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
8643 if (const auto *MD = dyn_cast<CXXMethodDecl>(FnDC)) {
8644 // Fields aren't shadowed in C++ static members or in member functions
8645 // with an explicit object parameter.
8646 if (MD->isStatic() || MD->isExplicitObjectMemberFunction())
8647 return;
8648 } else if (isa<FunctionDecl>(FnDC)) {
8649 // A FunctionDecl here (not a CXXMethodDecl) can only be an
8650 // inline-defined friend function, since that's the only way to
8651 // introduce a non-member function inside a class body. Friends have
8652 // no implicit `this`, so nothing here can shadow a field.
8653 return;
8654 }
8655 // Fields shadowed by constructor parameters are a special case. Usually
8656 // the constructor initializes the field with the parameter.
8657 if (isa<CXXConstructorDecl>(NewDC))
8658 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
8659 // Remember that this was shadowed so we can either warn about its
8660 // modification or its existence depending on warning settings.
8661 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
8662 return;
8663 }
8664 }
8665
8666 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
8667 if (shadowedVar->isExternC()) {
8668 // For shadowing external vars, make sure that we point to the global
8669 // declaration, not a locally scoped extern declaration.
8670 for (auto *I : shadowedVar->redecls())
8671 if (I->isFileVarDecl()) {
8672 ShadowedDecl = I;
8673 break;
8674 }
8675 }
8676
8677 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
8678
8679 unsigned WarningDiag = diag::warn_decl_shadow;
8680 SourceLocation CaptureLoc;
8681 if (isa<VarDecl>(D) && NewDC && isa<CXXMethodDecl>(NewDC)) {
8682 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
8683 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
8684 // Handle both VarDecl and BindingDecl in lambda contexts
8685 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8686 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8687 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
8688 if (RD->getLambdaCaptureDefault() == LCD_None) {
8689 // Try to avoid warnings for lambdas with an explicit capture
8690 // list. Warn only when the lambda captures the shadowed decl
8691 // explicitly.
8692 CaptureLoc = getCaptureLocation(LSI, VD);
8693 if (CaptureLoc.isInvalid())
8694 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
8695 } else {
8696 // Remember that this was shadowed so we can avoid the warning if
8697 // the shadowed decl isn't captured and the warning settings allow
8698 // it.
8700 ->ShadowingDecls.push_back({D, VD});
8701 return;
8702 }
8703 }
8704 if (isa<FieldDecl>(ShadowedDecl)) {
8705 // If lambda can capture this, then emit default shadowing warning,
8706 // Otherwise it is not really a shadowing case since field is not
8707 // available in lambda's body.
8708 // At this point we don't know that lambda can capture this, so
8709 // remember that this was shadowed and delay until we know.
8711 ->ShadowingDecls.push_back({D, ShadowedDecl});
8712 return;
8713 }
8714 }
8715 // Apply scoping logic to both VarDecl and BindingDecl with local storage
8716 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8717 bool HasLocalStorage = false;
8718 if (const auto *VD = dyn_cast<VarDecl>(ShadowedDecl))
8719 HasLocalStorage = VD->hasLocalStorage();
8720 else if (const auto *BD = dyn_cast<BindingDecl>(ShadowedDecl))
8721 HasLocalStorage =
8722 cast<VarDecl>(BD->getDecomposedDecl())->hasLocalStorage();
8723
8724 if (HasLocalStorage) {
8725 // A variable can't shadow a local variable or binding in an enclosing
8726 // scope, if they are separated by a non-capturing declaration
8727 // context.
8728 for (DeclContext *ParentDC = NewDC;
8729 ParentDC && !ParentDC->Equals(OldDC);
8730 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
8731 // Only block literals, captured statements, and lambda expressions
8732 // can capture; other scopes don't.
8733 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
8734 !isLambdaCallOperator(ParentDC))
8735 return;
8736 }
8737 }
8738 }
8739 }
8740 }
8741
8742 // Never warn about shadowing a placeholder variable.
8743 if (ShadowedDecl->isPlaceholderVar(getLangOpts()))
8744 return;
8745
8746 // Only warn about certain kinds of shadowing for class members.
8747 if (NewDC) {
8748 // In particular, don't warn about shadowing non-class members.
8749 if (NewDC->isRecord() && !OldDC->isRecord())
8750 return;
8751
8752 // Skip shadowing check if we're in a class scope, dealing with an enum
8753 // constant in a different context.
8754 DeclContext *ReDC = NewDC->getRedeclContext();
8755 if (ReDC->isRecord() && isa<EnumConstantDecl>(D) && !OldDC->Equals(ReDC))
8756 return;
8757
8758 // TODO: should we warn about static data members shadowing
8759 // static data members from base classes?
8760
8761 // TODO: don't diagnose for inaccessible shadowed members.
8762 // This is hard to do perfectly because we might friend the
8763 // shadowing context, but that's just a false negative.
8764 }
8765
8766 DeclarationName Name = R.getLookupName();
8767
8768 // Emit warning and note.
8769 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
8770 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
8771 if (!CaptureLoc.isInvalid())
8772 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8773 << Name << /*explicitly*/ 1;
8774 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8775}
8776
8778 for (const auto &Shadow : LSI->ShadowingDecls) {
8779 const NamedDecl *ShadowedDecl = Shadow.ShadowedDecl;
8780 // Try to avoid the warning when the shadowed decl isn't captured.
8781 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8782 if (isa<VarDecl, BindingDecl>(ShadowedDecl)) {
8783 const auto *VD = cast<ValueDecl>(ShadowedDecl);
8784 SourceLocation CaptureLoc = getCaptureLocation(LSI, VD);
8785 Diag(Shadow.VD->getLocation(),
8786 CaptureLoc.isInvalid() ? diag::warn_decl_shadow_uncaptured_local
8787 : diag::warn_decl_shadow)
8788 << Shadow.VD->getDeclName()
8789 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8790 if (CaptureLoc.isValid())
8791 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
8792 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
8793 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8794 } else if (isa<FieldDecl>(ShadowedDecl)) {
8795 Diag(Shadow.VD->getLocation(),
8796 LSI->isCXXThisCaptured() ? diag::warn_decl_shadow
8797 : diag::warn_decl_shadow_uncaptured_local)
8798 << Shadow.VD->getDeclName()
8799 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
8800 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8801 }
8802 }
8803}
8804
8806 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
8807 return;
8808
8809 LookupResult R(*this, D->getDeclName(), D->getLocation(),
8812 LookupName(R, S);
8813 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
8814 CheckShadow(D, ShadowedDecl, R);
8815}
8816
8817/// Check if 'E', which is an expression that is about to be modified, refers
8818/// to a constructor parameter that shadows a field.
8820 // Quickly ignore expressions that can't be shadowing ctor parameters.
8821 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8822 return;
8823 E = E->IgnoreParenImpCasts();
8824 auto *DRE = dyn_cast<DeclRefExpr>(E);
8825 if (!DRE)
8826 return;
8827 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8828 auto I = ShadowingDecls.find(D);
8829 if (I == ShadowingDecls.end())
8830 return;
8831 const NamedDecl *ShadowedDecl = I->second;
8832 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8833 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8834 Diag(D->getLocation(), diag::note_var_declared_here) << D;
8835 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8836
8837 // Avoid issuing multiple warnings about the same decl.
8838 ShadowingDecls.erase(I);
8839}
8840
8841/// Check for conflict between this global or extern "C" declaration and
8842/// previous global or extern "C" declarations. This is only used in C++.
8843template<typename T>
8845 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8846 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8847 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8848
8849 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8850 // The common case: this global doesn't conflict with any extern "C"
8851 // declaration.
8852 return false;
8853 }
8854
8855 if (Prev) {
8856 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8857 // Both the old and new declarations have C language linkage. This is a
8858 // redeclaration.
8859 Previous.clear();
8860 Previous.addDecl(Prev);
8861 return true;
8862 }
8863
8864 // This is a global, non-extern "C" declaration, and there is a previous
8865 // non-global extern "C" declaration. Diagnose if this is a variable
8866 // declaration.
8867 if (!isa<VarDecl>(ND))
8868 return false;
8869 } else {
8870 // The declaration is extern "C". Check for any declaration in the
8871 // translation unit which might conflict.
8872 if (IsGlobal) {
8873 // We have already performed the lookup into the translation unit.
8874 IsGlobal = false;
8875 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8876 I != E; ++I) {
8877 if (isa<VarDecl>(*I)) {
8878 Prev = *I;
8879 break;
8880 }
8881 }
8882 } else {
8884 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8885 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8886 I != E; ++I) {
8887 if (isa<VarDecl>(*I)) {
8888 Prev = *I;
8889 break;
8890 }
8891 // FIXME: If we have any other entity with this name in global scope,
8892 // the declaration is ill-formed, but that is a defect: it breaks the
8893 // 'stat' hack, for instance. Only variables can have mangled name
8894 // clashes with extern "C" declarations, so only they deserve a
8895 // diagnostic.
8896 }
8897 }
8898
8899 if (!Prev)
8900 return false;
8901 }
8902
8903 // Use the first declaration's location to ensure we point at something which
8904 // is lexically inside an extern "C" linkage-spec.
8905 assert(Prev && "should have found a previous declaration to diagnose");
8906 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8907 Prev = FD->getFirstDecl();
8908 else
8909 Prev = cast<VarDecl>(Prev)->getFirstDecl();
8910
8911 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8912 << IsGlobal << ND;
8913 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8914 << IsGlobal;
8915 return false;
8916}
8917
8918/// Apply special rules for handling extern "C" declarations. Returns \c true
8919/// if we have found that this is a redeclaration of some prior entity.
8920///
8921/// Per C++ [dcl.link]p6:
8922/// Two declarations [for a function or variable] with C language linkage
8923/// with the same name that appear in different scopes refer to the same
8924/// [entity]. An entity with C language linkage shall not be declared with
8925/// the same name as an entity in global scope.
8926template<typename T>
8929 if (!S.getLangOpts().CPlusPlus) {
8930 // In C, when declaring a global variable, look for a corresponding 'extern'
8931 // variable declared in function scope. We don't need this in C++, because
8932 // we find local extern decls in the surrounding file-scope DeclContext.
8933 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8934 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8935 Previous.clear();
8936 Previous.addDecl(Prev);
8937 return true;
8938 }
8939 }
8940 return false;
8941 }
8942
8943 // A declaration in the translation unit can conflict with an extern "C"
8944 // declaration.
8945 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8946 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8947
8948 // An extern "C" declaration can conflict with a declaration in the
8949 // translation unit or can be a redeclaration of an extern "C" declaration
8950 // in another scope.
8951 if (isIncompleteDeclExternC(S,ND))
8952 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8953
8954 // Neither global nor extern "C": nothing to do.
8955 return false;
8956}
8957
8958static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc,
8959 QualType T) {
8960 QualType CanonT = SemaRef.Context.getCanonicalType(T);
8961 // C23 6.7.1p5: An object declared with storage-class specifier constexpr or
8962 // any of its members, even recursively, shall not have an atomic type, or a
8963 // variably modified type, or a type that is volatile or restrict qualified.
8964 if (CanonT->isVariablyModifiedType()) {
8965 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8966 return true;
8967 }
8968
8969 // Arrays are qualified by their element type, so get the base type (this
8970 // works on non-arrays as well).
8971 CanonT = SemaRef.Context.getBaseElementType(CanonT);
8972
8973 if (CanonT->isAtomicType() || CanonT.isVolatileQualified() ||
8974 CanonT.isRestrictQualified()) {
8975 SemaRef.Diag(VarLoc, diag::err_c23_constexpr_invalid_type) << T;
8976 return true;
8977 }
8978
8979 if (CanonT->isRecordType()) {
8980 const RecordDecl *RD = CanonT->getAsRecordDecl();
8981 if (!RD->isInvalidDecl() &&
8982 llvm::any_of(RD->fields(), [&SemaRef, VarLoc](const FieldDecl *F) {
8983 return CheckC23ConstexprVarType(SemaRef, VarLoc, F->getType());
8984 }))
8985 return true;
8986 }
8987
8988 return false;
8989}
8990
8992 return AS >= LangAS::sycl_global && AS <= LangAS::sycl_constant;
8993}
8994
8996 // If the decl is already known invalid, don't check it.
8997 if (NewVD->isInvalidDecl())
8998 return;
8999
9000 QualType T = NewVD->getType();
9001
9002 // Defer checking an 'auto' type until its initializer is attached.
9003 if (T->isUndeducedType())
9004 return;
9005
9006 if (NewVD->hasAttrs())
9008
9009 if (T->isObjCObjectType()) {
9010 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
9011 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
9012 T = Context.getObjCObjectPointerType(T);
9013 NewVD->setType(T);
9014 }
9015
9016 // The top-level type of a variable declaration cannot have a SYCL address
9017 // space qualifier.
9018 if (getLangOpts().isSYCL()) {
9019 LangAS AS = Context.getBaseElementType(T).getAddressSpace();
9020 if (isSYCLAddressSpace(AS)) {
9021 Diag(NewVD->getLocation(), diag::err_sycl_address_space_qualified_object)
9023 NewVD->setInvalidDecl();
9024 return;
9025 }
9026 }
9027
9028 // Emit an error if an address space was applied to decl with local storage.
9029 // This includes arrays of objects with address space qualifiers, but not
9030 // automatic variables that point to other address spaces.
9031 // ISO/IEC TR 18037 S5.1.2
9032 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
9033 T.getAddressSpace() != LangAS::Default) {
9034 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
9035 NewVD->setInvalidDecl();
9036 return;
9037 }
9038
9039 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
9040 // scope.
9041 if (getLangOpts().OpenCLVersion == 120 &&
9042 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
9043 getLangOpts()) &&
9044 NewVD->isStaticLocal()) {
9045 Diag(NewVD->getLocation(), diag::err_static_function_scope);
9046 NewVD->setInvalidDecl();
9047 return;
9048 }
9049
9050 if (getLangOpts().OpenCL) {
9051 if (!diagnoseOpenCLTypes(*this, NewVD))
9052 return;
9053
9054 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
9055 if (NewVD->hasAttr<BlocksAttr>()) {
9056 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
9057 return;
9058 }
9059
9060 if (T->isBlockPointerType()) {
9061 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
9062 // can't use 'extern' storage class.
9063 if (!T.isConstQualified()) {
9064 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
9065 << 0 /*const*/;
9066 NewVD->setInvalidDecl();
9067 return;
9068 }
9069 if (NewVD->hasExternalStorage()) {
9070 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
9071 NewVD->setInvalidDecl();
9072 return;
9073 }
9074 }
9075
9076 // FIXME: Adding local AS in C++ for OpenCL might make sense.
9077 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
9078 NewVD->hasExternalStorage()) {
9079 if (!T->isSamplerT() && !T->isDependentType() &&
9080 !(T.getAddressSpace() == LangAS::opencl_constant ||
9081 (T.getAddressSpace() == LangAS::opencl_global &&
9082 getOpenCLOptions().areProgramScopeVariablesSupported(
9083 getLangOpts())))) {
9084 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
9085 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
9086 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
9087 << Scope << "global or constant";
9088 else
9089 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
9090 << Scope << "constant";
9091 NewVD->setInvalidDecl();
9092 return;
9093 }
9094 } else {
9095 if (T.getAddressSpace() == LangAS::opencl_global) {
9096 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9097 << 1 /*is any function*/ << "global";
9098 NewVD->setInvalidDecl();
9099 return;
9100 }
9101 // When this extension is enabled, 'local' variables are permitted in
9102 // non-kernel functions and within nested scopes of kernel functions,
9103 // bypassing standard OpenCL address space restrictions.
9104 bool AllowFunctionScopeLocalVariables =
9105 T.getAddressSpace() == LangAS::opencl_local &&
9107 "__cl_clang_function_scope_local_variables", getLangOpts());
9108 if (AllowFunctionScopeLocalVariables) {
9109 // Direct pass: No further diagnostics needed for this specific case.
9110 } else if (T.getAddressSpace() == LangAS::opencl_constant ||
9111 T.getAddressSpace() == LangAS::opencl_local) {
9113 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
9114 // in functions.
9115 if (FD && !FD->hasAttr<DeviceKernelAttr>()) {
9116 if (T.getAddressSpace() == LangAS::opencl_constant)
9117 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9118 << 0 /*non-kernel only*/ << "constant";
9119 else
9120 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
9121 << 0 /*non-kernel only*/ << "local";
9122 NewVD->setInvalidDecl();
9123 return;
9124 }
9125 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
9126 // in the outermost scope of a kernel function.
9127 if (FD && FD->hasAttr<DeviceKernelAttr>()) {
9128 if (!getCurScope()->isFunctionScope()) {
9129 if (T.getAddressSpace() == LangAS::opencl_constant)
9130 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9131 << "constant";
9132 else
9133 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
9134 << "local";
9135 NewVD->setInvalidDecl();
9136 return;
9137 }
9138 }
9139 } else if (T.getAddressSpace() != LangAS::opencl_private &&
9140 // If we are parsing a template we didn't deduce an addr
9141 // space yet.
9142 T.getAddressSpace() != LangAS::Default) {
9143 // Do not allow other address spaces on automatic variable.
9144 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
9145 NewVD->setInvalidDecl();
9146 return;
9147 }
9148 }
9149 }
9150
9151 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
9152 && !NewVD->hasAttr<BlocksAttr>()) {
9153 if (getLangOpts().getGC() != LangOptions::NonGC)
9154 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
9155 else {
9156 assert(!getLangOpts().ObjCAutoRefCount);
9157 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
9158 }
9159 }
9160
9161 // WebAssembly tables must be static with a zero length and can't be
9162 // declared within functions.
9163 if (T->isWebAssemblyTableType()) {
9164 if (getCurScope()->getParent()) { // Parent is null at top-level
9165 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function);
9166 NewVD->setInvalidDecl();
9167 return;
9168 }
9169 if (NewVD->getStorageClass() != SC_Static) {
9170 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static);
9171 NewVD->setInvalidDecl();
9172 return;
9173 }
9174 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr());
9175 if (!ATy || ATy->getZExtSize() != 0) {
9176 Diag(NewVD->getLocation(),
9177 diag::err_typecheck_wasm_table_must_have_zero_length);
9178 NewVD->setInvalidDecl();
9179 return;
9180 }
9181 }
9182
9183 // zero sized static arrays are not allowed in HIP device functions
9184 if (getLangOpts().HIP && LangOpts.CUDAIsDevice) {
9185 if (FunctionDecl *FD = getCurFunctionDecl();
9186 FD &&
9187 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>())) {
9188 if (const ConstantArrayType *ArrayT =
9189 getASTContext().getAsConstantArrayType(T);
9190 ArrayT && ArrayT->isZeroSize()) {
9191 Diag(NewVD->getLocation(), diag::err_typecheck_zero_array_size) << 2;
9192 }
9193 }
9194 }
9195
9196 bool isVM = T->isVariablyModifiedType();
9197 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
9198 NewVD->hasAttr<BlocksAttr>())
9200
9201 if ((isVM && NewVD->hasLinkage()) ||
9202 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
9203 bool SizeIsNegative;
9204 llvm::APSInt Oversized;
9206 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
9207 QualType FixedT;
9208 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
9209 FixedT = FixedTInfo->getType();
9210 else if (FixedTInfo) {
9211 // Type and type-as-written are canonically different. We need to fix up
9212 // both types separately.
9213 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
9214 Oversized);
9215 }
9216 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
9217 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
9218 // FIXME: This won't give the correct result for
9219 // int a[10][n];
9220 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
9221
9222 if (NewVD->isFileVarDecl())
9223 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
9224 << SizeRange;
9225 else if (NewVD->isStaticLocal())
9226 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
9227 << SizeRange;
9228 else
9229 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
9230 << SizeRange;
9231 NewVD->setInvalidDecl();
9232 return;
9233 }
9234
9235 if (!FixedTInfo) {
9236 if (NewVD->isFileVarDecl())
9237 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
9238 else
9239 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
9240 NewVD->setInvalidDecl();
9241 return;
9242 }
9243
9244 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
9245 NewVD->setType(FixedT);
9246 NewVD->setTypeSourceInfo(FixedTInfo);
9247 }
9248
9249 if (T->isVoidType()) {
9250 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
9251 // of objects and functions.
9253 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
9254 << T;
9255 NewVD->setInvalidDecl();
9256 return;
9257 }
9258 }
9259
9260 if (!NewVD->hasLocalStorage() && T->isSizelessType() &&
9261 !T.isWebAssemblyReferenceType() && !T->isHLSLSpecificType()) {
9262 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
9263 NewVD->setInvalidDecl();
9264 return;
9265 }
9266
9267 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
9268 Diag(NewVD->getLocation(), diag::err_block_not_allowed_on)
9269 << diag::NotAllowedBlockVarReason::VariablyModifiedType;
9270 NewVD->setInvalidDecl();
9271 return;
9272 }
9273
9274 if (getLangOpts().C23 && NewVD->isConstexpr() &&
9275 CheckC23ConstexprVarType(*this, NewVD->getLocation(), T)) {
9276 NewVD->setInvalidDecl();
9277 return;
9278 }
9279
9280 if (getLangOpts().CPlusPlus && NewVD->isConstexpr() &&
9281 !T->isDependentType() &&
9283 diag::err_constexpr_var_non_literal)) {
9284 NewVD->setInvalidDecl();
9285 return;
9286 }
9287
9288 // PPC MMA non-pointer types are not allowed as non-local variable types.
9289 if (Context.getTargetInfo().getTriple().isPPC64() &&
9290 !NewVD->isLocalVarDecl() &&
9291 PPC().CheckPPCMMAType(T, NewVD->getLocation())) {
9292 NewVD->setInvalidDecl();
9293 return;
9294 }
9295
9296 // Check that SVE types are only used in functions with SVE available.
9297 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9299 llvm::StringMap<bool> CallerFeatureMap;
9300 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9301 if (ARM().checkSVETypeSupport(T, NewVD->getLocation(), FD,
9302 CallerFeatureMap)) {
9303 NewVD->setInvalidDecl();
9304 return;
9305 }
9306 }
9307
9308 if (T->isRVVSizelessBuiltinType() && isa<FunctionDecl>(CurContext)) {
9310 llvm::StringMap<bool> CallerFeatureMap;
9311 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
9313 CallerFeatureMap);
9314 }
9315
9316 if (Context.getTargetInfo().hasAMDGPUTypes()) {
9317 if (!AMDGPU().checkAMDGPUTypeSupport(T, NewVD->getLocation())) {
9318 NewVD->setInvalidDecl();
9319 return;
9320 }
9321 }
9322
9323 if (T.hasAddressSpace() &&
9324 !CheckVarDeclSizeAddressSpace(NewVD, T.getAddressSpace())) {
9325 NewVD->setInvalidDecl();
9326 return;
9327 }
9328}
9329
9332
9333 // If the decl is already known invalid, don't check it.
9334 if (NewVD->isInvalidDecl())
9335 return false;
9336
9337 // If we did not find anything by this name, look for a non-visible
9338 // extern "C" declaration with the same name.
9339 if (Previous.empty() &&
9341 Previous.setShadowed();
9342
9343 if (!Previous.empty()) {
9344 MergeVarDecl(NewVD, Previous);
9345 return true;
9346 }
9347 return false;
9348}
9349
9352
9353 // Look for methods in base classes that this method might override.
9354 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
9355 /*DetectVirtual=*/false);
9356 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9357 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
9358 DeclarationName Name = MD->getDeclName();
9359
9361 // We really want to find the base class destructor here.
9362 Name = Context.DeclarationNames.getCXXDestructorName(
9363 Context.getCanonicalTagType(BaseRecord));
9364 }
9365
9366 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
9367 CXXMethodDecl *BaseMD =
9368 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
9369 if (!BaseMD || !BaseMD->isVirtual() ||
9370 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
9371 /*ConsiderCudaAttrs=*/true))
9372 continue;
9373 if (!CheckExplicitObjectOverride(MD, BaseMD))
9374 continue;
9375 if (Overridden.insert(BaseMD).second) {
9376 MD->addOverriddenMethod(BaseMD);
9381 }
9382
9383 // A method can only override one function from each base class. We
9384 // don't track indirectly overridden methods from bases of bases.
9385 return true;
9386 }
9387
9388 return false;
9389 };
9390
9391 DC->lookupInBases(VisitBase, Paths);
9392 return !Overridden.empty();
9393}
9394
9395namespace {
9396 // Struct for holding all of the extra arguments needed by
9397 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
9398 struct ActOnFDArgs {
9399 Scope *S;
9400 Declarator &D;
9401 MultiTemplateParamsArg TemplateParamLists;
9402 bool AddToScope;
9403 };
9404} // end anonymous namespace
9405
9406namespace {
9407
9408// Callback to only accept typo corrections that have a non-zero edit distance.
9409// Also only accept corrections that have the same parent decl.
9410class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
9411 public:
9412 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
9413 CXXRecordDecl *Parent)
9414 : Context(Context), OriginalFD(TypoFD),
9415 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
9416
9417 bool ValidateCandidate(const TypoCorrection &candidate) override {
9418 if (candidate.getEditDistance() == 0)
9419 return false;
9420
9421 SmallVector<unsigned, 1> MismatchedParams;
9422 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
9423 CDeclEnd = candidate.end();
9424 CDecl != CDeclEnd; ++CDecl) {
9425 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9426
9427 if (FD && !FD->hasBody() &&
9428 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
9429 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9430 CXXRecordDecl *Parent = MD->getParent();
9431 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
9432 return true;
9433 } else if (!ExpectedParent) {
9434 return true;
9435 }
9436 }
9437 }
9438
9439 return false;
9440 }
9441
9442 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9443 return std::make_unique<DifferentNameValidatorCCC>(*this);
9444 }
9445
9446 private:
9447 ASTContext &Context;
9448 FunctionDecl *OriginalFD;
9449 CXXRecordDecl *ExpectedParent;
9450};
9451
9452} // end anonymous namespace
9453
9457
9458/// Generate diagnostics for an invalid function redeclaration.
9459///
9460/// This routine handles generating the diagnostic messages for an invalid
9461/// function redeclaration, including finding possible similar declarations
9462/// or performing typo correction if there are no previous declarations with
9463/// the same name.
9464///
9465/// Returns a NamedDecl iff typo correction was performed and substituting in
9466/// the new declaration name does not cause new errors.
9468 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
9469 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
9470 DeclarationName Name = NewFD->getDeclName();
9471 DeclContext *NewDC = NewFD->getDeclContext();
9472 SmallVector<unsigned, 1> MismatchedParams;
9474 TypoCorrection Correction;
9475 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
9476 unsigned DiagMsg =
9477 IsLocalFriend ? diag::err_no_matching_local_friend :
9478 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
9479 diag::err_member_decl_does_not_match;
9480 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
9481 IsLocalFriend ? Sema::LookupLocalFriendName
9484
9485 NewFD->setInvalidDecl();
9486 if (IsLocalFriend)
9487 SemaRef.LookupName(Prev, S);
9488 else
9489 SemaRef.LookupQualifiedName(Prev, NewDC);
9490 assert(!Prev.isAmbiguous() &&
9491 "Cannot have an ambiguity in previous-declaration lookup");
9492 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9493 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
9494 MD ? MD->getParent() : nullptr);
9495 if (!Prev.empty()) {
9496 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
9497 Func != FuncEnd; ++Func) {
9498 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
9499 if (FD &&
9500 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9501 // Add 1 to the index so that 0 can mean the mismatch didn't
9502 // involve a parameter
9503 unsigned ParamNum =
9504 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
9505 NearMatches.push_back(std::make_pair(FD, ParamNum));
9506 }
9507 }
9508 // If the qualified name lookup yielded nothing, try typo correction
9509 } else if ((Correction = SemaRef.CorrectTypo(
9510 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
9511 &ExtraArgs.D.getCXXScopeSpec(), CCC,
9513 IsLocalFriend ? nullptr : NewDC))) {
9514 // Set up everything for the call to ActOnFunctionDeclarator
9515 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
9516 ExtraArgs.D.getIdentifierLoc());
9517 Previous.clear();
9518 Previous.setLookupName(Correction.getCorrection());
9519 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
9520 CDeclEnd = Correction.end();
9521 CDecl != CDeclEnd; ++CDecl) {
9522 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
9523 if (FD && !FD->hasBody() &&
9524 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
9525 Previous.addDecl(FD);
9526 }
9527 }
9528 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
9529
9531 // Retry building the function declaration with the new previous
9532 // declarations, and with errors suppressed.
9533 {
9534 // Trap errors.
9535 Sema::SFINAETrap Trap(SemaRef);
9536
9537 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
9538 // pieces need to verify the typo-corrected C++ declaration and hopefully
9539 // eliminate the need for the parameter pack ExtraArgs.
9541 ExtraArgs.S, ExtraArgs.D,
9542 Correction.getCorrectionDecl()->getDeclContext(),
9543 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
9544 ExtraArgs.AddToScope);
9545
9546 if (Trap.hasErrorOccurred())
9547 Result = nullptr;
9548 }
9549
9550 if (Result) {
9551 // Determine which correction we picked.
9552 Decl *Canonical = Result->getCanonicalDecl();
9553 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9554 I != E; ++I)
9555 if ((*I)->getCanonicalDecl() == Canonical)
9556 Correction.setCorrectionDecl(*I);
9557
9558 // Let Sema know about the correction.
9560 SemaRef.diagnoseTypo(
9561 Correction,
9562 SemaRef.PDiag(IsLocalFriend
9563 ? diag::err_no_matching_local_friend_suggest
9564 : diag::err_member_decl_does_not_match_suggest)
9565 << Name << NewDC << IsDefinition);
9566 return Result;
9567 }
9568
9569 // Pretend the typo correction never occurred
9570 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
9571 ExtraArgs.D.getIdentifierLoc());
9572 ExtraArgs.D.setRedeclaration(wasRedeclaration);
9573 Previous.clear();
9574 Previous.setLookupName(Name);
9575 }
9576
9577 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
9578 << Name << NewDC << IsDefinition << NewFD->getLocation();
9579
9580 CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD);
9581 if (NewMD && DiagMsg == diag::err_member_decl_does_not_match) {
9582 CXXRecordDecl *RD = NewMD->getParent();
9583 SemaRef.Diag(RD->getLocation(), diag::note_defined_here)
9584 << RD->getName() << RD->getLocation();
9585 }
9586
9587 bool NewFDisConst = NewMD && NewMD->isConst();
9588
9589 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
9590 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
9591 NearMatch != NearMatchEnd; ++NearMatch) {
9592 FunctionDecl *FD = NearMatch->first;
9593 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9594 bool FDisConst = MD && MD->isConst();
9595 bool IsMember = MD || !IsLocalFriend;
9596
9597 // FIXME: These notes are poorly worded for the local friend case.
9598 if (unsigned Idx = NearMatch->second) {
9599 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
9600 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
9601 if (Loc.isInvalid()) Loc = FD->getLocation();
9602 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
9603 : diag::note_local_decl_close_param_match)
9604 << Idx << FDParam->getType()
9605 << NewFD->getParamDecl(Idx - 1)->getType();
9606 } else if (FDisConst != NewFDisConst) {
9607 auto DB = SemaRef.Diag(FD->getLocation(),
9608 diag::note_member_def_close_const_match)
9609 << NewFDisConst << FD->getSourceRange().getEnd();
9610 if (const auto &FTI = ExtraArgs.D.getFunctionTypeInfo(); !NewFDisConst)
9611 DB << FixItHint::CreateInsertion(FTI.getRParenLoc().getLocWithOffset(1),
9612 " const");
9613 else if (FTI.hasMethodTypeQualifiers() &&
9614 FTI.getConstQualifierLoc().isValid())
9615 DB << FixItHint::CreateRemoval(FTI.getConstQualifierLoc());
9616 } else {
9617 SemaRef.Diag(FD->getLocation(),
9618 IsMember ? diag::note_member_def_close_match
9619 : diag::note_local_decl_close_match);
9620 }
9621 }
9622 return nullptr;
9623}
9624
9626 switch (D.getDeclSpec().getStorageClassSpec()) {
9627 default: llvm_unreachable("Unknown storage class!");
9628 case DeclSpec::SCS_auto:
9632 diag::err_typecheck_sclass_func);
9634 D.setInvalidType();
9635 break;
9636 case DeclSpec::SCS_unspecified: break;
9639 return SC_None;
9640 return SC_Extern;
9641 case DeclSpec::SCS_static: {
9643 // C99 6.7.1p5:
9644 // The declaration of an identifier for a function that has
9645 // block scope shall have no explicit storage-class specifier
9646 // other than extern
9647 // See also (C++ [dcl.stc]p4).
9649 diag::err_static_block_func);
9650 break;
9651 } else
9652 return SC_Static;
9653 }
9655 }
9656
9657 // No explicit storage class has already been returned
9658 return SC_None;
9659}
9660
9662 DeclContext *DC, QualType &R,
9663 TypeSourceInfo *TInfo,
9664 StorageClass SC,
9665 bool &IsVirtualOkay) {
9666 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
9667 DeclarationName Name = NameInfo.getName();
9668
9669 FunctionDecl *NewFD = nullptr;
9670 bool isInline = D.getDeclSpec().isInlineSpecified();
9671
9673 if (ConstexprKind == ConstexprSpecKind::Constinit ||
9674 (SemaRef.getLangOpts().C23 &&
9675 ConstexprKind == ConstexprSpecKind::Constexpr)) {
9676
9677 if (SemaRef.getLangOpts().C23)
9678 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9679 diag::err_c23_constexpr_not_variable);
9680 else
9681 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
9682 diag::err_constexpr_wrong_decl_kind)
9683 << static_cast<int>(ConstexprKind);
9684 ConstexprKind = ConstexprSpecKind::Unspecified;
9686 }
9687
9688 if (!SemaRef.getLangOpts().CPlusPlus) {
9689 // Determine whether the function was written with a prototype. This is
9690 // true when:
9691 // - there is a prototype in the declarator, or
9692 // - the type R of the function is some kind of typedef or other non-
9693 // attributed reference to a type name (which eventually refers to a
9694 // function type). Note, we can't always look at the adjusted type to
9695 // check this case because attributes may cause a non-function
9696 // declarator to still have a function type. e.g.,
9697 // typedef void func(int a);
9698 // __attribute__((noreturn)) func other_func; // This has a prototype
9699 bool HasPrototype =
9701 (D.getDeclSpec().isTypeRep() &&
9702 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr)
9703 ->isFunctionProtoType()) ||
9704 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
9705 assert(
9706 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
9707 "Strict prototypes are required");
9708
9709 NewFD = FunctionDecl::Create(
9710 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9711 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
9713 /*TrailingRequiresClause=*/{});
9714 if (D.isInvalidType())
9715 NewFD->setInvalidDecl();
9716
9717 return NewFD;
9718 }
9719
9721 AssociatedConstraint TrailingRequiresClause(D.getTrailingRequiresClause());
9722
9723 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R);
9724
9726 // This is a C++ constructor declaration.
9727 assert(DC->isRecord() &&
9728 "Constructors can only be declared in a member context");
9729
9730 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
9732 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9734 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
9735 InheritedConstructor(), TrailingRequiresClause);
9736
9737 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9738 // This is a C++ destructor declaration.
9739 if (DC->isRecord()) {
9740 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
9743 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
9744 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9745 /*isImplicitlyDeclared=*/false, ConstexprKind,
9746 TrailingRequiresClause);
9747 // User defined destructors start as not selected if the class definition is still
9748 // not done.
9749 if (Record->isBeingDefined())
9750 NewDD->setIneligibleOrNotSelected(true);
9751
9752 // If the destructor needs an implicit exception specification, set it
9753 // now. FIXME: It'd be nice to be able to create the right type to start
9754 // with, but the type needs to reference the destructor declaration.
9755 if (SemaRef.getLangOpts().CPlusPlus11)
9756 SemaRef.AdjustDestructorExceptionSpec(NewDD);
9757
9758 IsVirtualOkay = true;
9759 return NewDD;
9760
9761 } else {
9762 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
9763 D.setInvalidType();
9764
9765 // Create a FunctionDecl to satisfy the function definition parsing
9766 // code path.
9767 return FunctionDecl::Create(
9768 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
9769 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9770 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
9771 }
9772
9774 if (!DC->isRecord()) {
9775 SemaRef.Diag(D.getIdentifierLoc(),
9776 diag::err_conv_function_not_member);
9777 return nullptr;
9778 }
9779
9780 SemaRef.CheckConversionDeclarator(D, R, SC);
9781 if (D.isInvalidType())
9782 return nullptr;
9783
9784 IsVirtualOkay = true;
9786 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9787 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9788 ExplicitSpecifier, ConstexprKind, SourceLocation(),
9789 TrailingRequiresClause);
9790
9792 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC))
9793 return nullptr;
9795 SemaRef.Context, DC, D.getBeginLoc(), ExplicitSpecifier, NameInfo, R,
9796 TInfo, D.getEndLoc(), /*Ctor=*/nullptr,
9797 /*Kind=*/DeductionCandidate::Normal, TrailingRequiresClause);
9798 } else if (DC->isRecord()) {
9799 // If the name of the function is the same as the name of the record,
9800 // then this must be an invalid constructor that has a return type.
9801 // (The parser checks for a return type and makes the declarator a
9802 // constructor if it has no return type).
9803 if (Name.getAsIdentifierInfo() &&
9804 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
9805 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
9808 return nullptr;
9809 }
9810
9811 // This is a C++ method declaration.
9813 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
9814 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9815 ConstexprKind, SourceLocation(), TrailingRequiresClause);
9816 IsVirtualOkay = !Ret->isStatic();
9817 return Ret;
9818 } else {
9819 bool isFriend =
9820 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
9821 if (!isFriend && SemaRef.CurContext->isRecord())
9822 return nullptr;
9823
9824 // Determine whether the function was written with a
9825 // prototype. This true when:
9826 // - we're in C++ (where every function has a prototype),
9827 return FunctionDecl::Create(
9828 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
9829 SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
9830 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
9831 }
9832}
9833
9842
9844 // Size dependent types are just typedefs to normal integer types
9845 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
9846 // integers other than by their names.
9847 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
9848
9849 // Remove typedefs one by one until we reach a typedef
9850 // for a size dependent type.
9851 QualType DesugaredTy = Ty;
9852 do {
9853 ArrayRef<StringRef> Names(SizeTypeNames);
9854 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
9855 if (Names.end() != Match)
9856 return true;
9857
9858 Ty = DesugaredTy;
9859 DesugaredTy = Ty.getSingleStepDesugaredType(C);
9860 } while (DesugaredTy != Ty);
9861
9862 return false;
9863}
9864
9866 if (PT->isDependentType())
9867 return InvalidKernelParam;
9868
9869 if (PT->isPointerOrReferenceType()) {
9870 QualType PointeeType = PT->getPointeeType();
9871 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
9872 PointeeType.getAddressSpace() == LangAS::opencl_private ||
9873 PointeeType.getAddressSpace() == LangAS::Default)
9875
9876 if (PointeeType->isPointerType()) {
9877 // This is a pointer to pointer parameter.
9878 // Recursively check inner type.
9879 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
9880 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
9881 ParamKind == InvalidKernelParam)
9882 return ParamKind;
9883
9884 // OpenCL v3.0 s6.11.a:
9885 // A restriction to pass pointers to pointers only applies to OpenCL C
9886 // v1.2 or below.
9888 return ValidKernelParam;
9889
9890 return PtrPtrKernelParam;
9891 }
9892
9893 // C++ for OpenCL v1.0 s2.4:
9894 // Moreover the types used in parameters of the kernel functions must be:
9895 // Standard layout types for pointer parameters. The same applies to
9896 // reference if an implementation supports them in kernel parameters.
9897 if (S.getLangOpts().OpenCLCPlusPlus &&
9899 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
9900 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
9901 bool IsStandardLayoutType = true;
9902 if (CXXRec) {
9903 // If template type is not ODR-used its definition is only available
9904 // in the template definition not its instantiation.
9905 // FIXME: This logic doesn't work for types that depend on template
9906 // parameter (PR58590).
9907 if (!CXXRec->hasDefinition())
9908 CXXRec = CXXRec->getTemplateInstantiationPattern();
9909 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
9910 IsStandardLayoutType = false;
9911 }
9912 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
9913 !IsStandardLayoutType)
9914 return InvalidKernelParam;
9915 }
9916
9917 // OpenCL v1.2 s6.9.p:
9918 // A restriction to pass pointers only applies to OpenCL C v1.2 or below.
9920 return ValidKernelParam;
9921
9922 return PtrKernelParam;
9923 }
9924
9925 // OpenCL v1.2 s6.9.k:
9926 // Arguments to kernel functions in a program cannot be declared with the
9927 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9928 // uintptr_t or a struct and/or union that contain fields declared to be one
9929 // of these built-in scalar types.
9931 return InvalidKernelParam;
9932
9933 if (PT->isImageType())
9934 return PtrKernelParam;
9935
9936 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
9937 return InvalidKernelParam;
9938
9939 // OpenCL extension spec v1.2 s9.5:
9940 // This extension adds support for half scalar and vector types as built-in
9941 // types that can be used for arithmetic operations, conversions etc.
9942 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
9943 PT->isHalfType())
9944 return InvalidKernelParam;
9945
9946 // Look into an array argument to check if it has a forbidden type.
9947 if (PT->isArrayType()) {
9948 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
9949 // Call ourself to check an underlying type of an array. Since the
9950 // getPointeeOrArrayElementType returns an innermost type which is not an
9951 // array, this recursive call only happens once.
9952 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
9953 }
9954
9955 // C++ for OpenCL v1.0 s2.4:
9956 // Moreover the types used in parameters of the kernel functions must be:
9957 // Trivial and standard-layout types C++17 [basic.types] (plain old data
9958 // types) for parameters passed by value;
9959 if (S.getLangOpts().OpenCLCPlusPlus &&
9961 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
9962 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
9963 return InvalidKernelParam;
9964
9965 if (PT->isRecordType())
9966 return RecordKernelParam;
9967
9968 return ValidKernelParam;
9969}
9970
9972 Sema &S,
9973 Declarator &D,
9974 ParmVarDecl *Param,
9975 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9976 QualType PT = Param->getType();
9977
9978 // Cache the valid types we encounter to avoid rechecking structs that are
9979 // used again
9980 if (ValidTypes.count(PT.getTypePtr()))
9981 return;
9982
9983 switch (getOpenCLKernelParameterType(S, PT)) {
9984 case PtrPtrKernelParam:
9985 // OpenCL v3.0 s6.11.a:
9986 // A kernel function argument cannot be declared as a pointer to a pointer
9987 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9988 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9989 D.setInvalidType();
9990 return;
9991
9993 // OpenCL v1.0 s6.5:
9994 // __kernel function arguments declared to be a pointer of a type can point
9995 // to one of the following address spaces only : __global, __local or
9996 // __constant.
9997 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9998 D.setInvalidType();
9999 return;
10000
10001 // OpenCL v1.2 s6.9.k:
10002 // Arguments to kernel functions in a program cannot be declared with the
10003 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
10004 // uintptr_t or a struct and/or union that contain fields declared to be
10005 // one of these built-in scalar types.
10006
10007 case InvalidKernelParam:
10008 // OpenCL v1.2 s6.8 n:
10009 // A kernel function argument cannot be declared
10010 // of event_t type.
10011 // Do not diagnose half type since it is diagnosed as invalid argument
10012 // type for any function elsewhere.
10013 if (!PT->isHalfType()) {
10014 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
10015
10016 // Explain what typedefs are involved.
10017 const TypedefType *Typedef = nullptr;
10018 while ((Typedef = PT->getAs<TypedefType>())) {
10019 SourceLocation Loc = Typedef->getDecl()->getLocation();
10020 // SourceLocation may be invalid for a built-in type.
10021 if (Loc.isValid())
10022 S.Diag(Loc, diag::note_entity_declared_at) << PT;
10023 PT = Typedef->desugar();
10024 }
10025 }
10026
10027 D.setInvalidType();
10028 return;
10029
10030 case PtrKernelParam:
10031 case ValidKernelParam:
10032 ValidTypes.insert(PT.getTypePtr());
10033 return;
10034
10035 case RecordKernelParam:
10036 break;
10037 }
10038
10039 // Track nested structs we will inspect
10041
10042 // Track where we are in the nested structs. Items will migrate from
10043 // VisitStack to HistoryStack as we do the DFS for bad field.
10045 HistoryStack.push_back(nullptr);
10046
10047 // At this point we already handled everything except of a RecordType.
10048 assert(PT->isRecordType() && "Unexpected type.");
10049 const auto *PD = PT->castAsRecordDecl();
10050 VisitStack.push_back(PD);
10051 assert(VisitStack.back() && "First decl null?");
10052
10053 do {
10054 const Decl *Next = VisitStack.pop_back_val();
10055 if (!Next) {
10056 assert(!HistoryStack.empty());
10057 // Found a marker, we have gone up a level
10058 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
10059 ValidTypes.insert(Hist->getType().getTypePtr());
10060
10061 continue;
10062 }
10063
10064 // Adds everything except the original parameter declaration (which is not a
10065 // field itself) to the history stack.
10066 const RecordDecl *RD;
10067 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
10068 HistoryStack.push_back(Field);
10069
10070 QualType FieldTy = Field->getType();
10071 // Other field types (known to be valid or invalid) are handled while we
10072 // walk around RecordDecl::fields().
10073 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
10074 "Unexpected type.");
10075 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
10076
10077 RD = FieldRecTy->castAsRecordDecl();
10078 } else {
10079 RD = cast<RecordDecl>(Next);
10080 }
10081
10082 // Add a null marker so we know when we've gone back up a level
10083 VisitStack.push_back(nullptr);
10084
10085 for (const auto *FD : RD->fields()) {
10086 QualType QT = FD->getType();
10087
10088 if (ValidTypes.count(QT.getTypePtr()))
10089 continue;
10090
10092 if (ParamType == ValidKernelParam)
10093 continue;
10094
10095 if (ParamType == RecordKernelParam) {
10096 VisitStack.push_back(FD);
10097 continue;
10098 }
10099
10100 // OpenCL v1.2 s6.9.p:
10101 // Arguments to kernel functions that are declared to be a struct or union
10102 // do not allow OpenCL objects to be passed as elements of the struct or
10103 // union. This restriction was lifted in OpenCL v2.0 with the introduction
10104 // of SVM.
10105 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
10106 ParamType == InvalidAddrSpacePtrKernelParam) {
10107 S.Diag(Param->getLocation(),
10108 diag::err_record_with_pointers_kernel_param)
10109 << PT->isUnionType()
10110 << PT;
10111 } else {
10112 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
10113 }
10114
10115 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
10116 << PD->getDeclName();
10117
10118 // We have an error, now let's go back up through history and show where
10119 // the offending field came from
10121 I = HistoryStack.begin() + 1,
10122 E = HistoryStack.end();
10123 I != E; ++I) {
10124 const FieldDecl *OuterField = *I;
10125 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
10126 << OuterField->getType();
10127 }
10128
10129 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
10130 << QT->isPointerType()
10131 << QT;
10132 D.setInvalidType();
10133 return;
10134 }
10135 } while (!VisitStack.empty());
10136}
10137
10138/// Find the DeclContext in which a tag is implicitly declared if we see an
10139/// elaborated type specifier in the specified context, and lookup finds
10140/// nothing.
10142 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
10143 DC = DC->getParent();
10144 return DC;
10145}
10146
10147/// Find the Scope in which a tag is implicitly declared if we see an
10148/// elaborated type specifier in the specified context, and lookup finds
10149/// nothing.
10150static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
10151 while (S->isClassScope() ||
10152 (LangOpts.CPlusPlus &&
10154 ((S->getFlags() & Scope::DeclScope) == 0) ||
10155 (S->getEntity() && S->getEntity()->isTransparentContext()))
10156 S = S->getParent();
10157 return S;
10158}
10159
10160/// Determine whether a declaration matches a known function in namespace std.
10162 unsigned BuiltinID) {
10163 switch (BuiltinID) {
10164 case Builtin::BI__GetExceptionInfo:
10165 // No type checking whatsoever.
10166 return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
10167
10168 case Builtin::BIaddressof:
10169 case Builtin::BI__addressof:
10170 case Builtin::BIforward:
10171 case Builtin::BIforward_like:
10172 case Builtin::BImove:
10173 case Builtin::BImove_if_noexcept:
10174 case Builtin::BIas_const: {
10175 // Ensure that we don't treat the algorithm
10176 // OutputIt std::move(InputIt, InputIt, OutputIt)
10177 // as the builtin std::move.
10178 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10179 return FPT->getNumParams() == 1 && !FPT->isVariadic();
10180 }
10181
10182 default:
10183 return false;
10184 }
10185}
10186
10188 const auto *FT = FD->getType()->getAs<FunctionType>();
10189 if (!FT)
10190 return;
10191
10192 StringRef Tag;
10193 switch (FT->getCallConv()) {
10194#define CC_VLS_CASE(ABI_VLEN) \
10195 case CC_RISCVVLSCall_##ABI_VLEN: \
10196 Tag = "riscv_vls_cc_" #ABI_VLEN; \
10197 break;
10198 CC_VLS_CASE(32)
10199 CC_VLS_CASE(64)
10200 CC_VLS_CASE(128)
10201 CC_VLS_CASE(256)
10202 CC_VLS_CASE(512)
10203 CC_VLS_CASE(1024)
10204 CC_VLS_CASE(2048)
10205 CC_VLS_CASE(4096)
10206 CC_VLS_CASE(8192)
10207 CC_VLS_CASE(16384)
10208 CC_VLS_CASE(32768)
10209 CC_VLS_CASE(65536)
10210#undef CC_VLS_CASE
10211 default:
10212 return;
10213 }
10214
10215 SmallVector<AbiTagAttr *, 2> Existing(FD->specific_attrs<AbiTagAttr>());
10216 AbiTagAttr *Old = Existing.empty() ? nullptr : Existing.front();
10217
10219 if (Old)
10220 llvm::append_range(Tags, Old->tags());
10221 if (llvm::is_contained(Tags, Tag))
10222 return;
10223 Tags.push_back(Tag);
10224
10225 AbiTagAttr *Merged =
10226 Old ? AbiTagAttr::Create(Context, Tags.data(), Tags.size(), *Old)
10227 : AbiTagAttr::CreateImplicit(Context, Tags.data(), Tags.size(),
10228 FD->getLocation());
10229 FD->dropAttr<AbiTagAttr>();
10230 FD->addAttr(Merged);
10231 for (size_t I = 1, E = Existing.size(); I < E; ++I)
10232 FD->addAttr(Existing[I]);
10233}
10234
10235NamedDecl*
10238 MultiTemplateParamsArg TemplateParamListsRef,
10239 bool &AddToScope) {
10240 QualType R = TInfo->getType();
10241
10242 assert(R->isFunctionType());
10243 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
10244 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
10245
10246 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
10247 llvm::append_range(TemplateParamLists, TemplateParamListsRef);
10249 if (!TemplateParamLists.empty() && !TemplateParamLists.back()->empty() &&
10250 Invented->getDepth() == TemplateParamLists.back()->getDepth())
10251 TemplateParamLists.back() = Invented;
10252 else
10253 TemplateParamLists.push_back(Invented);
10254 }
10255
10256 // TODO: consider using NameInfo for diagnostic.
10258 DeclarationName Name = NameInfo.getName();
10260
10263 diag::err_invalid_thread)
10265
10270
10271 bool isFriend = false;
10273 bool isMemberSpecialization = false;
10274 bool isFunctionTemplateSpecialization = false;
10275
10276 bool HasExplicitTemplateArgs = false;
10277 TemplateArgumentListInfo TemplateArgs;
10278
10279 bool isVirtualOkay = false;
10280
10281 DeclContext *OriginalDC = DC;
10282 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
10283
10284 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
10285 isVirtualOkay);
10286 if (!NewFD) return nullptr;
10287
10288 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
10290
10291 // Set the lexical context. If this is a function-scope declaration, or has a
10292 // C++ scope specifier, or is the object of a friend declaration, the lexical
10293 // context will be different from the semantic context.
10295
10296 if (IsLocalExternDecl)
10297 NewFD->setLocalExternDecl();
10298
10299 if (getLangOpts().CPlusPlus) {
10300 // The rules for implicit inlines changed in C++20 for methods and friends
10301 // with an in-class definition (when such a definition is not attached to
10302 // the global module). This does not affect declarations that are already
10303 // inline (whether explicitly or implicitly by being declared constexpr,
10304 // consteval, etc).
10305 // FIXME: We need a better way to separate C++ standard and clang modules.
10306 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
10307 !NewFD->getOwningModule() ||
10308 NewFD->isFromGlobalModule() ||
10310 bool isInline = D.getDeclSpec().isInlineSpecified();
10311 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10312 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
10313 isFriend = D.getDeclSpec().isFriendSpecified();
10314 if (ImplicitInlineCXX20 && isFriend && D.isFunctionDefinition()) {
10315 // Pre-C++20 [class.friend]p5
10316 // A function can be defined in a friend declaration of a
10317 // class . . . . Such a function is implicitly inline.
10318 // Post C++20 [class.friend]p7
10319 // Such a function is implicitly an inline function if it is attached
10320 // to the global module.
10321 NewFD->setImplicitlyInline();
10322 }
10323
10324 // If this is a method defined in an __interface, and is not a constructor
10325 // or an overloaded operator, then set the pure flag (isVirtual will already
10326 // return true).
10327 if (const CXXRecordDecl *Parent =
10328 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
10329 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
10330 NewFD->setIsPureVirtual(true);
10331
10332 // C++ [class.union]p2
10333 // A union can have member functions, but not virtual functions.
10334 if (isVirtual && Parent->isUnion()) {
10335 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
10336 NewFD->setInvalidDecl();
10337 }
10338 if ((Parent->isClass() || Parent->isStruct()) &&
10339 Parent->hasAttr<SYCLSpecialClassAttr>() &&
10340 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
10341 NewFD->getName() == "__init" && D.isFunctionDefinition()) {
10342 if (auto *Def = Parent->getDefinition())
10343 Def->setInitMethod(true);
10344 }
10345 }
10346
10347 SetNestedNameSpecifier(*this, NewFD, D);
10348 isMemberSpecialization = false;
10349 isFunctionTemplateSpecialization = false;
10350 if (D.isInvalidType())
10351 NewFD->setInvalidDecl();
10352
10353 // Match up the template parameter lists with the scope specifier, then
10354 // determine whether we have a template or a template specialization.
10355 bool Invalid = false;
10356 TemplateIdAnnotation *TemplateId =
10358 ? D.getName().TemplateId
10359 : nullptr;
10360 TemplateParameterList *TemplateParams =
10363 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend,
10364 isMemberSpecialization, Invalid);
10365 if (TemplateParams) {
10366 // Check that we can declare a template here.
10367 if (CheckTemplateDeclScope(S, TemplateParams))
10368 NewFD->setInvalidDecl();
10369
10370 if (TemplateParams->size() > 0) {
10371 // This is a function template
10372
10373 // A destructor cannot be a template.
10375 Diag(NewFD->getLocation(), diag::err_destructor_template);
10376 NewFD->setInvalidDecl();
10377 // Function template with explicit template arguments.
10378 } else if (TemplateId) {
10379 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
10380 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
10381 NewFD->setInvalidDecl();
10382 }
10383
10384 // If we're adding a template to a dependent context, we may need to
10385 // rebuilding some of the types used within the template parameter list,
10386 // now that we know what the current instantiation is.
10387 if (DC->isDependentContext()) {
10388 ContextRAII SavedContext(*this, DC);
10390 Invalid = true;
10391 }
10392
10394 NewFD->getLocation(),
10395 Name, TemplateParams,
10396 NewFD);
10397 FunctionTemplate->setLexicalDeclContext(CurContext);
10399
10400 // For source fidelity, store the other template param lists.
10401 if (TemplateParamLists.size() > 1) {
10403 ArrayRef<TemplateParameterList *>(TemplateParamLists)
10404 .drop_back(1));
10405 }
10406 } else {
10407 // This is a function template specialization.
10408 isFunctionTemplateSpecialization = true;
10409 // For source fidelity, store all the template param lists.
10410 if (TemplateParamLists.size() > 0)
10411 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10412
10413 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
10414 if (isFriend) {
10415 // We want to remove the "template<>", found here.
10416 SourceRange RemoveRange = TemplateParams->getSourceRange();
10417
10418 // If we remove the template<> and the name is not a
10419 // template-id, we're actually silently creating a problem:
10420 // the friend declaration will refer to an untemplated decl,
10421 // and clearly the user wants a template specialization. So
10422 // we need to insert '<>' after the name.
10423 SourceLocation InsertLoc;
10425 InsertLoc = D.getName().getSourceRange().getEnd();
10426 InsertLoc = getLocForEndOfToken(InsertLoc);
10427 }
10428
10429 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
10430 << Name << RemoveRange
10431 << FixItHint::CreateRemoval(RemoveRange)
10432 << FixItHint::CreateInsertion(InsertLoc, "<>");
10433 Invalid = true;
10434
10435 // Recover by faking up an empty template argument list.
10436 HasExplicitTemplateArgs = true;
10437 TemplateArgs.setLAngleLoc(InsertLoc);
10438 TemplateArgs.setRAngleLoc(InsertLoc);
10439 }
10440 }
10441 } else {
10442 // Check that we can declare a template here.
10443 if (!TemplateParamLists.empty() && isMemberSpecialization &&
10444 CheckTemplateDeclScope(S, TemplateParamLists.back()))
10445 NewFD->setInvalidDecl();
10446
10447 // All template param lists were matched against the scope specifier:
10448 // this is NOT (an explicit specialization of) a template.
10449 if (TemplateParamLists.size() > 0)
10450 // For source fidelity, store all the template param lists.
10451 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
10452
10453 // "friend void foo<>(int);" is an implicit specialization decl.
10454 if (isFriend && TemplateId)
10455 isFunctionTemplateSpecialization = true;
10456 }
10457
10458 // If this is a function template specialization and the unqualified-id of
10459 // the declarator-id is a template-id, convert the template argument list
10460 // into our AST format and check for unexpanded packs.
10461 if (isFunctionTemplateSpecialization && TemplateId) {
10462 HasExplicitTemplateArgs = true;
10463
10464 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
10465 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
10466 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
10467 TemplateId->NumArgs);
10468 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
10469
10470 // FIXME: Should we check for unexpanded packs if this was an (invalid)
10471 // declaration of a function template partial specialization? Should we
10472 // consider the unexpanded pack context to be a partial specialization?
10473 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) {
10475 ArgLoc, isFriend ? UPPC_FriendDeclaration
10477 NewFD->setInvalidDecl();
10478 }
10479 }
10480
10481 if (Invalid) {
10482 NewFD->setInvalidDecl();
10483 if (FunctionTemplate)
10484 FunctionTemplate->setInvalidDecl();
10485 }
10486
10487 // C++ [dcl.fct.spec]p5:
10488 // The virtual specifier shall only be used in declarations of
10489 // nonstatic class member functions that appear within a
10490 // member-specification of a class declaration; see 10.3.
10491 //
10492 if (isVirtual && !NewFD->isInvalidDecl()) {
10493 if (!isVirtualOkay) {
10495 diag::err_virtual_non_function);
10496 } else if (!CurContext->isRecord()) {
10497 // 'virtual' was specified outside of the class.
10499 diag::err_virtual_out_of_class)
10501 } else if (NewFD->getDescribedFunctionTemplate()) {
10502 // C++ [temp.mem]p3:
10503 // A member function template shall not be virtual.
10505 diag::err_virtual_member_function_template)
10507 } else {
10508 // Okay: Add virtual to the method.
10509 NewFD->setVirtualAsWritten(true);
10510 }
10511
10512 if (getLangOpts().CPlusPlus14 &&
10513 NewFD->getReturnType()->isUndeducedType())
10514 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
10515 }
10516
10517 // C++ [dcl.fct.spec]p3:
10518 // The inline specifier shall not appear on a block scope function
10519 // declaration.
10520 if (isInline && !NewFD->isInvalidDecl()) {
10521 if (CurContext->isFunctionOrMethod()) {
10522 // 'inline' is not allowed on block scope function declaration.
10524 diag::err_inline_declaration_block_scope) << Name
10526 }
10527 }
10528
10529 // C++ [dcl.fct.spec]p6:
10530 // The explicit specifier shall be used only in the declaration of a
10531 // constructor or conversion function within its class definition;
10532 // see 12.3.1 and 12.3.2.
10533 if (hasExplicit && !NewFD->isInvalidDecl() &&
10535 if (!CurContext->isRecord()) {
10536 // 'explicit' was specified outside of the class.
10538 diag::err_explicit_out_of_class)
10540 } else if (!isa<CXXConstructorDecl>(NewFD) &&
10541 !isa<CXXConversionDecl>(NewFD)) {
10542 // 'explicit' was specified on a function that wasn't a constructor
10543 // or conversion function.
10545 diag::err_explicit_non_ctor_or_conv_function)
10547 }
10548 }
10549
10551 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
10552 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
10553 // are implicitly inline.
10554 NewFD->setImplicitlyInline();
10555
10556 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
10557 // be either constructors or to return a literal type. Therefore,
10558 // destructors cannot be declared constexpr.
10559 if (isa<CXXDestructorDecl>(NewFD) &&
10561 ConstexprKind == ConstexprSpecKind::Consteval)) {
10562 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
10563 << static_cast<int>(ConstexprKind);
10567 }
10568 // C++20 [dcl.constexpr]p2: An allocation function, or a
10569 // deallocation function shall not be declared with the consteval
10570 // specifier.
10571 if (ConstexprKind == ConstexprSpecKind::Consteval &&
10574 diag::err_invalid_consteval_decl_kind)
10575 << NewFD;
10577 }
10578 }
10579
10580 // If __module_private__ was specified, mark the function accordingly.
10582 if (isFunctionTemplateSpecialization) {
10583 SourceLocation ModulePrivateLoc
10585 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
10586 << 0
10587 << FixItHint::CreateRemoval(ModulePrivateLoc);
10588 } else {
10589 NewFD->setModulePrivate();
10590 if (FunctionTemplate)
10591 FunctionTemplate->setModulePrivate();
10592 }
10593 }
10594
10595 if (isFriend) {
10596 if (FunctionTemplate) {
10597 FunctionTemplate->setObjectOfFriendDecl();
10598 FunctionTemplate->setAccess(AS_public);
10599 }
10600 NewFD->setObjectOfFriendDecl();
10601 NewFD->setAccess(AS_public);
10602 }
10603
10604 // If a function is defined as defaulted or deleted, mark it as such now.
10605 // We'll do the relevant checks on defaulted / deleted functions later.
10606 switch (D.getFunctionDefinitionKind()) {
10609 break;
10610
10612 NewFD->setDefaulted();
10613 break;
10614
10616 NewFD->setDeletedAsWritten();
10617 break;
10618 }
10619
10620 if (ImplicitInlineCXX20 && isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
10622 // Pre C++20 [class.mfct]p2:
10623 // A member function may be defined (8.4) in its class definition, in
10624 // which case it is an inline member function (7.1.2)
10625 // Post C++20 [class.mfct]p1:
10626 // If a member function is attached to the global module and is defined
10627 // in its class definition, it is inline.
10628 NewFD->setImplicitlyInline();
10629 }
10630
10631 if (!isFriend && SC != SC_None) {
10632 // C++ [temp.expl.spec]p2:
10633 // The declaration in an explicit-specialization shall not be an
10634 // export-declaration. An explicit specialization shall not use a
10635 // storage-class-specifier other than thread_local.
10636 //
10637 // We diagnose friend declarations with storage-class-specifiers
10638 // elsewhere.
10639 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10641 diag::ext_explicit_specialization_storage_class)
10644 }
10645
10646 if (SC == SC_Static && !CurContext->isRecord() && DC->isRecord()) {
10647 assert(isa<CXXMethodDecl>(NewFD) &&
10648 "Out-of-line member function should be a CXXMethodDecl");
10649 // C++ [class.static]p1:
10650 // A data or function member of a class may be declared static
10651 // in a class definition, in which case it is a static member of
10652 // the class.
10653
10654 // Complain about the 'static' specifier if it's on an out-of-line
10655 // member function definition.
10656
10657 // MSVC permits the use of a 'static' storage specifier on an
10658 // out-of-line member function template declaration and class member
10659 // template declaration (MSVC versions before 2015), warn about this.
10661 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
10662 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
10663 (getLangOpts().MSVCCompat &&
10665 ? diag::ext_static_out_of_line
10666 : diag::err_static_out_of_line)
10669 }
10670 }
10671
10672 // C++11 [except.spec]p15:
10673 // A deallocation function with no exception-specification is treated
10674 // as if it were specified with noexcept(true).
10675 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
10676 if (Name.isAnyOperatorDelete() && getLangOpts().CPlusPlus11 && FPT &&
10677 !FPT->hasExceptionSpec())
10678 NewFD->setType(Context.getFunctionType(
10679 FPT->getReturnType(), FPT->getParamTypes(),
10681
10682 // C++20 [dcl.inline]/7
10683 // If an inline function or variable that is attached to a named module
10684 // is declared in a definition domain, it shall be defined in that
10685 // domain.
10686 // So, if the current declaration does not have a definition, we must
10687 // check at the end of the TU (or when the PMF starts) to see that we
10688 // have a definition at that point.
10689 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
10690 NewFD->isInNamedModule()) {
10691 PendingInlineFuncDecls.insert(NewFD);
10692 }
10693 }
10694
10695 // Filter out previous declarations that don't match the scope.
10698 isMemberSpecialization ||
10699 isFunctionTemplateSpecialization);
10700
10702
10703 // Handle GNU asm-label extension (encoded as an attribute).
10704 if (Expr *E = D.getAsmLabel()) {
10705 // The parser guarantees this is a string.
10707 NewFD->addAttr(
10708 AsmLabelAttr::Create(Context, SE->getString(), SE->getStrTokenLoc(0)));
10709 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
10710 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>::iterator I =
10712 if (I != ExtnameUndeclaredIdentifiers.end()) {
10713 if (isDeclExternC(NewFD)) {
10714 NewFD->addAttr(I->second);
10716 } else if (NewFD->getDeclContext()
10719 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
10720 << /*Variable*/0 << NewFD;
10721 }
10722 }
10723
10724 // Copy the parameter declarations from the declarator D to the function
10725 // declaration NewFD, if they are available. First scavenge them into Params.
10727 unsigned FTIIdx;
10728 if (D.isFunctionDeclarator(FTIIdx)) {
10730
10731 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
10732 // function that takes no arguments, not a function that takes a
10733 // single void argument.
10734 // We let through "const void" here because Sema::GetTypeForDeclarator
10735 // already checks for that case.
10736 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
10737 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
10738 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
10739 assert(Param->getDeclContext() != NewFD && "Was set before ?");
10740 Param->setDeclContext(NewFD);
10741 Params.push_back(Param);
10742
10743 if (Param->isInvalidDecl())
10744 NewFD->setInvalidDecl();
10745 }
10746 }
10747
10748 if (!getLangOpts().CPlusPlus) {
10749 // In C, find all the tag declarations from the prototype and move them
10750 // into the function DeclContext. Remove them from the surrounding tag
10751 // injection context of the function, which is typically but not always
10752 // the TU.
10753 DeclContext *PrototypeTagContext =
10755 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
10756 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
10757
10758 // We don't want to reparent enumerators. Look at their parent enum
10759 // instead.
10760 if (!TD) {
10761 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
10762 TD = cast<EnumDecl>(ECD->getDeclContext());
10763 }
10764 if (!TD)
10765 continue;
10766 DeclContext *TagDC = TD->getLexicalDeclContext();
10767 if (!TagDC->containsDecl(TD))
10768 continue;
10769 TagDC->removeDecl(TD);
10770 TD->setDeclContext(NewFD);
10771 NewFD->addDecl(TD);
10772
10773 // Preserve the lexical DeclContext if it is not the surrounding tag
10774 // injection context of the FD. In this example, the semantic context of
10775 // E will be f and the lexical context will be S, while both the
10776 // semantic and lexical contexts of S will be f:
10777 // void f(struct S { enum E { a } f; } s);
10778 if (TagDC != PrototypeTagContext)
10779 TD->setLexicalDeclContext(TagDC);
10780 }
10781 }
10782 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
10783 // When we're declaring a function with a typedef, typeof, etc as in the
10784 // following example, we'll need to synthesize (unnamed)
10785 // parameters for use in the declaration.
10786 //
10787 // @code
10788 // typedef void fn(int);
10789 // fn f;
10790 // @endcode
10791
10792 // Synthesize a parameter for each argument type.
10793 for (const auto &AI : FT->param_types()) {
10794 ParmVarDecl *Param =
10796 Param->setScopeInfo(0, Params.size());
10797 Params.push_back(Param);
10798 }
10799 } else {
10800 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
10801 "Should not need args for typedef of non-prototype fn");
10802 }
10803
10804 // Finally, we know we have the right number of parameters, install them.
10805 NewFD->setParams(Params);
10806
10807 // If this declarator is a declaration and not a definition, its parameters
10808 // will not be pushed onto a scope chain. That means we will not issue any
10809 // reserved identifier warnings for the declaration, but we will for the
10810 // definition. Handle those here.
10811 if (!D.isFunctionDefinition()) {
10812 for (const ParmVarDecl *PVD : Params)
10814 }
10815
10817 NewFD->addAttr(
10818 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc()));
10819
10820 // Functions returning a variably modified type violate C99 6.7.5.2p2
10821 // because all functions have linkage.
10822 if (!NewFD->isInvalidDecl() &&
10824 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
10825 NewFD->setInvalidDecl();
10826 }
10827
10828 // Apply an implicit SectionAttr if '#pragma clang section text' is active
10830 !NewFD->hasAttr<SectionAttr>())
10831 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
10832 Context, PragmaClangTextSection.SectionName,
10833 PragmaClangTextSection.PragmaLocation));
10834
10835 // Apply an implicit SectionAttr if #pragma code_seg is active.
10836 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
10837 !NewFD->hasAttr<SectionAttr>()) {
10838 NewFD->addAttr(SectionAttr::CreateImplicit(
10839 Context, CodeSegStack.CurrentValue->getString(),
10840 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate));
10841 if (UnifySection(CodeSegStack.CurrentValue->getString(),
10844 NewFD))
10845 NewFD->dropAttr<SectionAttr>();
10846 }
10847
10848 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
10849 // active.
10850 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
10851 !NewFD->hasAttr<StrictGuardStackCheckAttr>())
10852 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
10853 Context, PragmaClangTextSection.PragmaLocation));
10854
10855 // Apply an implicit CodeSegAttr from class declspec or
10856 // apply an implicit SectionAttr from #pragma code_seg if active.
10857 if (!NewFD->hasAttr<CodeSegAttr>()) {
10859 D.isFunctionDefinition())) {
10860 NewFD->addAttr(SAttr);
10861 }
10862 }
10863
10864 // Handle attributes.
10865 ProcessDeclAttributes(S, NewFD, D);
10867 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
10868 if (Context.getTargetInfo().getTriple().isAArch64() && NewTVA &&
10869 !NewTVA->isDefaultVersion() &&
10870 !Context.getTargetInfo().hasFeature("fmv")) {
10871 // Don't add to scope fmv functions declarations if fmv disabled
10872 AddToScope = false;
10873 return NewFD;
10874 }
10875
10876 if (getLangOpts().OpenCL || getLangOpts().HLSL) {
10877 // Neither OpenCL nor HLSL allow an address space qualifyer on a return
10878 // type.
10879 //
10880 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
10881 // type declaration will generate a compilation error.
10882 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
10883 if (AddressSpace != LangAS::Default) {
10884 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
10885 NewFD->setInvalidDecl();
10886 }
10887 }
10888
10889 if (!getLangOpts().CPlusPlus) {
10890 // Perform semantic checking on the function declaration.
10891 if (!NewFD->isInvalidDecl() && NewFD->isMain())
10892 CheckMain(NewFD, D.getDeclSpec());
10893
10894 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
10895 CheckMSVCRTEntryPoint(NewFD);
10896
10897 if (!NewFD->isInvalidDecl())
10899 isMemberSpecialization,
10901 else if (!Previous.empty())
10902 // Recover gracefully from an invalid redeclaration.
10903 D.setRedeclaration(true);
10904 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
10905 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
10906 "previous declaration set still overloaded");
10907
10908 // Diagnose no-prototype function declarations with calling conventions that
10909 // don't support variadic calls. Only do this in C and do it after merging
10910 // possibly prototyped redeclarations.
10911 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
10913 CallingConv CC = FT->getExtInfo().getCC();
10914 if (!supportsVariadicCall(CC)) {
10915 // Windows system headers sometimes accidentally use stdcall without
10916 // (void) parameters, so we relax this to a warning.
10917 int DiagID =
10918 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
10919 Diag(NewFD->getLocation(), DiagID)
10921 }
10922 }
10923
10927 NewFD->getReturnType(), NewFD->getReturnTypeSourceRange().getBegin(),
10929 } else {
10930 // C++11 [replacement.functions]p3:
10931 // The program's definitions shall not be specified as inline.
10932 //
10933 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
10934 //
10935 // Suppress the diagnostic if the function is __attribute__((used)), since
10936 // that forces an external definition to be emitted.
10937 if (D.getDeclSpec().isInlineSpecified() &&
10939 !NewFD->hasAttr<UsedAttr>())
10941 diag::ext_operator_new_delete_declared_inline)
10942 << NewFD->getDeclName();
10943
10944 if (const Expr *TRC = NewFD->getTrailingRequiresClause().ConstraintExpr) {
10945 // C++20 [dcl.decl.general]p4:
10946 // The optional requires-clause in an init-declarator or
10947 // member-declarator shall be present only if the declarator declares a
10948 // templated function.
10949 //
10950 // C++20 [temp.pre]p8:
10951 // An entity is templated if it is
10952 // - a template,
10953 // - an entity defined or created in a templated entity,
10954 // - a member of a templated entity,
10955 // - an enumerator for an enumeration that is a templated entity, or
10956 // - the closure type of a lambda-expression appearing in the
10957 // declaration of a templated entity.
10958 //
10959 // [Note 6: A local class, a local or block variable, or a friend
10960 // function defined in a templated entity is a templated entity.
10961 // — end note]
10962 //
10963 // A templated function is a function template or a function that is
10964 // templated. A templated class is a class template or a class that is
10965 // templated. A templated variable is a variable template or a variable
10966 // that is templated.
10967 if (!FunctionTemplate) {
10968 if (isFunctionTemplateSpecialization || isMemberSpecialization) {
10969 // C++ [temp.expl.spec]p8 (proposed resolution for CWG2847):
10970 // An explicit specialization shall not have a trailing
10971 // requires-clause unless it declares a function template.
10972 //
10973 // Since a friend function template specialization cannot be
10974 // definition, and since a non-template friend declaration with a
10975 // trailing requires-clause must be a definition, we diagnose
10976 // friend function template specializations with trailing
10977 // requires-clauses on the same path as explicit specializations
10978 // even though they aren't necessarily prohibited by the same
10979 // language rule.
10980 Diag(TRC->getBeginLoc(), diag::err_non_temp_spec_requires_clause)
10981 << isFriend;
10982 } else if (isFriend && NewFD->isTemplated() &&
10983 !D.isFunctionDefinition()) {
10984 // C++ [temp.friend]p9:
10985 // A non-template friend declaration with a requires-clause shall be
10986 // a definition.
10987 Diag(NewFD->getBeginLoc(),
10988 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def);
10989 NewFD->setInvalidDecl();
10990 } else if (!NewFD->isTemplated() ||
10991 !(isa<CXXMethodDecl>(NewFD) || D.isFunctionDefinition())) {
10992 Diag(TRC->getBeginLoc(),
10993 diag::err_constrained_non_templated_function);
10994 }
10995 }
10996 }
10997
10998 // We do not add HD attributes to specializations here because
10999 // they may have different constexpr-ness compared to their
11000 // templates and, after maybeAddHostDeviceAttrs() is applied,
11001 // may end up with different effective targets. Instead, a
11002 // specialization inherits its target attributes from its template
11003 // in the CheckFunctionTemplateSpecialization() call below.
11004 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
11006
11007 // Handle explicit specializations of function templates
11008 // and friend function declarations with an explicit
11009 // template argument list.
11010 if (isFunctionTemplateSpecialization) {
11011 bool isDependentSpecialization = false;
11012 if (isFriend) {
11013 // For friend function specializations, this is a dependent
11014 // specialization if its semantic context is dependent, its
11015 // qualifier is dependent, its type is dependent, or its template-id is
11016 // dependent.
11017 isDependentSpecialization =
11018 DC->isDependentContext() || NewFD->getQualifier().isDependent() ||
11019 NewFD->getType()->isDependentType() ||
11020 (HasExplicitTemplateArgs &&
11021 TemplateSpecializationType::
11022 anyInstantiationDependentTemplateArguments(
11023 TemplateArgs.arguments()));
11024 assert((!isDependentSpecialization ||
11025 (HasExplicitTemplateArgs == isDependentSpecialization)) &&
11026 "dependent friend function specialization without template "
11027 "args");
11028 } else {
11029 // For class-scope explicit specializations of function templates,
11030 // if the lexical context is dependent, then the specialization
11031 // is dependent.
11032 isDependentSpecialization =
11033 CurContext->isRecord() && CurContext->isDependentContext();
11034 }
11035
11036 TemplateArgumentListInfo *ExplicitTemplateArgs =
11037 HasExplicitTemplateArgs ? &TemplateArgs : nullptr;
11038 if (isDependentSpecialization) {
11039 // If it's a dependent specialization, it may not be possible
11040 // to determine the primary template (for explicit specializations)
11041 // or befriended declaration (for friends) until the enclosing
11042 // template is instantiated. In such cases, we store the declarations
11043 // found by name lookup and defer resolution until instantiation.
11045 NewFD, ExplicitTemplateArgs, Previous))
11046 NewFD->setInvalidDecl();
11047 } else if (!NewFD->isInvalidDecl()) {
11048 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs,
11049 Previous))
11050 NewFD->setInvalidDecl();
11051 }
11052 } else if (isMemberSpecialization && !FunctionTemplate) {
11054 NewFD->setInvalidDecl();
11055 }
11056
11057 // Perform semantic checking on the function declaration.
11058 if (!NewFD->isInvalidDecl() && NewFD->isMain())
11059 CheckMain(NewFD, D.getDeclSpec());
11060
11061 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
11062 CheckMSVCRTEntryPoint(NewFD);
11063
11064 if (!NewFD->isInvalidDecl())
11066 isMemberSpecialization,
11068 else if (!Previous.empty())
11069 // Recover gracefully from an invalid redeclaration.
11070 D.setRedeclaration(true);
11071
11072 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
11073 !D.isRedeclaration() ||
11074 Previous.getResultKind() != LookupResultKind::FoundOverloaded) &&
11075 "previous declaration set still overloaded");
11076
11077 NamedDecl *PrincipalDecl = (FunctionTemplate
11079 : NewFD);
11080
11081 if (isFriend && NewFD->getPreviousDecl()) {
11082 AccessSpecifier Access = AS_public;
11083 if (!NewFD->isInvalidDecl())
11084 Access = NewFD->getPreviousDecl()->getAccess();
11085
11086 NewFD->setAccess(Access);
11087 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
11088 }
11089
11090 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
11092 PrincipalDecl->setNonMemberOperator();
11093
11094 // If we have a function template, check the template parameter
11095 // list. This will check and merge default template arguments.
11096 if (FunctionTemplate) {
11097 FunctionTemplateDecl *PrevTemplate =
11098 FunctionTemplate->getPreviousDecl();
11099 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
11100 PrevTemplate ? PrevTemplate->getTemplateParameters()
11101 : nullptr,
11106 : (D.getCXXScopeSpec().isSet() &&
11107 DC && DC->isRecord() &&
11108 DC->isDependentContext())
11111 }
11112
11113 if (NewFD->isInvalidDecl()) {
11114 // Ignore all the rest of this.
11115 } else if (!D.isRedeclaration()) {
11116 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
11117 AddToScope };
11118 // Fake up an access specifier if it's supposed to be a class member.
11119 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
11120 NewFD->setAccess(AS_public);
11121
11122 // Qualified decls generally require a previous declaration.
11123 if (D.getCXXScopeSpec().isSet()) {
11124 // ...with the major exception of templated-scope or
11125 // dependent-scope friend declarations.
11126
11127 // TODO: we currently also suppress this check in dependent
11128 // contexts because (1) the parameter depth will be off when
11129 // matching friend templates and (2) we might actually be
11130 // selecting a friend based on a dependent factor. But there
11131 // are situations where these conditions don't apply and we
11132 // can actually do this check immediately.
11133 //
11134 // Unless the scope is dependent, it's always an error if qualified
11135 // redeclaration lookup found nothing at all. Diagnose that now;
11136 // nothing will diagnose that error later.
11137 if (isFriend &&
11139 (!Previous.empty() && CurContext->isDependentContext()))) {
11140 // ignore these
11141 } else if (NewFD->isCPUDispatchMultiVersion() ||
11142 NewFD->isCPUSpecificMultiVersion()) {
11143 // ignore this, we allow the redeclaration behavior here to create new
11144 // versions of the function.
11145 } else {
11146 // The user tried to provide an out-of-line definition for a
11147 // function that is a member of a class or namespace, but there
11148 // was no such member function declared (C++ [class.mfct]p2,
11149 // C++ [namespace.memdef]p2). For example:
11150 //
11151 // class X {
11152 // void f() const;
11153 // };
11154 //
11155 // void X::f() { } // ill-formed
11156 //
11157 // Complain about this problem, and attempt to suggest close
11158 // matches (e.g., those that differ only in cv-qualifiers and
11159 // whether the parameter types are references).
11160
11162 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
11163 AddToScope = ExtraArgs.AddToScope;
11164 return Result;
11165 }
11166 }
11167
11168 // Unqualified local friend declarations are required to resolve
11169 // to something.
11170 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
11172 *this, Previous, NewFD, ExtraArgs, true, S)) {
11173 AddToScope = ExtraArgs.AddToScope;
11174 return Result;
11175 }
11176 }
11177 } else if (!D.isFunctionDefinition() &&
11178 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
11179 !isFriend && !isFunctionTemplateSpecialization &&
11180 !isMemberSpecialization) {
11181 // An out-of-line member function declaration must also be a
11182 // definition (C++ [class.mfct]p2).
11183 // Note that this is not the case for explicit specializations of
11184 // function templates or member functions of class templates, per
11185 // C++ [temp.expl.spec]p2. We also allow these declarations as an
11186 // extension for compatibility with old SWIG code which likes to
11187 // generate them.
11188 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
11189 << D.getCXXScopeSpec().getRange();
11190 }
11191 }
11192
11193 if (getLangOpts().HLSL && D.isFunctionDefinition()) {
11194 // Any top level function could potentially be specified as an entry.
11195 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier())
11196 HLSL().ActOnTopLevelFunction(NewFD);
11197
11198 if (NewFD->hasAttr<HLSLShaderAttr>())
11199 HLSL().CheckEntryPoint(NewFD);
11200
11201 // Resources cannot be passed to functions that are not inlined.
11202 if (const NoInlineAttr *NoInline = NewFD->getAttr<NoInlineAttr>()) {
11203 for (const ParmVarDecl *PVD : NewFD->parameters()) {
11204 QualType ParamTy = PVD->getType().getNonReferenceType();
11205 QualType EltTy = Context.getBaseElementType(ParamTy);
11206 // `isCompleteType` forces completion of the element type without
11207 // reporting an error (diagnosed elsewhere) so the resource parameter
11208 // check is valid.
11209 if (!EltTy->isDependentType() &&
11210 isCompleteType(PVD->getLocation(), EltTy) &&
11211 ParamTy->isHLSLIntangibleType()) {
11212 Diag(PVD->getLocation(),
11213 diag::err_hlsl_resource_param_in_noinline_function)
11214 << ParamTy;
11215 Diag(NoInline->getLocation(), diag::note_attribute);
11216 }
11217 }
11218 }
11219 }
11220
11221 // If this is the first declaration of a library builtin function, add
11222 // attributes as appropriate.
11223 if (!D.isRedeclaration()) {
11224 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
11225 if (unsigned BuiltinID = II->getBuiltinID()) {
11226 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
11227 if (!InStdNamespace &&
11229 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
11230 // Validate the type matches unless this builtin is specified as
11231 // matching regardless of its declared type.
11232 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
11233 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11234 } else {
11236 LookupNecessaryTypesForBuiltin(S, BuiltinID);
11237 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
11238
11239 if (!Error && !BuiltinType.isNull() &&
11240 Context.hasSameFunctionTypeIgnoringExceptionSpec(
11241 NewFD->getType(), BuiltinType))
11242 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11243 }
11244 }
11245 } else if (InStdNamespace && NewFD->isInStdNamespace() &&
11246 isStdBuiltin(Context, NewFD, BuiltinID)) {
11247 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
11248 }
11249 }
11250 }
11251 }
11252
11253 ProcessPragmaWeak(S, NewFD);
11254 ProcessPragmaExport(NewFD);
11255 checkAttributesAfterMerging(*this, *NewFD);
11256
11258 // The above can add the format attribute for known builtin/library functions
11259 // which is required by the modular_format attribute, thus
11260 // validate modular_format now after those attributes have been added.
11261 checkModularFormatAttr(*this, *NewFD);
11262
11263 if (NewFD->hasAttr<OverloadableAttr>() &&
11264 !NewFD->getType()->getAs<FunctionProtoType>()) {
11265 Diag(NewFD->getLocation(),
11266 diag::err_attribute_overloadable_no_prototype)
11267 << NewFD;
11268 NewFD->dropAttr<OverloadableAttr>();
11269 }
11270
11271 // If there's a #pragma GCC visibility in scope, and this isn't a class
11272 // member, set the visibility of this function.
11273 if (!DC->isRecord() && NewFD->isExternallyVisible())
11275
11276 // If there's a #pragma clang arc_cf_code_audited in scope, consider
11277 // marking the function.
11278 ObjC().AddCFAuditedAttribute(NewFD);
11279
11280 // If this is a function definition, check if we have to apply any
11281 // attributes (i.e. optnone and no_builtin) due to a pragma.
11282 if (D.isFunctionDefinition()) {
11283 AddRangeBasedOptnone(NewFD);
11285 AddSectionMSAllocText(NewFD);
11287 }
11288
11289 // If this is the first declaration of an extern C variable, update
11290 // the map of such variables.
11291 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
11292 isIncompleteDeclExternC(*this, NewFD))
11294
11295 // Set this FunctionDecl's range up to the right paren.
11296 NewFD->setRangeEnd(D.getSourceRange().getEnd());
11297
11298 if (D.isRedeclaration() && !Previous.empty()) {
11299 NamedDecl *Prev = Previous.getRepresentativeDecl();
11300 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
11301 isMemberSpecialization ||
11302 isFunctionTemplateSpecialization,
11304 }
11305
11306 if (getLangOpts().CUDA) {
11307 if (IdentifierInfo *II = NewFD->getIdentifier()) {
11308 if (II->isStr(CUDA().getConfigureFuncName()) && !NewFD->isInvalidDecl() &&
11310 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11311 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11313 Context.setcudaConfigureCallDecl(NewFD);
11314 }
11315 if (II->isStr(CUDA().getGetParameterBufferFuncName()) &&
11316 !NewFD->isInvalidDecl() &&
11318 if (!R->castAs<FunctionType>()->getReturnType()->isPointerType())
11319 Diag(NewFD->getLocation(), diag::err_config_pointer_return)
11321 Context.setcudaGetParameterBufferDecl(NewFD);
11322 }
11323 if (II->isStr(CUDA().getLaunchDeviceFuncName()) &&
11324 !NewFD->isInvalidDecl() &&
11326 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
11327 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
11329 Context.setcudaLaunchDeviceDecl(NewFD);
11330 }
11331 }
11332 }
11333
11335
11336 if (getLangOpts().OpenCL && NewFD->hasAttr<DeviceKernelAttr>()) {
11337 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
11338 if (SC == SC_Static) {
11339 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
11340 D.setInvalidType();
11341 }
11342
11343 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
11344 if (!NewFD->getReturnType()->isVoidType()) {
11345 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
11346 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
11347 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
11348 : FixItHint());
11349 D.setInvalidType();
11350 }
11351
11353 for (auto *Param : NewFD->parameters())
11354 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
11355
11356 if (getLangOpts().OpenCLCPlusPlus) {
11357 if (DC->isRecord()) {
11358 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
11359 D.setInvalidType();
11360 }
11361 if (FunctionTemplate) {
11362 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
11363 D.setInvalidType();
11364 }
11365 }
11366 }
11367
11368 if (getLangOpts().CPlusPlus) {
11369 // Precalculate whether this is a friend function template with a constraint
11370 // that depends on an enclosing template, per [temp.friend]p9.
11371 if (isFriend && FunctionTemplate &&
11374
11375 // C++ [temp.friend]p9:
11376 // A friend function template with a constraint that depends on a
11377 // template parameter from an enclosing template shall be a definition.
11378 if (!D.isFunctionDefinition()) {
11379 Diag(NewFD->getBeginLoc(),
11380 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def);
11381 NewFD->setInvalidDecl();
11382 }
11383 }
11384
11385 if (FunctionTemplate) {
11386 if (NewFD->isInvalidDecl())
11387 FunctionTemplate->setInvalidDecl();
11388 return FunctionTemplate;
11389 }
11390
11391 if (isMemberSpecialization && !NewFD->isInvalidDecl())
11393 }
11394
11395 for (const ParmVarDecl *Param : NewFD->parameters()) {
11396 QualType PT = Param->getType();
11397
11398 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
11399 // types.
11400 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
11401 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
11402 QualType ElemTy = PipeTy->getElementType();
11403 if (ElemTy->isPointerOrReferenceType()) {
11404 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type);
11405 D.setInvalidType();
11406 }
11407 }
11408 }
11409 // WebAssembly tables can't be used as function parameters.
11410 if (Context.getTargetInfo().getTriple().isWasm()) {
11412 Diag(Param->getTypeSpecStartLoc(),
11413 diag::err_wasm_table_as_function_parameter);
11414 D.setInvalidType();
11415 }
11416 }
11417 }
11418
11419 // Diagnose availability attributes. Availability cannot be used on functions
11420 // that are run during load/unload.
11421 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
11422 if (NewFD->hasAttr<ConstructorAttr>()) {
11423 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11424 << 1;
11425 NewFD->dropAttr<AvailabilityAttr>();
11426 }
11427 if (NewFD->hasAttr<DestructorAttr>()) {
11428 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
11429 << 2;
11430 NewFD->dropAttr<AvailabilityAttr>();
11431 }
11432 }
11433
11434 // Diagnose no_builtin attribute on function declaration that are not a
11435 // definition.
11436 // FIXME: We should really be doing this in
11437 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
11438 // the FunctionDecl and at this point of the code
11439 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
11440 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11441 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
11442 switch (D.getFunctionDefinitionKind()) {
11445 Diag(NBA->getLocation(),
11446 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
11447 << NBA->getSpelling();
11448 break;
11450 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
11451 << NBA->getSpelling();
11452 break;
11454 break;
11455 }
11456
11457 // Similar to no_builtin logic above, at this point of the code
11458 // FunctionDecl::isThisDeclarationADefinition() always returns `false`
11459 // because Sema::ActOnStartOfFunctionDef has not been called yet.
11460 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
11461 !NewFD->isInvalidDecl() &&
11463 ExternalDeclarations.push_back(NewFD);
11464
11465 // Used for a warning on the 'next' declaration when used with a
11466 // `routine(name)`.
11467 if (getLangOpts().OpenACC)
11469
11470 return NewFD;
11471}
11472
11473/// Return a CodeSegAttr from a containing class. The Microsoft docs say
11474/// when __declspec(code_seg) "is applied to a class, all member functions of
11475/// the class and nested classes -- this includes compiler-generated special
11476/// member functions -- are put in the specified segment."
11477/// The actual behavior is a little more complicated. The Microsoft compiler
11478/// won't check outer classes if there is an active value from #pragma code_seg.
11479/// The CodeSeg is always applied from the direct parent but only from outer
11480/// classes when the #pragma code_seg stack is empty. See:
11481/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
11482/// available since MS has removed the page.
11484 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
11485 if (!Method)
11486 return nullptr;
11487 const CXXRecordDecl *Parent = Method->getParent();
11488 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11489 Attr *NewAttr = SAttr->clone(S.getASTContext());
11490 NewAttr->setImplicit(true);
11491 return NewAttr;
11492 }
11493
11494 // The Microsoft compiler won't check outer classes for the CodeSeg
11495 // when the #pragma code_seg stack is active.
11496 if (S.CodeSegStack.CurrentValue)
11497 return nullptr;
11498
11499 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
11500 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
11501 Attr *NewAttr = SAttr->clone(S.getASTContext());
11502 NewAttr->setImplicit(true);
11503 return NewAttr;
11504 }
11505 }
11506 return nullptr;
11507}
11508
11510 bool IsDefinition) {
11511 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
11512 return A;
11513 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
11514 CodeSegStack.CurrentValue)
11515 return SectionAttr::CreateImplicit(
11516 getASTContext(), CodeSegStack.CurrentValue->getString(),
11517 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate);
11518 return nullptr;
11519}
11520
11522 QualType NewT, QualType OldT) {
11524 return true;
11525
11526 // For dependently-typed local extern declarations and friends, we can't
11527 // perform a correct type check in general until instantiation:
11528 //
11529 // int f();
11530 // template<typename T> void g() { T f(); }
11531 //
11532 // (valid if g() is only instantiated with T = int).
11533 if (NewT->isDependentType() &&
11534 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
11535 return false;
11536
11537 // Similarly, if the previous declaration was a dependent local extern
11538 // declaration, we don't really know its type yet.
11539 if (OldT->isDependentType() && OldD->isLocalExternDecl())
11540 return false;
11541
11542 return true;
11543}
11544
11547 return true;
11548
11549 // Don't chain dependent friend function definitions until instantiation, to
11550 // permit cases like
11551 //
11552 // void func();
11553 // template<typename T> class C1 { friend void func() {} };
11554 // template<typename T> class C2 { friend void func() {} };
11555 //
11556 // ... which is valid if only one of C1 and C2 is ever instantiated.
11557 //
11558 // FIXME: This need only apply to function definitions. For now, we proxy
11559 // this by checking for a file-scope function. We do not want this to apply
11560 // to friend declarations nominating member functions, because that gets in
11561 // the way of access checks.
11563 return false;
11564
11565 auto *VD = dyn_cast<ValueDecl>(D);
11566 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
11567 return !VD || !PrevVD ||
11568 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
11569 PrevVD->getType());
11570}
11571
11572/// Check the target or target_version attribute of the function for
11573/// MultiVersion validity.
11574///
11575/// Returns true if there was an error, false otherwise.
11576static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
11577 const auto *TA = FD->getAttr<TargetAttr>();
11578 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11579
11580 assert((TA || TVA) && "Expecting target or target_version attribute");
11581
11583 enum ErrType { Feature = 0, Architecture = 1 };
11584
11585 if (TA) {
11586 ParsedTargetAttr ParseInfo =
11587 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
11588 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
11589 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11590 << Architecture << ParseInfo.CPU;
11591 return true;
11592 }
11593 for (const auto &Feat : ParseInfo.Features) {
11594 auto BareFeat = StringRef{Feat}.substr(1);
11595 if (Feat[0] == '-') {
11596 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11597 << Feature << ("no-" + BareFeat);
11598 return true;
11599 }
11600
11601 if (!TargetInfo.validateCpuSupports(BareFeat) ||
11602 !TargetInfo.isValidFeatureName(BareFeat) ||
11603 (BareFeat != "default" && TargetInfo.getFMVPriority(BareFeat) == 0)) {
11604 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11605 << Feature << BareFeat;
11606 return true;
11607 }
11608 }
11609 }
11610
11611 if (TVA) {
11613 ParsedTargetAttr ParseInfo;
11614 if (S.getASTContext().getTargetInfo().getTriple().isRISCV()) {
11615 ParseInfo =
11616 S.getASTContext().getTargetInfo().parseTargetAttr(TVA->getName());
11617 for (auto &Feat : ParseInfo.Features)
11618 Feats.push_back(StringRef{Feat}.substr(1));
11619 } else {
11620 assert(S.getASTContext().getTargetInfo().getTriple().isAArch64());
11621 TVA->getFeatures(Feats);
11622 }
11623 for (const auto &Feat : Feats) {
11624 if (!TargetInfo.validateCpuSupports(Feat)) {
11625 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
11626 << Feature << Feat;
11627 return true;
11628 }
11629 }
11630 }
11631 return false;
11632}
11633
11634// Provide a white-list of attributes that are allowed to be combined with
11635// multiversion functions.
11637 MultiVersionKind MVKind) {
11638 // Note: this list/diagnosis must match the list in
11639 // checkMultiversionAttributesAllSame.
11640 switch (Kind) {
11641 default:
11642 return false;
11643 case attr::ArmLocallyStreaming:
11644 return MVKind == MultiVersionKind::TargetVersion ||
11646 case attr::Used:
11647 return MVKind == MultiVersionKind::Target;
11648 case attr::NonNull:
11649 case attr::NoThrow:
11650 return true;
11651 }
11652}
11653
11655 const FunctionDecl *FD,
11656 const FunctionDecl *CausedFD,
11657 MultiVersionKind MVKind) {
11658 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
11659 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
11660 << static_cast<unsigned>(MVKind) << A;
11661 if (CausedFD)
11662 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
11663 return true;
11664 };
11665
11666 for (const Attr *A : FD->attrs()) {
11667 switch (A->getKind()) {
11668 case attr::CPUDispatch:
11669 case attr::CPUSpecific:
11670 if (MVKind != MultiVersionKind::CPUDispatch &&
11672 return Diagnose(S, A);
11673 break;
11674 case attr::Target:
11675 if (MVKind != MultiVersionKind::Target)
11676 return Diagnose(S, A);
11677 break;
11678 case attr::TargetVersion:
11679 if (MVKind != MultiVersionKind::TargetVersion &&
11681 return Diagnose(S, A);
11682 break;
11683 case attr::TargetClones:
11684 if (MVKind != MultiVersionKind::TargetClones &&
11686 return Diagnose(S, A);
11687 break;
11688 default:
11689 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
11690 return Diagnose(S, A);
11691 break;
11692 }
11693 }
11694 return false;
11695}
11696
11698 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
11699 const PartialDiagnostic &NoProtoDiagID,
11700 const PartialDiagnosticAt &NoteCausedDiagIDAt,
11701 const PartialDiagnosticAt &NoSupportDiagIDAt,
11702 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
11703 bool ConstexprSupported, bool CLinkageMayDiffer) {
11704 enum DoesntSupport {
11705 FuncTemplates = 0,
11706 VirtFuncs = 1,
11707 DeducedReturn = 2,
11708 Constructors = 3,
11709 Destructors = 4,
11710 DeletedFuncs = 5,
11711 DefaultedFuncs = 6,
11712 ConstexprFuncs = 7,
11713 ConstevalFuncs = 8,
11714 Lambda = 9,
11715 };
11716 enum Different {
11717 CallingConv = 0,
11718 ReturnType = 1,
11719 ConstexprSpec = 2,
11720 InlineSpec = 3,
11721 Linkage = 4,
11722 LanguageLinkage = 5,
11723 };
11724
11725 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
11726 !OldFD->getType()->getAs<FunctionProtoType>()) {
11727 Diag(OldFD->getLocation(), NoProtoDiagID);
11728 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
11729 return true;
11730 }
11731
11732 if (NoProtoDiagID.getDiagID() != 0 &&
11733 !NewFD->getType()->getAs<FunctionProtoType>())
11734 return Diag(NewFD->getLocation(), NoProtoDiagID);
11735
11736 if (!TemplatesSupported &&
11738 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11739 << FuncTemplates;
11740
11741 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
11742 if (NewCXXFD->isVirtual())
11743 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11744 << VirtFuncs;
11745
11746 if (isa<CXXConstructorDecl>(NewCXXFD))
11747 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11748 << Constructors;
11749
11750 if (isa<CXXDestructorDecl>(NewCXXFD))
11751 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11752 << Destructors;
11753 }
11754
11755 if (NewFD->isDeleted())
11756 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11757 << DeletedFuncs;
11758
11759 if (NewFD->isDefaulted())
11760 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11761 << DefaultedFuncs;
11762
11763 if (!ConstexprSupported && NewFD->isConstexpr())
11764 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11765 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
11766
11767 QualType NewQType = Context.getCanonicalType(NewFD->getType());
11768 const auto *NewType = cast<FunctionType>(NewQType);
11769 QualType NewReturnType = NewType->getReturnType();
11770
11771 if (NewReturnType->isUndeducedType())
11772 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
11773 << DeducedReturn;
11774
11775 // Ensure the return type is identical.
11776 if (OldFD) {
11777 QualType OldQType = Context.getCanonicalType(OldFD->getType());
11778 const auto *OldType = cast<FunctionType>(OldQType);
11779 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
11780 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
11781
11782 const auto *OldFPT = OldFD->getType()->getAs<FunctionProtoType>();
11783 const auto *NewFPT = NewFD->getType()->getAs<FunctionProtoType>();
11784
11785 bool ArmStreamingCCMismatched = false;
11786 if (OldFPT && NewFPT) {
11787 unsigned Diff =
11788 OldFPT->getAArch64SMEAttributes() ^ NewFPT->getAArch64SMEAttributes();
11789 // Arm-streaming, arm-streaming-compatible and non-streaming versions
11790 // cannot be mixed.
11793 ArmStreamingCCMismatched = true;
11794 }
11795
11796 if (OldTypeInfo.getCC() != NewTypeInfo.getCC() || ArmStreamingCCMismatched)
11797 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
11798
11799 QualType OldReturnType = OldType->getReturnType();
11800
11801 if (OldReturnType != NewReturnType)
11802 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
11803
11804 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
11805 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
11806
11807 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
11808 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
11809
11810 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
11811 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
11812
11813 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
11814 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
11815
11816 if (CheckEquivalentExceptionSpec(OldFPT, OldFD->getLocation(), NewFPT,
11817 NewFD->getLocation()))
11818 return true;
11819 }
11820 return false;
11821}
11822
11824 const FunctionDecl *NewFD,
11825 bool CausesMV,
11826 MultiVersionKind MVKind) {
11828 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
11829 if (OldFD)
11830 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11831 return true;
11832 }
11833
11834 bool IsCPUSpecificCPUDispatchMVKind =
11837
11838 if (CausesMV && OldFD &&
11839 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
11840 return true;
11841
11842 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
11843 return true;
11844
11845 // Only allow transition to MultiVersion if it hasn't been used.
11846 if (OldFD && CausesMV && OldFD->isUsed(false)) {
11847 S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
11848 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11849 return true;
11850 }
11851
11853 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
11855 S.PDiag(diag::note_multiversioning_caused_here)),
11857 S.PDiag(diag::err_multiversion_doesnt_support)
11858 << static_cast<unsigned>(MVKind)),
11860 S.PDiag(diag::err_multiversion_diff)),
11861 /*TemplatesSupported=*/false,
11862 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
11863 /*CLinkageMayDiffer=*/false);
11864}
11865
11866/// Check the validity of a multiversion function declaration that is the
11867/// first of its kind. Also sets the multiversion'ness' of the function itself.
11868///
11869/// This sets NewFD->isInvalidDecl() to true if there was an error.
11870///
11871/// Returns true if there was an error, false otherwise.
11874 assert(MVKind != MultiVersionKind::None &&
11875 "Function lacks multiversion attribute");
11876 const auto *TA = FD->getAttr<TargetAttr>();
11877 const auto *TVA = FD->getAttr<TargetVersionAttr>();
11878 // The target attribute only causes MV if this declaration is the default,
11879 // otherwise it is treated as a normal function.
11880 if (TA && !TA->isDefaultVersion())
11881 return false;
11882
11883 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
11884 FD->setInvalidDecl();
11885 return true;
11886 }
11887
11888 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
11889 FD->setInvalidDecl();
11890 return true;
11891 }
11892
11893 FD->setIsMultiVersion();
11894 return false;
11895}
11896
11898 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
11900 return true;
11901 }
11902
11903 return false;
11904}
11905
11907 if (!From->getASTContext().getTargetInfo().getTriple().isAArch64() &&
11908 !From->getASTContext().getTargetInfo().getTriple().isRISCV())
11909 return;
11910
11911 MultiVersionKind MVKindFrom = From->getMultiVersionKind();
11912 MultiVersionKind MVKindTo = To->getMultiVersionKind();
11913
11914 if (MVKindTo == MultiVersionKind::None &&
11915 (MVKindFrom == MultiVersionKind::TargetVersion ||
11916 MVKindFrom == MultiVersionKind::TargetClones))
11917 To->addAttr(TargetVersionAttr::CreateImplicit(
11918 To->getASTContext(), "default", To->getSourceRange()));
11919}
11920
11922 FunctionDecl *NewFD,
11923 bool &Redeclaration,
11924 NamedDecl *&OldDecl,
11926 assert(!OldFD->isMultiVersion() && "Unexpected MultiVersion");
11927
11928 const auto *NewTA = NewFD->getAttr<TargetAttr>();
11929 const auto *OldTA = OldFD->getAttr<TargetAttr>();
11930 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
11931 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
11932
11933 assert((NewTA || NewTVA) && "Excpecting target or target_version attribute");
11934
11935 // The definitions should be allowed in any order. If we have discovered
11936 // a new target version and the preceeding was the default, then add the
11937 // corresponding attribute to it.
11938 patchDefaultTargetVersion(NewFD, OldFD);
11939
11940 // If the old decl is NOT MultiVersioned yet, and we don't cause that
11941 // to change, this is a simple redeclaration.
11942 if (NewTA && !NewTA->isDefaultVersion() &&
11943 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
11944 return false;
11945
11946 // Otherwise, this decl causes MultiVersioning.
11947 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
11950 NewFD->setInvalidDecl();
11951 return true;
11952 }
11953
11954 if (CheckMultiVersionValue(S, NewFD)) {
11955 NewFD->setInvalidDecl();
11956 return true;
11957 }
11958
11959 // If this is 'default', permit the forward declaration.
11960 if ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
11961 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA)) {
11962 Redeclaration = true;
11963 OldDecl = OldFD;
11964 OldFD->setIsMultiVersion();
11965 NewFD->setIsMultiVersion();
11966 return false;
11967 }
11968
11969 if ((OldTA || OldTVA) && CheckMultiVersionValue(S, OldFD)) {
11970 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
11971 NewFD->setInvalidDecl();
11972 return true;
11973 }
11974
11975 if (NewTA) {
11976 ParsedTargetAttr OldParsed =
11978 OldTA->getFeaturesStr());
11979 llvm::sort(OldParsed.Features);
11980 ParsedTargetAttr NewParsed =
11982 NewTA->getFeaturesStr());
11983 // Sort order doesn't matter, it just needs to be consistent.
11984 llvm::sort(NewParsed.Features);
11985 if (OldParsed == NewParsed) {
11986 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
11987 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
11988 NewFD->setInvalidDecl();
11989 return true;
11990 }
11991 }
11992
11993 for (const auto *FD : OldFD->redecls()) {
11994 const auto *CurTA = FD->getAttr<TargetAttr>();
11995 const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
11996 // We allow forward declarations before ANY multiversioning attributes, but
11997 // nothing after the fact.
11999 ((NewTA && (!CurTA || CurTA->isInherited())) ||
12000 (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
12001 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
12002 << (NewTA ? 0 : 2);
12003 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
12004 NewFD->setInvalidDecl();
12005 return true;
12006 }
12007 }
12008
12009 OldFD->setIsMultiVersion();
12010 NewFD->setIsMultiVersion();
12011 Redeclaration = false;
12012 OldDecl = nullptr;
12013 Previous.clear();
12014 return false;
12015}
12016
12018 MultiVersionKind OldKind = Old->getMultiVersionKind();
12019 MultiVersionKind NewKind = New->getMultiVersionKind();
12020
12021 if (OldKind == NewKind || OldKind == MultiVersionKind::None ||
12022 NewKind == MultiVersionKind::None)
12023 return true;
12024
12025 if (Old->getASTContext().getTargetInfo().getTriple().isAArch64()) {
12026 switch (OldKind) {
12028 return NewKind == MultiVersionKind::TargetClones;
12030 return NewKind == MultiVersionKind::TargetVersion;
12031 default:
12032 return false;
12033 }
12034 } else {
12035 switch (OldKind) {
12037 return NewKind == MultiVersionKind::CPUSpecific;
12039 return NewKind == MultiVersionKind::CPUDispatch;
12040 default:
12041 return false;
12042 }
12043 }
12044}
12045
12046/// Check the validity of a new function declaration being added to an existing
12047/// multiversioned declaration collection.
12049 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
12050 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
12051 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
12053
12054 // Disallow mixing of multiversioning types.
12055 if (!MultiVersionTypesCompatible(OldFD, NewFD)) {
12056 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
12057 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
12058 NewFD->setInvalidDecl();
12059 return true;
12060 }
12061
12062 // Add the default target_version attribute if it's missing.
12063 patchDefaultTargetVersion(OldFD, NewFD);
12064 patchDefaultTargetVersion(NewFD, OldFD);
12065
12066 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12067 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12068 MultiVersionKind NewMVKind = NewFD->getMultiVersionKind();
12069 [[maybe_unused]] MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
12070
12071 ParsedTargetAttr NewParsed;
12072 if (NewTA) {
12074 NewTA->getFeaturesStr());
12075 llvm::sort(NewParsed.Features);
12076 }
12078 if (NewTVA) {
12079 NewTVA->getFeatures(NewFeats);
12080 llvm::sort(NewFeats);
12081 }
12082
12083 bool UseMemberUsingDeclRules =
12084 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
12085
12086 bool MayNeedOverloadableChecks =
12088
12089 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
12090 // of a previous member of the MultiVersion set.
12091 for (NamedDecl *ND : Previous) {
12092 FunctionDecl *CurFD = ND->getAsFunction();
12093 if (!CurFD || CurFD->isInvalidDecl())
12094 continue;
12095 if (MayNeedOverloadableChecks &&
12096 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
12097 continue;
12098
12099 switch (NewMVKind) {
12101 assert(OldMVKind == MultiVersionKind::TargetClones &&
12102 "Only target_clones can be omitted in subsequent declarations");
12103 break;
12105 const auto *CurTA = CurFD->getAttr<TargetAttr>();
12106 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
12107 NewFD->setIsMultiVersion();
12108 Redeclaration = true;
12109 OldDecl = ND;
12110 return false;
12111 }
12112
12113 ParsedTargetAttr CurParsed =
12115 CurTA->getFeaturesStr());
12116 llvm::sort(CurParsed.Features);
12117 if (CurParsed == NewParsed) {
12118 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12119 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12120 NewFD->setInvalidDecl();
12121 return true;
12122 }
12123 break;
12124 }
12126 if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12127 if (CurTVA->getName() == NewTVA->getName()) {
12128 NewFD->setIsMultiVersion();
12129 Redeclaration = true;
12130 OldDecl = ND;
12131 return false;
12132 }
12134 CurTVA->getFeatures(CurFeats);
12135 llvm::sort(CurFeats);
12136
12137 if (CurFeats == NewFeats) {
12138 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12139 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12140 NewFD->setInvalidDecl();
12141 return true;
12142 }
12143 } else if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12144 // Default
12145 if (NewFeats.empty())
12146 break;
12147
12148 for (unsigned I = 0; I < CurClones->featuresStrs_size(); ++I) {
12150 CurClones->getFeatures(CurFeats, I);
12151 llvm::sort(CurFeats);
12152
12153 if (CurFeats == NewFeats) {
12154 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12155 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12156 NewFD->setInvalidDecl();
12157 return true;
12158 }
12159 }
12160 }
12161 break;
12162 }
12164 assert(NewClones && "MultiVersionKind does not match attribute type");
12165 if (const auto *CurClones = CurFD->getAttr<TargetClonesAttr>()) {
12166 if (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
12167 !std::equal(CurClones->featuresStrs_begin(),
12168 CurClones->featuresStrs_end(),
12169 NewClones->featuresStrs_begin())) {
12170 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
12171 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12172 NewFD->setInvalidDecl();
12173 return true;
12174 }
12175 } else if (const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>()) {
12177 CurTVA->getFeatures(CurFeats);
12178 llvm::sort(CurFeats);
12179
12180 // Default
12181 if (CurFeats.empty())
12182 break;
12183
12184 for (unsigned I = 0; I < NewClones->featuresStrs_size(); ++I) {
12185 NewFeats.clear();
12186 NewClones->getFeatures(NewFeats, I);
12187 llvm::sort(NewFeats);
12188
12189 if (CurFeats == NewFeats) {
12190 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
12191 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12192 NewFD->setInvalidDecl();
12193 return true;
12194 }
12195 }
12196 break;
12197 }
12198 Redeclaration = true;
12199 OldDecl = CurFD;
12200 NewFD->setIsMultiVersion();
12201 return false;
12202 }
12205 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
12206 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
12207 // Handle CPUDispatch/CPUSpecific versions.
12208 // Only 1 CPUDispatch function is allowed, this will make it go through
12209 // the redeclaration errors.
12210 if (NewMVKind == MultiVersionKind::CPUDispatch &&
12211 CurFD->hasAttr<CPUDispatchAttr>()) {
12212 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
12213 std::equal(
12214 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
12215 NewCPUDisp->cpus_begin(),
12216 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12217 return Cur->getName() == New->getName();
12218 })) {
12219 NewFD->setIsMultiVersion();
12220 Redeclaration = true;
12221 OldDecl = ND;
12222 return false;
12223 }
12224
12225 // If the declarations don't match, this is an error condition.
12226 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
12227 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12228 NewFD->setInvalidDecl();
12229 return true;
12230 }
12231 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
12232 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
12233 std::equal(
12234 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
12235 NewCPUSpec->cpus_begin(),
12236 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
12237 return Cur->getName() == New->getName();
12238 })) {
12239 NewFD->setIsMultiVersion();
12240 Redeclaration = true;
12241 OldDecl = ND;
12242 return false;
12243 }
12244
12245 // Only 1 version of CPUSpecific is allowed for each CPU.
12246 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
12247 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
12248 if (CurII == NewII) {
12249 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
12250 << NewII;
12251 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
12252 NewFD->setInvalidDecl();
12253 return true;
12254 }
12255 }
12256 }
12257 }
12258 break;
12259 }
12260 }
12261 }
12262
12263 // Redeclarations of a target_clones function may omit the attribute, in which
12264 // case it will be inherited during declaration merging.
12265 if (NewMVKind == MultiVersionKind::None &&
12266 OldMVKind == MultiVersionKind::TargetClones) {
12267 NewFD->setIsMultiVersion();
12268 Redeclaration = true;
12269 OldDecl = OldFD;
12270 return false;
12271 }
12272
12273 // Else, this is simply a non-redecl case. Checking the 'value' is only
12274 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
12275 // handled in the attribute adding step.
12276 if ((NewTA || NewTVA) && CheckMultiVersionValue(S, NewFD)) {
12277 NewFD->setInvalidDecl();
12278 return true;
12279 }
12280
12281 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
12282 !OldFD->isMultiVersion(), NewMVKind)) {
12283 NewFD->setInvalidDecl();
12284 return true;
12285 }
12286
12287 // Permit forward declarations in the case where these two are compatible.
12288 if (!OldFD->isMultiVersion()) {
12289 OldFD->setIsMultiVersion();
12290 NewFD->setIsMultiVersion();
12291 Redeclaration = true;
12292 OldDecl = OldFD;
12293 return false;
12294 }
12295
12296 NewFD->setIsMultiVersion();
12297 Redeclaration = false;
12298 OldDecl = nullptr;
12299 Previous.clear();
12300 return false;
12301}
12302
12303/// Check the validity of a mulitversion function declaration.
12304/// Also sets the multiversion'ness' of the function itself.
12305///
12306/// This sets NewFD->isInvalidDecl() to true if there was an error.
12307///
12308/// Returns true if there was an error, false otherwise.
12310 bool &Redeclaration, NamedDecl *&OldDecl,
12312 const TargetInfo &TI = S.getASTContext().getTargetInfo();
12313
12314 // Check if FMV is disabled.
12315 if (TI.getTriple().isAArch64() && !TI.hasFeature("fmv"))
12316 return false;
12317
12318 const auto *NewTA = NewFD->getAttr<TargetAttr>();
12319 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
12320 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
12321 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
12322 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
12323 MultiVersionKind MVKind = NewFD->getMultiVersionKind();
12324
12325 // Main isn't allowed to become a multiversion function, however it IS
12326 // permitted to have 'main' be marked with the 'target' optimization hint,
12327 // for 'target_version' only default is allowed.
12328 if (NewFD->isMain()) {
12329 if (MVKind != MultiVersionKind::None &&
12330 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
12331 !(MVKind == MultiVersionKind::TargetVersion &&
12332 NewTVA->isDefaultVersion())) {
12333 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
12334 NewFD->setInvalidDecl();
12335 return true;
12336 }
12337 return false;
12338 }
12339
12340 // Target attribute on AArch64 is not used for multiversioning
12341 if (NewTA && TI.getTriple().isAArch64())
12342 return false;
12343
12344 // Target attribute on RISCV is not used for multiversioning
12345 if (NewTA && TI.getTriple().isRISCV())
12346 return false;
12347
12348 if (!OldDecl || !OldDecl->getAsFunction() ||
12349 !OldDecl->getDeclContext()->getRedeclContext()->Equals(
12350 NewFD->getDeclContext()->getRedeclContext())) {
12351 // If there's no previous declaration, AND this isn't attempting to cause
12352 // multiversioning, this isn't an error condition.
12353 if (MVKind == MultiVersionKind::None)
12354 return false;
12355 return CheckMultiVersionFirstFunction(S, NewFD);
12356 }
12357
12358 FunctionDecl *OldFD = OldDecl->getAsFunction();
12359
12360 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
12361 return false;
12362
12363 // Multiversioned redeclarations aren't allowed to omit the attribute, except
12364 // for target_clones and target_version.
12365 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
12368 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
12370 NewFD->setInvalidDecl();
12371 return true;
12372 }
12373
12374 if (!OldFD->isMultiVersion()) {
12375 switch (MVKind) {
12379 S, OldFD, NewFD, Redeclaration, OldDecl, Previous);
12381 if (OldFD->isUsed(false)) {
12382 NewFD->setInvalidDecl();
12383 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
12384 }
12385 OldFD->setIsMultiVersion();
12386 break;
12387
12391 break;
12392 }
12393 }
12394
12395 // At this point, we have a multiversion function decl (in OldFD) AND an
12396 // appropriate attribute in the current function decl (unless it's allowed to
12397 // omit the attribute). Resolve that these are still compatible with previous
12398 // declarations.
12399 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, NewCPUDisp,
12400 NewCPUSpec, NewClones, Redeclaration,
12401 OldDecl, Previous);
12402}
12403
12405 bool IsPure = NewFD->hasAttr<PureAttr>();
12406 bool IsConst = NewFD->hasAttr<ConstAttr>();
12407
12408 // If there are no pure or const attributes, there's nothing to check.
12409 if (!IsPure && !IsConst)
12410 return;
12411
12412 // If the function is marked both pure and const, we retain the const
12413 // attribute because it makes stronger guarantees than the pure attribute, and
12414 // we drop the pure attribute explicitly to prevent later confusion about
12415 // semantics.
12416 if (IsPure && IsConst) {
12417 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr);
12418 NewFD->dropAttrs<PureAttr>();
12419 }
12420
12421 // Constructors and destructors are functions which return void, so are
12422 // handled here as well.
12423 if (NewFD->getReturnType()->isVoidType()) {
12424 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void)
12425 << IsConst;
12426 NewFD->dropAttrs<PureAttr, ConstAttr>();
12427 }
12428}
12429
12432 bool IsMemberSpecialization,
12433 bool DeclIsDefn) {
12434 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
12435 "Variably modified return types are not handled here");
12436
12437 // Determine whether the type of this function should be merged with
12438 // a previous visible declaration. This never happens for functions in C++,
12439 // and always happens in C if the previous declaration was visible.
12440 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
12441 !Previous.isShadowed();
12442
12443 bool Redeclaration = false;
12444 NamedDecl *OldDecl = nullptr;
12445 bool MayNeedOverloadableChecks = false;
12446
12448 // Merge or overload the declaration with an existing declaration of
12449 // the same name, if appropriate.
12450 if (!Previous.empty()) {
12451 // Determine whether NewFD is an overload of PrevDecl or
12452 // a declaration that requires merging. If it's an overload,
12453 // there's no more work to do here; we'll just add the new
12454 // function to the scope.
12456 NamedDecl *Candidate = Previous.getRepresentativeDecl();
12457 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
12458 Redeclaration = true;
12459 OldDecl = Candidate;
12460 }
12461 } else {
12462 MayNeedOverloadableChecks = true;
12463 switch (CheckOverload(S, NewFD, Previous, OldDecl,
12464 /*NewIsUsingDecl*/ false)) {
12466 Redeclaration = true;
12467 break;
12468
12470 Redeclaration = true;
12471 break;
12472
12474 Redeclaration = false;
12475 break;
12476 }
12477 }
12478 }
12479
12480 // Check for a previous extern "C" declaration with this name.
12481 if (!Redeclaration &&
12483 if (!Previous.empty()) {
12484 // This is an extern "C" declaration with the same name as a previous
12485 // declaration, and thus redeclares that entity...
12486 Redeclaration = true;
12487 OldDecl = Previous.getFoundDecl();
12488 MergeTypeWithPrevious = false;
12489
12490 // ... except in the presence of __attribute__((overloadable)).
12491 if (OldDecl->hasAttr<OverloadableAttr>() ||
12492 NewFD->hasAttr<OverloadableAttr>()) {
12493 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
12494 MayNeedOverloadableChecks = true;
12495 Redeclaration = false;
12496 OldDecl = nullptr;
12497 }
12498 }
12499 }
12500 }
12501
12502 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
12503 return Redeclaration;
12504
12505 // PPC MMA non-pointer types are not allowed as function return types.
12506 if (Context.getTargetInfo().getTriple().isPPC64() &&
12507 PPC().CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
12508 NewFD->setInvalidDecl();
12509 }
12510
12511 CheckConstPureAttributesUsage(*this, NewFD);
12512
12513 // C++ [dcl.spec.auto.general]p12:
12514 // Return type deduction for a templated function with a placeholder in its
12515 // declared type occurs when the definition is instantiated even if the
12516 // function body contains a return statement with a non-type-dependent
12517 // operand.
12518 //
12519 // C++ [temp.dep.expr]p3:
12520 // An id-expression is type-dependent if it is a template-id that is not a
12521 // concept-id and is dependent; or if its terminal name is:
12522 // - [...]
12523 // - associated by name lookup with one or more declarations of member
12524 // functions of a class that is the current instantiation declared with a
12525 // return type that contains a placeholder type,
12526 // - [...]
12527 //
12528 // If this is a templated function with a placeholder in its return type,
12529 // make the placeholder type dependent since it won't be deduced until the
12530 // definition is instantiated. We do this here because it needs to happen
12531 // for implicitly instantiated member functions/member function templates.
12532 if (getLangOpts().CPlusPlus14 &&
12533 (NewFD->isDependentContext() &&
12534 NewFD->getReturnType()->isUndeducedType())) {
12535 const FunctionProtoType *FPT =
12536 NewFD->getType()->castAs<FunctionProtoType>();
12537 QualType NewReturnType = SubstAutoTypeDependent(FPT->getReturnType());
12538 NewFD->setType(Context.getFunctionType(NewReturnType, FPT->getParamTypes(),
12539 FPT->getExtProtoInfo()));
12540 }
12541
12542 // C++11 [dcl.constexpr]p8:
12543 // A constexpr specifier for a non-static member function that is not
12544 // a constructor declares that member function to be const.
12545 //
12546 // This needs to be delayed until we know whether this is an out-of-line
12547 // definition of a static member function.
12548 //
12549 // This rule is not present in C++1y, so we produce a backwards
12550 // compatibility warning whenever it happens in C++11.
12551 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
12552 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
12553 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
12555 CXXMethodDecl *OldMD = nullptr;
12556 if (OldDecl)
12557 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
12558 if (!OldMD || !OldMD->isStatic()) {
12559 const FunctionProtoType *FPT =
12562 EPI.TypeQuals.addConst();
12563 MD->setType(Context.getFunctionType(FPT->getReturnType(),
12564 FPT->getParamTypes(), EPI));
12565
12566 // Warn that we did this, if we're not performing template instantiation.
12567 // In that case, we'll have warned already when the template was defined.
12568 if (!inTemplateInstantiation()) {
12569 SourceLocation AddConstLoc;
12572 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
12573
12574 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
12575 << FixItHint::CreateInsertion(AddConstLoc, " const");
12576 }
12577 }
12578 }
12579
12580 if (Redeclaration) {
12581 // NewFD and OldDecl represent declarations that need to be
12582 // merged.
12583 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
12584 DeclIsDefn)) {
12585 NewFD->setInvalidDecl();
12586 return Redeclaration;
12587 }
12588
12589 Previous.clear();
12590 Previous.addDecl(OldDecl);
12591
12592 if (FunctionTemplateDecl *OldTemplateDecl =
12593 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
12594 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
12595 FunctionTemplateDecl *NewTemplateDecl
12597 assert(NewTemplateDecl && "Template/non-template mismatch");
12598
12599 // The call to MergeFunctionDecl above may have created some state in
12600 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
12601 // can add it as a redeclaration.
12602 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
12603
12604 NewFD->setPreviousDeclaration(OldFD);
12605 if (NewFD->isCXXClassMember()) {
12606 NewFD->setAccess(OldTemplateDecl->getAccess());
12607 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
12608 }
12609
12610 // If this is an explicit specialization of a member that is a function
12611 // template, mark it as a member specialization.
12612 if (IsMemberSpecialization &&
12613 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
12614 NewTemplateDecl->setMemberSpecialization();
12615 assert(OldTemplateDecl->isMemberSpecialization());
12616 // Explicit specializations of a member template do not inherit deleted
12617 // status from the parent member template that they are specializing.
12618 if (OldFD->isDeleted()) {
12619 // FIXME: This assert will not hold in the presence of modules.
12620 assert(OldFD->getCanonicalDecl() == OldFD);
12621 // FIXME: We need an update record for this AST mutation.
12622 OldFD->setDeletedAsWritten(false);
12623 }
12624 }
12625
12626 } else {
12627 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
12628 auto *OldFD = cast<FunctionDecl>(OldDecl);
12629 // This needs to happen first so that 'inline' propagates.
12630 NewFD->setPreviousDeclaration(OldFD);
12631 if (NewFD->isCXXClassMember())
12632 NewFD->setAccess(OldFD->getAccess());
12633 }
12634 }
12635 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
12636 !NewFD->getAttr<OverloadableAttr>()) {
12637 assert((Previous.empty() ||
12638 llvm::any_of(Previous,
12639 [](const NamedDecl *ND) {
12640 return ND->hasAttr<OverloadableAttr>();
12641 })) &&
12642 "Non-redecls shouldn't happen without overloadable present");
12643
12644 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
12645 const auto *FD = dyn_cast<FunctionDecl>(ND);
12646 return FD && !FD->hasAttr<OverloadableAttr>();
12647 });
12648
12649 if (OtherUnmarkedIter != Previous.end()) {
12650 Diag(NewFD->getLocation(),
12651 diag::err_attribute_overloadable_multiple_unmarked_overloads);
12652 Diag((*OtherUnmarkedIter)->getLocation(),
12653 diag::note_attribute_overloadable_prev_overload)
12654 << false;
12655
12656 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
12657 }
12658 }
12659
12660 if (LangOpts.OpenMP)
12662
12663 if (NewFD->hasAttr<SYCLKernelEntryPointAttr>())
12665
12666 if (NewFD->hasAttr<SYCLExternalAttr>())
12668
12669 // Semantic checking for this function declaration (in isolation).
12670
12671 if (getLangOpts().CPlusPlus) {
12672 // C++-specific checks.
12673 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
12675 } else if (CXXDestructorDecl *Destructor =
12676 dyn_cast<CXXDestructorDecl>(NewFD)) {
12677 // We check here for invalid destructor names.
12678 // If we have a friend destructor declaration that is dependent, we can't
12679 // diagnose right away because cases like this are still valid:
12680 // template <class T> struct A { friend T::X::~Y(); };
12681 // struct B { struct Y { ~Y(); }; using X = Y; };
12682 // template struct A<B>;
12684 (!Destructor->getFunctionObjectParameterType()->isDependentType() &&
12685 !Destructor->getDeclName().isDependentName())) {
12686 CanQualType ClassType =
12687 Context.getCanonicalTagType(Destructor->getParent());
12688
12689 DeclarationName Name =
12690 Context.DeclarationNames.getCXXDestructorName(ClassType);
12691 if (NewFD->getDeclName() != Name) {
12692 Diag(NewFD->getLocation(), diag::err_destructor_name);
12693 NewFD->setInvalidDecl();
12694 return Redeclaration;
12695 }
12696 }
12697 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
12698 if (auto *TD = Guide->getDescribedFunctionTemplate())
12700
12701 // A deduction guide is not on the list of entities that can be
12702 // explicitly specialized.
12703 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
12704 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
12705 << /*explicit specialization*/ 1;
12706 }
12707
12708 // Find any virtual functions that this function overrides.
12709 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
12710 if (!Method->isFunctionTemplateSpecialization() &&
12711 !Method->getDescribedFunctionTemplate() &&
12712 Method->isCanonicalDecl()) {
12713 AddOverriddenMethods(Method->getParent(), Method);
12714 }
12715 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
12716 // C++2a [class.virtual]p6
12717 // A virtual method shall not have a requires-clause.
12719 diag::err_constrained_virtual_method);
12720
12721 if (Method->isStatic())
12723 }
12724
12725 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
12726 ActOnConversionDeclarator(Conversion);
12727
12728 // Extra checking for C++ overloaded operators (C++ [over.oper]).
12729 if (NewFD->isOverloadedOperator() &&
12731 NewFD->setInvalidDecl();
12732 return Redeclaration;
12733 }
12734
12735 // Extra checking for C++0x literal operators (C++0x [over.literal]).
12736 if (NewFD->getLiteralIdentifier() &&
12738 NewFD->setInvalidDecl();
12739 return Redeclaration;
12740 }
12741
12742 // In C++, check default arguments now that we have merged decls. Unless
12743 // the lexical context is the class, because in this case this is done
12744 // during delayed parsing anyway.
12745 if (!CurContext->isRecord())
12747
12748 // If this function is declared as being extern "C", then check to see if
12749 // the function returns a UDT (class, struct, or union type) that is not C
12750 // compatible, and if it does, warn the user.
12751 // But, issue any diagnostic on the first declaration only.
12752 if (Previous.empty() && NewFD->isExternC()) {
12753 QualType R = NewFD->getReturnType();
12754 if (R->isIncompleteType() && !R->isVoidType())
12755 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
12756 << NewFD << R;
12757 else if (!R.isPODType(Context) && !R->isVoidType() &&
12758 !R->isObjCObjectPointerType())
12759 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
12760 }
12761
12762 // C++1z [dcl.fct]p6:
12763 // [...] whether the function has a non-throwing exception-specification
12764 // [is] part of the function type
12765 //
12766 // This results in an ABI break between C++14 and C++17 for functions whose
12767 // declared type includes an exception-specification in a parameter or
12768 // return type. (Exception specifications on the function itself are OK in
12769 // most cases, and exception specifications are not permitted in most other
12770 // contexts where they could make it into a mangling.)
12771 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
12772 auto HasNoexcept = [&](QualType T) -> bool {
12773 // Strip off declarator chunks that could be between us and a function
12774 // type. We don't need to look far, exception specifications are very
12775 // restricted prior to C++17.
12776 if (auto *RT = T->getAs<ReferenceType>())
12777 T = RT->getPointeeType();
12778 else if (T->isAnyPointerType())
12779 T = T->getPointeeType();
12780 else if (auto *MPT = T->getAs<MemberPointerType>())
12781 T = MPT->getPointeeType();
12782 if (auto *FPT = T->getAs<FunctionProtoType>())
12783 if (FPT->isNothrow())
12784 return true;
12785 return false;
12786 };
12787
12788 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
12789 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
12790 for (QualType T : FPT->param_types())
12791 AnyNoexcept |= HasNoexcept(T);
12792 if (AnyNoexcept)
12793 Diag(NewFD->getLocation(),
12794 diag::warn_cxx17_compat_exception_spec_in_signature)
12795 << NewFD;
12796 }
12797
12798 if (!Redeclaration && LangOpts.CUDA) {
12799 bool IsKernel = NewFD->hasAttr<CUDAGlobalAttr>();
12800 for (auto *Parm : NewFD->parameters()) {
12801 if (!Parm->getType()->isDependentType() &&
12802 Parm->hasAttr<CUDAGridConstantAttr>() &&
12803 !(IsKernel && Parm->getType().isConstQualified()))
12804 Diag(Parm->getAttr<CUDAGridConstantAttr>()->getLocation(),
12805 diag::err_cuda_grid_constant_not_allowed);
12806 }
12808 }
12809 }
12810
12811 if (DeclIsDefn && Context.getTargetInfo().getTriple().isAArch64())
12813
12814 return Redeclaration;
12815}
12816
12818 // [basic.start.main]p3
12819 // The main function shall not be declared with C linkage-specification.
12820 if (FD->isExternCContext())
12821 Diag(FD->getLocation(), diag::ext_main_invalid_linkage_specification);
12822
12823 // C++11 [basic.start.main]p3:
12824 // A program that [...] declares main to be inline, static or
12825 // constexpr is ill-formed.
12826 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
12827 // appear in a declaration of main.
12828 // static main is not an error under C99, but we should warn about it.
12829 // We accept _Noreturn main as an extension.
12830 if (FD->getStorageClass() == SC_Static)
12832 ? diag::err_static_main : diag::warn_static_main)
12834 if (FD->isInlineSpecified())
12835 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
12837 if (DS.isNoreturnSpecified()) {
12838 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
12839 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
12840 Diag(NoreturnLoc, diag::ext_noreturn_main);
12841 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
12842 << FixItHint::CreateRemoval(NoreturnRange);
12843 }
12844 if (FD->isConstexpr()) {
12845 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
12846 << FD->isConsteval()
12849 }
12850
12851 if (getLangOpts().OpenCL) {
12852 Diag(FD->getLocation(), diag::err_opencl_no_main)
12853 << FD->hasAttr<DeviceKernelAttr>();
12854 FD->setInvalidDecl();
12855 return;
12856 }
12857
12858 if (FD->hasAttr<SYCLExternalAttr>()) {
12859 Diag(FD->getLocation(), diag::err_sycl_external_invalid_main)
12860 << FD->getAttr<SYCLExternalAttr>();
12861 FD->setInvalidDecl();
12862 return;
12863 }
12864
12865 // Functions named main in hlsl are default entries, but don't have specific
12866 // signatures they are required to conform to.
12867 if (getLangOpts().HLSL)
12868 return;
12869
12870 QualType T = FD->getType();
12871 assert(T->isFunctionType() && "function decl is not of function type");
12872 const FunctionType* FT = T->castAs<FunctionType>();
12873
12874 // Set default calling convention for main()
12875 if (FT->getCallConv() != CC_C) {
12876 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
12877 FD->setType(QualType(FT, 0));
12878 T = Context.getCanonicalType(FD->getType());
12879 }
12880
12882 // In C with GNU extensions we allow main() to have non-integer return
12883 // type, but we should warn about the extension, and we disable the
12884 // implicit-return-zero rule.
12885
12886 // GCC in C mode accepts qualified 'int'.
12887 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
12888 FD->setHasImplicitReturnZero(true);
12889 else {
12890 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
12891 SourceRange RTRange = FD->getReturnTypeSourceRange();
12892 if (RTRange.isValid())
12893 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
12894 << FixItHint::CreateReplacement(RTRange, "int");
12895 }
12896 } else {
12897 // In C and C++, main magically returns 0 if you fall off the end;
12898 // set the flag which tells us that.
12899 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
12900
12901 // All the standards say that main() should return 'int'.
12902 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
12903 FD->setHasImplicitReturnZero(true);
12904 else {
12905 // Otherwise, this is just a flat-out error.
12906 SourceRange RTRange = FD->getReturnTypeSourceRange();
12907 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
12908 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
12909 : FixItHint());
12910 FD->setInvalidDecl(true);
12911 }
12912
12913 // [basic.start.main]p3:
12914 // A program that declares a function main that belongs to the global scope
12915 // and is attached to a named module is ill-formed.
12916 if (FD->isInNamedModule()) {
12917 const SourceLocation start = FD->getTypeSpecStartLoc();
12918 Diag(start, diag::warn_main_in_named_module)
12919 << FixItHint::CreateInsertion(start, "extern \"C++\" ", true);
12920 }
12921 }
12922
12923 // Treat protoless main() as nullary.
12924 if (isa<FunctionNoProtoType>(FT)) return;
12925
12927 unsigned nparams = FTP->getNumParams();
12928 assert(FD->getNumParams() == nparams);
12929
12930 bool HasExtraParameters = (nparams > 3);
12931
12932 if (FTP->isVariadic()) {
12933 Diag(FD->getLocation(), diag::ext_variadic_main);
12934 // FIXME: if we had information about the location of the ellipsis, we
12935 // could add a FixIt hint to remove it as a parameter.
12936 }
12937
12938 // Darwin passes an undocumented fourth argument of type char**. If
12939 // other platforms start sprouting these, the logic below will start
12940 // getting shifty.
12941 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
12942 HasExtraParameters = false;
12943
12944 if (HasExtraParameters) {
12945 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
12946 FD->setInvalidDecl(true);
12947 nparams = 3;
12948 }
12949
12950 // FIXME: a lot of the following diagnostics would be improved
12951 // if we had some location information about types.
12952
12953 QualType CharPP =
12954 Context.getPointerType(Context.getPointerType(Context.CharTy));
12955 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
12956
12957 for (unsigned i = 0; i < nparams; ++i) {
12958 QualType AT = FTP->getParamType(i);
12959
12960 bool mismatch = true;
12961
12962 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
12963 mismatch = false;
12964 else if (Expected[i] == CharPP) {
12965 // As an extension, the following forms are okay:
12966 // char const **
12967 // char const * const *
12968 // char * const *
12969
12971 const PointerType* PT;
12972 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
12973 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
12974 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
12975 Context.CharTy)) {
12976 qs.removeConst();
12977 mismatch = !qs.empty();
12978 }
12979 }
12980
12981 if (mismatch) {
12982 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
12983 // TODO: suggest replacing given type with expected type
12984 FD->setInvalidDecl(true);
12985 }
12986 }
12987
12988 if (nparams == 1 && !FD->isInvalidDecl()) {
12989 Diag(FD->getLocation(), diag::warn_main_one_arg);
12990 }
12991
12992 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
12993 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
12994 FD->setInvalidDecl();
12995 }
12996}
12997
12998static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
12999
13000 // Default calling convention for main and wmain is __cdecl
13001 if (FD->getName() == "main" || FD->getName() == "wmain")
13002 return false;
13003
13004 // Default calling convention for MinGW and Cygwin is __cdecl
13005 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
13006 if (T.isOSCygMing())
13007 return false;
13008
13009 // Default calling convention for WinMain, wWinMain and DllMain
13010 // is __stdcall on 32 bit Windows
13011 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
13012 return true;
13013
13014 return false;
13015}
13016
13018 QualType T = FD->getType();
13019 assert(T->isFunctionType() && "function decl is not of function type");
13020 const FunctionType *FT = T->castAs<FunctionType>();
13021
13022 // Set an implicit return of 'zero' if the function can return some integral,
13023 // enumeration, pointer or nullptr type.
13027 // DllMain is exempt because a return value of zero means it failed.
13028 if (FD->getName() != "DllMain")
13029 FD->setHasImplicitReturnZero(true);
13030
13031 // Explicitly specified calling conventions are applied to MSVC entry points
13032 if (!hasExplicitCallingConv(T)) {
13033 if (isDefaultStdCall(FD, *this)) {
13034 if (FT->getCallConv() != CC_X86StdCall) {
13035 FT = Context.adjustFunctionType(
13037 FD->setType(QualType(FT, 0));
13038 }
13039 } else if (FT->getCallConv() != CC_C) {
13040 FT = Context.adjustFunctionType(FT,
13042 FD->setType(QualType(FT, 0));
13043 }
13044 }
13045
13046 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
13047 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
13048 FD->setInvalidDecl();
13049 }
13050}
13051
13053 // FIXME: Need strict checking. In C89, we need to check for
13054 // any assignment, increment, decrement, function-calls, or
13055 // commas outside of a sizeof. In C99, it's the same list,
13056 // except that the aforementioned are allowed in unevaluated
13057 // expressions. Everything else falls under the
13058 // "may accept other forms of constant expressions" exception.
13059 //
13060 // Regular C++ code will not end up here (exceptions: language extensions,
13061 // OpenCL C++ etc), so the constant expression rules there don't matter.
13062 if (Init->isValueDependent()) {
13063 assert(Init->containsErrors() &&
13064 "Dependent code should only occur in error-recovery path.");
13065 return true;
13066 }
13067 const Expr *Culprit;
13068 if (Init->isConstantInitializer(Context, /*ForRef=*/false, &Culprit))
13069 return false;
13070
13071 // The culprit reported by isConstantInitializer() may be wrapped in implicit
13072 // casts and parentheses that it does not look through: under ARC an
13073 // object-pointer initializer is an `ImplicitCastExpr
13074 // <ARCReclaimReturnedObject>`, an `id`-typed (or otherwise differently-typed)
13075 // variable adds an `ImplicitCastExpr <BitCast>` on top, and a parenthesized
13076 // initializer such as `(@{...})` adds a `ParenExpr`. Strip all of these so
13077 // the ObjC-specific classification and per-element reporting below can see
13078 // the underlying literal regardless of how it is wrapped.
13079 const Expr *CulpritLiteral = Culprit->IgnoreParenImpCasts();
13080
13081 // Emit ObjC-specific diagnostics for non-constant literals at file scope.
13082 if (getLangOpts().ObjCConstantLiterals &&
13083 isa<ObjCObjectLiteral>(CulpritLiteral)) {
13084
13085 // For collection literals, iterate the elements to point at the specific
13086 // offender. These per-element checks mirror the constant-initializer rules
13087 // applied when the literal was built (see SemaObjC::BuildObjCArrayLiteral
13088 // and SemaObjC::BuildObjCDictionaryLiteral): each element must itself be a
13089 // constant object literal, and dictionary keys must additionally be string
13090 // literals. Elements, keys and values are wrapped in an implicit BitCast to
13091 // `id`, so the isa<> classification is done on the unwrapped expression.
13092 if (const auto *ALE = dyn_cast<ObjCArrayLiteral>(CulpritLiteral)) {
13093 for (const Expr *Elm : ALE->elements()) {
13094 if (!isa<ObjCObjectLiteral>(Elm->IgnoreImpCasts()) ||
13095 !Elm->isConstantInitializer(Context)) {
13096 Diag(Elm->getExprLoc(),
13097 diag::err_objc_literal_nonconstant_at_file_scope)
13098 << ObjC().CheckLiteralKind(Init) << Elm->getSourceRange();
13099 return true;
13100 }
13101 }
13102 }
13103
13104 if (const auto *DLE = dyn_cast<ObjCDictionaryLiteral>(CulpritLiteral)) {
13105 for (size_t I = 0, N = DLE->getNumElements(); I != N; ++I) {
13106 const ObjCDictionaryElement Elm = DLE->getKeyValueElement(I);
13107
13108 // Keys must be constant string literals.
13111 Diag(Elm.Key->getExprLoc(),
13112 diag::err_objc_literal_nonconstant_at_file_scope)
13114 return true;
13115 }
13116
13117 // Values must be constant object literals.
13120 Diag(Elm.Value->getExprLoc(),
13121 diag::err_objc_literal_nonconstant_at_file_scope)
13123 return true;
13124 }
13125 }
13126 }
13127
13128 Diag(CulpritLiteral->getExprLoc(),
13129 diag::err_objc_literal_nonconstant_at_file_scope)
13130 << ObjC().CheckLiteralKind(Init) << CulpritLiteral->getSourceRange();
13131 return true;
13132 }
13133
13134 Diag(Culprit->getExprLoc(), DiagID) << Culprit->getSourceRange();
13135 return true;
13136}
13137
13138namespace {
13139 // Visits an initialization expression to see if OrigDecl is evaluated in
13140 // its own initialization and throws a warning if it does.
13141 class SelfReferenceChecker
13142 : public EvaluatedExprVisitor<SelfReferenceChecker> {
13143 Sema &S;
13144 Decl *OrigDecl;
13145 bool isRecordType;
13146 bool isPODType;
13147 bool isReferenceType;
13148 bool isInCXXOperatorCall;
13149
13150 bool isInitList;
13151 llvm::SmallVector<unsigned, 4> InitFieldIndex;
13152
13153 public:
13155
13156 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
13157 S(S), OrigDecl(OrigDecl) {
13158 isPODType = false;
13159 isRecordType = false;
13160 isReferenceType = false;
13161 isInCXXOperatorCall = false;
13162 isInitList = false;
13163 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
13164 isPODType = VD->getType().isPODType(S.Context);
13165 isRecordType = VD->getType()->isRecordType();
13166 isReferenceType = VD->getType()->isReferenceType();
13167 }
13168 }
13169
13170 // For most expressions, just call the visitor. For initializer lists,
13171 // track the index of the field being initialized since fields are
13172 // initialized in order allowing use of previously initialized fields.
13173 void CheckExpr(Expr *E) {
13174 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
13175 if (!InitList) {
13176 Visit(E);
13177 return;
13178 }
13179
13180 // Track and increment the index here.
13181 isInitList = true;
13182 InitFieldIndex.push_back(0);
13183 for (auto *Child : InitList->children()) {
13184 CheckExpr(cast<Expr>(Child));
13185 ++InitFieldIndex.back();
13186 }
13187 InitFieldIndex.pop_back();
13188 }
13189
13190 // Returns true if MemberExpr is checked and no further checking is needed.
13191 // Returns false if additional checking is required.
13192 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
13193 llvm::SmallVector<FieldDecl*, 4> Fields;
13194 Expr *Base = E;
13195 bool ReferenceField = false;
13196
13197 // Get the field members used.
13198 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13199 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
13200 if (!FD)
13201 return false;
13202 Fields.push_back(FD);
13203 if (FD->getType()->isReferenceType())
13204 ReferenceField = true;
13205 Base = ME->getBase()->IgnoreParenImpCasts();
13206 }
13207
13208 // Keep checking only if the base Decl is the same.
13209 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
13210 if (!DRE || DRE->getDecl() != OrigDecl)
13211 return false;
13212
13213 // A reference field can be bound to an unininitialized field.
13214 if (CheckReference && !ReferenceField)
13215 return true;
13216
13217 // Convert FieldDecls to their index number.
13218 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
13219 for (const FieldDecl *I : llvm::reverse(Fields))
13220 UsedFieldIndex.push_back(I->getFieldIndex());
13221
13222 // See if a warning is needed by checking the first difference in index
13223 // numbers. If field being used has index less than the field being
13224 // initialized, then the use is safe.
13225 for (auto UsedIter = UsedFieldIndex.begin(),
13226 UsedEnd = UsedFieldIndex.end(),
13227 OrigIter = InitFieldIndex.begin(),
13228 OrigEnd = InitFieldIndex.end();
13229 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
13230 if (*UsedIter < *OrigIter)
13231 return true;
13232 if (*UsedIter > *OrigIter)
13233 break;
13234 }
13235
13236 // TODO: Add a different warning which will print the field names.
13237 HandleDeclRefExpr(DRE);
13238 return true;
13239 }
13240
13241 // For most expressions, the cast is directly above the DeclRefExpr.
13242 // For conditional operators, the cast can be outside the conditional
13243 // operator if both expressions are DeclRefExpr's.
13244 void HandleValue(Expr *E) {
13245 E = E->IgnoreParens();
13246 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
13247 HandleDeclRefExpr(DRE);
13248 return;
13249 }
13250
13251 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
13252 Visit(CO->getCond());
13253 HandleValue(CO->getTrueExpr());
13254 HandleValue(CO->getFalseExpr());
13255 return;
13256 }
13257
13258 if (BinaryConditionalOperator *BCO =
13259 dyn_cast<BinaryConditionalOperator>(E)) {
13260 Visit(BCO->getCond());
13261 HandleValue(BCO->getFalseExpr());
13262 return;
13263 }
13264
13265 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
13266 if (Expr *SE = OVE->getSourceExpr())
13267 HandleValue(SE);
13268 return;
13269 }
13270
13271 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13272 if (BO->getOpcode() == BO_Comma) {
13273 Visit(BO->getLHS());
13274 HandleValue(BO->getRHS());
13275 return;
13276 }
13277 }
13278
13279 if (isa<MemberExpr>(E)) {
13280 if (isInitList) {
13281 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
13282 false /*CheckReference*/))
13283 return;
13284 }
13285
13286 Expr *Base = E->IgnoreParenImpCasts();
13287 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13288 // Check for static member variables and don't warn on them.
13289 if (!isa<FieldDecl>(ME->getMemberDecl()))
13290 return;
13291 Base = ME->getBase()->IgnoreParenImpCasts();
13292 }
13293 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
13294 HandleDeclRefExpr(DRE);
13295 return;
13296 }
13297
13298 Visit(E);
13299 }
13300
13301 // Reference types not handled in HandleValue are handled here since all
13302 // uses of references are bad, not just r-value uses.
13303 void VisitDeclRefExpr(DeclRefExpr *E) {
13304 if (isReferenceType)
13305 HandleDeclRefExpr(E);
13306 }
13307
13308 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13309 if (E->getCastKind() == CK_LValueToRValue) {
13310 HandleValue(E->getSubExpr());
13311 return;
13312 }
13313
13314 Inherited::VisitImplicitCastExpr(E);
13315 }
13316
13317 void VisitMemberExpr(MemberExpr *E) {
13318 if (isInitList) {
13319 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
13320 return;
13321 }
13322
13323 // Don't warn on arrays since they can be treated as pointers.
13324 if (E->getType()->canDecayToPointerType()) return;
13325
13326 // Warn when a non-static method call is followed by non-static member
13327 // field accesses, which is followed by a DeclRefExpr.
13328 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
13329 bool Warn = (MD && !MD->isStatic());
13330 Expr *Base = E->getBase()->IgnoreParenImpCasts();
13331 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
13332 if (!isa<FieldDecl>(ME->getMemberDecl()))
13333 Warn = false;
13334 Base = ME->getBase()->IgnoreParenImpCasts();
13335 }
13336
13337 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
13338 if (Warn)
13339 HandleDeclRefExpr(DRE);
13340 return;
13341 }
13342
13343 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
13344 // Visit that expression.
13345 Visit(Base);
13346 }
13347
13348 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
13349 llvm::SaveAndRestore CxxOpCallScope(isInCXXOperatorCall, true);
13350 Expr *Callee = E->getCallee();
13351
13352 if (isa<UnresolvedLookupExpr>(Callee))
13353 return Inherited::VisitCXXOperatorCallExpr(E);
13354
13355 Visit(Callee);
13356 for (auto Arg: E->arguments())
13357 HandleValue(Arg->IgnoreParenImpCasts());
13358 }
13359
13360 void VisitLambdaExpr(LambdaExpr *E) {
13361 if (!isInCXXOperatorCall) {
13362 Inherited::VisitLambdaExpr(E);
13363 return;
13364 }
13365
13366 for (Expr *Init : E->capture_inits())
13367 if (DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Init))
13368 HandleDeclRefExpr(DRE);
13369 else if (Init)
13370 Visit(Init);
13371 }
13372
13373 void VisitUnaryOperator(UnaryOperator *E) {
13374 // For POD record types, addresses of its own members are well-defined.
13375 if (E->getOpcode() == UO_AddrOf && isRecordType &&
13377 if (!isPODType)
13378 HandleValue(E->getSubExpr());
13379 return;
13380 }
13381
13382 if (E->isIncrementDecrementOp()) {
13383 HandleValue(E->getSubExpr());
13384 return;
13385 }
13386
13387 Inherited::VisitUnaryOperator(E);
13388 }
13389
13390 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
13391
13392 void VisitCXXConstructExpr(CXXConstructExpr *E) {
13393 if (E->getConstructor()->isCopyConstructor()) {
13394 Expr *ArgExpr = E->getArg(0);
13395 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
13396 if (ILE->getNumInits() == 1)
13397 ArgExpr = ILE->getInit(0);
13398 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
13399 if (ICE->getCastKind() == CK_NoOp)
13400 ArgExpr = ICE->getSubExpr();
13401 HandleValue(ArgExpr);
13402 return;
13403 }
13404 Inherited::VisitCXXConstructExpr(E);
13405 }
13406
13407 void VisitCallExpr(CallExpr *E) {
13408 // Treat std::move as a use.
13409 if (E->isCallToStdMove()) {
13410 HandleValue(E->getArg(0));
13411 return;
13412 }
13413
13414 Inherited::VisitCallExpr(E);
13415 }
13416
13417 void VisitBinaryOperator(BinaryOperator *E) {
13418 if (E->isCompoundAssignmentOp()) {
13419 HandleValue(E->getLHS());
13420 Visit(E->getRHS());
13421 return;
13422 }
13423
13424 Inherited::VisitBinaryOperator(E);
13425 }
13426
13427 // A custom visitor for BinaryConditionalOperator is needed because the
13428 // regular visitor would check the condition and true expression separately
13429 // but both point to the same place giving duplicate diagnostics.
13430 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
13431 Visit(E->getCond());
13432 Visit(E->getFalseExpr());
13433 }
13434
13435 void HandleDeclRefExpr(DeclRefExpr *DRE) {
13436 Decl* ReferenceDecl = DRE->getDecl();
13437 if (OrigDecl != ReferenceDecl) return;
13438 unsigned diag;
13439 if (isReferenceType) {
13440 diag = diag::warn_uninit_self_reference_in_reference_init;
13441 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
13442 diag = diag::warn_static_self_reference_in_init;
13443 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
13444 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
13445 DRE->getDecl()->getType()->isRecordType()) {
13446 diag = diag::warn_uninit_self_reference_in_init;
13447 } else {
13448 // Local variables will be handled by the CFG analysis.
13449 return;
13450 }
13451
13452 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
13453 S.PDiag(diag)
13454 << DRE->getDecl() << OrigDecl->getLocation()
13455 << DRE->getSourceRange());
13456 }
13457 };
13458
13459 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
13460 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
13461 bool DirectInit) {
13462 // Parameters arguments are occassionially constructed with itself,
13463 // for instance, in recursive functions. Skip them.
13464 if (isa<ParmVarDecl>(OrigDecl))
13465 return;
13466
13467 // Skip checking for file-scope constexpr variables - constant evaluation
13468 // will produce appropriate errors without needing runtime diagnostics.
13469 // Local constexpr should still emit runtime warnings.
13470 if (auto *VD = dyn_cast<VarDecl>(OrigDecl);
13471 VD && VD->isConstexpr() && VD->isFileVarDecl())
13472 return;
13473
13474 E = E->IgnoreParens();
13475
13476 // Skip checking T a = a where T is not a record or reference type.
13477 // Doing so is a way to silence uninitialized warnings.
13478 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
13479 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
13480 if (ICE->getCastKind() == CK_LValueToRValue)
13481 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
13482 if (DRE->getDecl() == OrigDecl)
13483 return;
13484
13485 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
13486 }
13487} // end anonymous namespace
13488
13489namespace {
13490 // Simple wrapper to add the name of a variable or (if no variable is
13491 // available) a DeclarationName into a diagnostic.
13492 struct VarDeclOrName {
13493 VarDecl *VDecl;
13494 DeclarationName Name;
13495
13496 friend const Sema::SemaDiagnosticBuilder &
13497 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
13498 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
13499 }
13500 };
13501} // end anonymous namespace
13502
13505 TypeSourceInfo *TSI,
13506 SourceRange Range, bool DirectInit,
13507 Expr *Init) {
13508 bool IsInitCapture = !VDecl;
13509 assert((!VDecl || !VDecl->isInitCapture()) &&
13510 "init captures are expected to be deduced prior to initialization");
13511
13512 VarDeclOrName VN{VDecl, Name};
13513
13514 DeducedType *Deduced = Type->getContainedDeducedType();
13515 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
13516
13517 // Diagnose auto array declarations in C23, unless it's a supported extension.
13518 if (getLangOpts().C23 && Type->isArrayType() &&
13519 !isa_and_present<StringLiteral, InitListExpr>(Init)) {
13520 Diag(Range.getBegin(), diag::err_auto_not_allowed)
13521 << (int)Deduced->getContainedAutoType()->getKeyword()
13522 << /*in array decl*/ 23 << Range;
13523 return QualType();
13524 }
13525
13526 // C++11 [dcl.spec.auto]p3
13527 if (!Init) {
13528 assert(VDecl && "no init for init capture deduction?");
13529
13530 // Except for class argument deduction, and then for an initializing
13531 // declaration only, i.e. no static at class scope or extern.
13533 VDecl->hasExternalStorage() ||
13534 VDecl->isStaticDataMember()) {
13535 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
13536 << VDecl->getDeclName() << Type;
13537 return QualType();
13538 }
13539 }
13540
13541 ArrayRef<Expr*> DeduceInits;
13542 if (Init)
13543 DeduceInits = Init;
13544
13545 auto *PL = dyn_cast_if_present<ParenListExpr>(Init);
13546 if (DirectInit && PL)
13547 DeduceInits = PL->exprs();
13548
13550 assert(VDecl && "non-auto type for init capture deduction?");
13553 VDecl->getLocation(), DirectInit, Init);
13554 // FIXME: Initialization should not be taking a mutable list of inits.
13555 SmallVector<Expr *, 8> InitsCopy(DeduceInits);
13556 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
13557 InitsCopy);
13558 }
13559
13560 if (DirectInit) {
13561 if (auto *IL = dyn_cast<InitListExpr>(Init))
13562 DeduceInits = IL->inits();
13563 }
13564
13565 // Deduction only works if we have exactly one source expression.
13566 if (DeduceInits.empty()) {
13567 // It isn't possible to write this directly, but it is possible to
13568 // end up in this situation with "auto x(some_pack...);"
13569 Diag(Init->getBeginLoc(), IsInitCapture
13570 ? diag::err_init_capture_no_expression
13571 : diag::err_auto_var_init_no_expression)
13572 << VN << Type << Range;
13573 return QualType();
13574 }
13575
13576 if (DeduceInits.size() > 1) {
13577 Diag(DeduceInits[1]->getBeginLoc(),
13578 IsInitCapture ? diag::err_init_capture_multiple_expressions
13579 : diag::err_auto_var_init_multiple_expressions)
13580 << VN << Type << Range;
13581 return QualType();
13582 }
13583
13584 Expr *DeduceInit = DeduceInits[0];
13585 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
13586 Diag(Init->getBeginLoc(), IsInitCapture
13587 ? diag::err_init_capture_paren_braces
13588 : diag::err_auto_var_init_paren_braces)
13589 << isa<InitListExpr>(Init) << VN << Type << Range;
13590 return QualType();
13591 }
13592
13593 // Expressions default to 'id' when we're in a debugger.
13594 bool DefaultedAnyToId = false;
13595 if (getLangOpts().DebuggerCastResultToId &&
13596 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
13598 if (Result.isInvalid()) {
13599 return QualType();
13600 }
13601 Init = Result.get();
13602 DefaultedAnyToId = true;
13603 }
13604
13605 // C++ [dcl.decomp]p1:
13606 // If the assignment-expression [...] has array type A and no ref-qualifier
13607 // is present, e has type cv A
13608 if (VDecl && isa<DecompositionDecl>(VDecl) &&
13609 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
13610 DeduceInit->getType()->isConstantArrayType())
13611 return Context.getQualifiedType(DeduceInit->getType(),
13612 Type.getQualifiers());
13613
13614 QualType DeducedType;
13615 TemplateDeductionInfo Info(DeduceInit->getExprLoc());
13617 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
13620 if (!IsInitCapture)
13621 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
13622 else if (isa<InitListExpr>(Init))
13623 Diag(Range.getBegin(),
13624 diag::err_init_capture_deduction_failure_from_init_list)
13625 << VN
13626 << (DeduceInit->getType().isNull() ? TSI->getType()
13627 : DeduceInit->getType())
13628 << DeduceInit->getSourceRange();
13629 else
13630 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
13631 << VN << TSI->getType()
13632 << (DeduceInit->getType().isNull() ? TSI->getType()
13633 : DeduceInit->getType())
13634 << DeduceInit->getSourceRange();
13635 }
13636
13637 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
13638 // 'id' instead of a specific object type prevents most of our usual
13639 // checks.
13640 // We only want to warn outside of template instantiations, though:
13641 // inside a template, the 'id' could have come from a parameter.
13642 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
13643 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
13644 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
13645 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
13646 }
13647
13648 return DeducedType;
13649}
13650
13652 Expr *Init) {
13653 assert(!Init || !Init->containsErrors());
13655 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
13656 VDecl->getSourceRange(), DirectInit, Init);
13657 if (DeducedType.isNull()) {
13658 VDecl->setInvalidDecl();
13659 return true;
13660 }
13661
13662 VDecl->setType(DeducedType);
13663 assert(VDecl->isLinkageValid());
13664
13665 // In ARC, infer lifetime.
13666 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(VDecl))
13667 VDecl->setInvalidDecl();
13668
13669 if (getLangOpts().OpenCL)
13671
13672 if (getLangOpts().HLSL)
13673 HLSL().deduceAddressSpace(VDecl);
13674
13675 // If this is a redeclaration, check that the type we just deduced matches
13676 // the previously declared type.
13677 if (VarDecl *Old = VDecl->getPreviousDecl()) {
13678 // We never need to merge the type, because we cannot form an incomplete
13679 // array of auto, nor deduce such a type.
13680 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
13681 }
13682
13683 // Check the deduced type is valid for a variable declaration.
13685 return VDecl->isInvalidDecl();
13686}
13687
13689 SourceLocation Loc) {
13690 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
13691 Init = EWC->getSubExpr();
13692
13693 if (auto *CE = dyn_cast<ConstantExpr>(Init))
13694 Init = CE->getSubExpr();
13695
13696 QualType InitType = Init->getType();
13699 "shouldn't be called if type doesn't have a non-trivial C struct");
13700 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
13701 for (auto *I : ILE->inits()) {
13702 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
13703 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
13704 continue;
13705 SourceLocation SL = I->getExprLoc();
13706 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
13707 }
13708 return;
13709 }
13710
13713 checkNonTrivialCUnion(InitType, Loc,
13715 NTCUK_Init);
13716 } else {
13717 // Assume all other explicit initializers involving copying some existing
13718 // object.
13719 // TODO: ignore any explicit initializers where we can guarantee
13720 // copy-elision.
13723 NTCUK_Copy);
13724 }
13725}
13726
13727namespace {
13728
13729bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
13730 // Ignore unavailable fields. A field can be marked as unavailable explicitly
13731 // in the source code or implicitly by the compiler if it is in a union
13732 // defined in a system header and has non-trivial ObjC ownership
13733 // qualifications. We don't want those fields to participate in determining
13734 // whether the containing union is non-trivial.
13735 return FD->hasAttr<UnavailableAttr>();
13736}
13737
13738struct DiagNonTrivalCUnionDefaultInitializeVisitor
13739 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13740 void> {
13741 using Super =
13742 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
13743 void>;
13744
13745 DiagNonTrivalCUnionDefaultInitializeVisitor(
13746 QualType OrigTy, SourceLocation OrigLoc,
13747 NonTrivialCUnionContext UseContext, Sema &S)
13748 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13749
13750 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
13751 const FieldDecl *FD, bool InNonTrivialUnion) {
13752 if (const auto *AT = S.Context.getAsArrayType(QT))
13753 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13754 InNonTrivialUnion);
13755 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
13756 }
13757
13758 void visitARCStrong(QualType QT, const FieldDecl *FD,
13759 bool InNonTrivialUnion) {
13760 if (InNonTrivialUnion)
13761 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13762 << 1 << 0 << QT << FD->getName();
13763 }
13764
13765 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13766 if (InNonTrivialUnion)
13767 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13768 << 1 << 0 << QT << FD->getName();
13769 }
13770
13771 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13772 const auto *RD = QT->castAsRecordDecl();
13773 if (RD->isUnion()) {
13774 if (OrigLoc.isValid()) {
13775 bool IsUnion = false;
13776 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13777 IsUnion = OrigRD->isUnion();
13778 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13779 << 0 << OrigTy << IsUnion << UseContext;
13780 // Reset OrigLoc so that this diagnostic is emitted only once.
13781 OrigLoc = SourceLocation();
13782 }
13783 InNonTrivialUnion = true;
13784 }
13785
13786 if (InNonTrivialUnion)
13787 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13788 << 0 << 0 << QT.getUnqualifiedType() << "";
13789
13790 for (const FieldDecl *FD : RD->fields())
13791 if (!shouldIgnoreForRecordTriviality(FD))
13792 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13793 }
13794
13795 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13796
13797 // The non-trivial C union type or the struct/union type that contains a
13798 // non-trivial C union.
13799 QualType OrigTy;
13800 SourceLocation OrigLoc;
13801 NonTrivialCUnionContext UseContext;
13802 Sema &S;
13803};
13804
13805struct DiagNonTrivalCUnionDestructedTypeVisitor
13806 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
13807 using Super =
13808 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
13809
13810 DiagNonTrivalCUnionDestructedTypeVisitor(QualType OrigTy,
13811 SourceLocation OrigLoc,
13812 NonTrivialCUnionContext UseContext,
13813 Sema &S)
13814 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13815
13816 void visitWithKind(QualType::DestructionKind DK, QualType QT,
13817 const FieldDecl *FD, bool InNonTrivialUnion) {
13818 if (const auto *AT = S.Context.getAsArrayType(QT))
13819 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13820 InNonTrivialUnion);
13821 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
13822 }
13823
13824 void visitARCStrong(QualType QT, const FieldDecl *FD,
13825 bool InNonTrivialUnion) {
13826 if (InNonTrivialUnion)
13827 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13828 << 1 << 1 << QT << FD->getName();
13829 }
13830
13831 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13832 if (InNonTrivialUnion)
13833 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13834 << 1 << 1 << QT << FD->getName();
13835 }
13836
13837 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13838 const auto *RD = QT->castAsRecordDecl();
13839 if (RD->isUnion()) {
13840 if (OrigLoc.isValid()) {
13841 bool IsUnion = false;
13842 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13843 IsUnion = OrigRD->isUnion();
13844 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13845 << 1 << OrigTy << IsUnion << UseContext;
13846 // Reset OrigLoc so that this diagnostic is emitted only once.
13847 OrigLoc = SourceLocation();
13848 }
13849 InNonTrivialUnion = true;
13850 }
13851
13852 if (InNonTrivialUnion)
13853 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13854 << 0 << 1 << QT.getUnqualifiedType() << "";
13855
13856 for (const FieldDecl *FD : RD->fields())
13857 if (!shouldIgnoreForRecordTriviality(FD))
13858 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13859 }
13860
13861 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13862 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
13863 bool InNonTrivialUnion) {}
13864
13865 // The non-trivial C union type or the struct/union type that contains a
13866 // non-trivial C union.
13867 QualType OrigTy;
13868 SourceLocation OrigLoc;
13869 NonTrivialCUnionContext UseContext;
13870 Sema &S;
13871};
13872
13873struct DiagNonTrivalCUnionCopyVisitor
13874 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
13875 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
13876
13877 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
13878 NonTrivialCUnionContext UseContext, Sema &S)
13879 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
13880
13881 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
13882 const FieldDecl *FD, bool InNonTrivialUnion) {
13883 if (const auto *AT = S.Context.getAsArrayType(QT))
13884 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
13885 InNonTrivialUnion);
13886 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
13887 }
13888
13889 void visitARCStrong(QualType QT, const FieldDecl *FD,
13890 bool InNonTrivialUnion) {
13891 if (InNonTrivialUnion)
13892 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13893 << 1 << 2 << QT << FD->getName();
13894 }
13895
13896 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13897 if (InNonTrivialUnion)
13898 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13899 << 1 << 2 << QT << FD->getName();
13900 }
13901
13902 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13903 const auto *RD = QT->castAsRecordDecl();
13904 if (RD->isUnion()) {
13905 if (OrigLoc.isValid()) {
13906 bool IsUnion = false;
13907 if (auto *OrigRD = OrigTy->getAsRecordDecl())
13908 IsUnion = OrigRD->isUnion();
13909 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
13910 << 2 << OrigTy << IsUnion << UseContext;
13911 // Reset OrigLoc so that this diagnostic is emitted only once.
13912 OrigLoc = SourceLocation();
13913 }
13914 InNonTrivialUnion = true;
13915 }
13916
13917 if (InNonTrivialUnion)
13918 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
13919 << 0 << 2 << QT.getUnqualifiedType() << "";
13920
13921 for (const FieldDecl *FD : RD->fields())
13922 if (!shouldIgnoreForRecordTriviality(FD))
13923 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
13924 }
13925
13926 void visitPtrAuth(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
13927 if (InNonTrivialUnion)
13928 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
13929 << 1 << 2 << QT << FD->getName();
13930 }
13931
13932 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
13933 const FieldDecl *FD, bool InNonTrivialUnion) {}
13934 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
13935 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
13936 bool InNonTrivialUnion) {}
13937
13938 // The non-trivial C union type or the struct/union type that contains a
13939 // non-trivial C union.
13940 QualType OrigTy;
13941 SourceLocation OrigLoc;
13942 NonTrivialCUnionContext UseContext;
13943 Sema &S;
13944};
13945
13946} // namespace
13947
13949 NonTrivialCUnionContext UseContext,
13950 unsigned NonTrivialKind) {
13954 "shouldn't be called if type doesn't have a non-trivial C union");
13955
13956 if ((NonTrivialKind & NTCUK_Init) &&
13958 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
13959 .visit(QT, nullptr, false);
13960 if ((NonTrivialKind & NTCUK_Destruct) &&
13962 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
13963 .visit(QT, nullptr, false);
13964 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
13965 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
13966 .visit(QT, nullptr, false);
13967}
13968
13970 const VarDecl *Dcl) {
13971 if (!getLangOpts().CPlusPlus)
13972 return false;
13973
13974 // We only need to warn if the definition is in a header file, so wait to
13975 // diagnose until we've seen the definition.
13976 if (!Dcl->isThisDeclarationADefinition())
13977 return false;
13978
13979 // If an object is defined in a source file, its definition can't get
13980 // duplicated since it will never appear in more than one TU.
13982 return false;
13983
13984 // If the variable we're looking at is a static local, then we actually care
13985 // about the properties of the function containing it.
13986 const ValueDecl *Target = Dcl;
13987 // VarDecls and FunctionDecls have different functions for checking
13988 // inline-ness, and whether they were originally templated, so we have to
13989 // call the appropriate functions manually.
13990 bool TargetIsInline = Dcl->isInline();
13991 bool TargetWasTemplated =
13993
13994 // Update the Target and TargetIsInline property if necessary
13995 if (Dcl->isStaticLocal()) {
13996 const DeclContext *Ctx = Dcl->getDeclContext();
13997 if (!Ctx)
13998 return false;
13999
14000 const FunctionDecl *FunDcl =
14001 dyn_cast_if_present<FunctionDecl>(Ctx->getNonClosureAncestor());
14002 if (!FunDcl)
14003 return false;
14004
14005 Target = FunDcl;
14006 // IsInlined() checks for the C++ inline property
14007 TargetIsInline = FunDcl->isInlined();
14008 TargetWasTemplated =
14010 }
14011
14012 // Non-inline functions/variables can only legally appear in one TU
14013 // unless they were part of a template. Unfortunately, making complex
14014 // template instantiations visible is infeasible in practice, since
14015 // everything the template depends on also has to be visible. To avoid
14016 // giving impractical-to-fix warnings, don't warn if we're inside
14017 // something that was templated, even on inline stuff.
14018 if (!TargetIsInline || TargetWasTemplated)
14019 return false;
14020
14021 // If the object isn't hidden, the dynamic linker will prevent duplication.
14022 clang::LinkageInfo Lnk = Target->getLinkageAndVisibility();
14023
14024 // The target is "hidden" (from the dynamic linker) if:
14025 // 1. On posix, it has hidden visibility, or
14026 // 2. On windows, it has no import/export annotation, and neither does the
14027 // class which directly contains it.
14028 if (Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
14029 if (Target->hasAttr<DLLExportAttr>() || Target->hasAttr<DLLImportAttr>())
14030 return false;
14031
14032 // If the variable isn't directly annotated, check to see if it's a member
14033 // of an annotated class.
14034 const CXXRecordDecl *Ctx =
14035 dyn_cast<CXXRecordDecl>(Target->getDeclContext());
14036 if (Ctx && (Ctx->hasAttr<DLLExportAttr>() || Ctx->hasAttr<DLLImportAttr>()))
14037 return false;
14038
14039 } else if (Lnk.getVisibility() != HiddenVisibility) {
14040 // Posix case
14041 return false;
14042 }
14043
14044 // If the obj doesn't have external linkage, it's supposed to be duplicated.
14046 return false;
14047
14048 return true;
14049}
14050
14051// Determine whether the object seems mutable for the purpose of diagnosing
14052// possible unique object duplication, i.e. non-const-qualified, and
14053// not an always-constant type like a function.
14054// Not perfect: doesn't account for mutable members, for example, or
14055// elements of container types.
14056// For nested pointers, any individual level being non-const is sufficient.
14057static bool looksMutable(QualType T, const ASTContext &Ctx) {
14058 T = T.getNonReferenceType();
14059 if (T->isFunctionType())
14060 return false;
14061 if (!T.isConstant(Ctx))
14062 return true;
14063 if (T->isPointerType())
14064 return looksMutable(T->getPointeeType(), Ctx);
14065 return false;
14066}
14067
14069 // If this object has external linkage and hidden visibility, it might be
14070 // duplicated when built into a shared library, which causes problems if it's
14071 // mutable (since the copies won't be in sync) or its initialization has side
14072 // effects (since it will run once per copy instead of once globally).
14073
14074 // Don't diagnose if we're inside a template, because it's not practical to
14075 // fix the warning in most cases.
14076 if (!VD->isTemplated() &&
14078
14079 QualType Type = VD->getType();
14080 if (looksMutable(Type, VD->getASTContext())) {
14081 Diag(VD->getLocation(), diag::warn_possible_object_duplication_mutable)
14082 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14083 }
14084
14085 // To keep false positives low, only warn if we're certain that the
14086 // initializer has side effects. Don't warn on operator new, since a mutable
14087 // pointer will trigger the previous warning, and an immutable pointer
14088 // getting duplicated just results in a little extra memory usage.
14089 const Expr *Init = VD->getAnyInitializer();
14090 if (Init &&
14091 Init->HasSideEffects(VD->getASTContext(),
14092 /*IncludePossibleEffects=*/false) &&
14093 !isa<CXXNewExpr>(Init->IgnoreParenImpCasts())) {
14094 Diag(Init->getExprLoc(), diag::warn_possible_object_duplication_init)
14095 << VD << Context.getTargetInfo().shouldDLLImportComdatSymbols();
14096 }
14097 }
14098}
14099
14101 llvm::scope_exit ResetDeclForInitializer([this]() {
14102 if (!this->ExprEvalContexts.empty())
14103 this->ExprEvalContexts.back().DeclForInitializer = nullptr;
14104 });
14105
14106 // If there is no declaration, there was an error parsing it. Just ignore
14107 // the initializer.
14108 if (!RealDecl) {
14109 return;
14110 }
14111
14112 if (auto *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
14113 if (!Method->isInvalidDecl()) {
14114 // Pure-specifiers are handled in ActOnPureSpecifier.
14115 Diag(Method->getLocation(), diag::err_member_function_initialization)
14116 << Method->getDeclName() << Init->getSourceRange();
14117 Method->setInvalidDecl();
14118 }
14119 return;
14120 }
14121
14122 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
14123 if (!VDecl) {
14124 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
14125 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
14126 RealDecl->setInvalidDecl();
14127 return;
14128 }
14129
14130 if (VDecl->isInvalidDecl()) {
14131 ExprResult Recovery =
14132 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init});
14133 if (Expr *E = Recovery.get())
14134 VDecl->setInit(E);
14135 return;
14136 }
14137
14138 // __amdgpu_feature_predicate_t cannot be initialised
14139 if (VDecl->getType().getDesugaredType(Context) ==
14140 Context.AMDGPUFeaturePredicateTy) {
14141 Diag(VDecl->getLocation(),
14142 diag::err_amdgcn_predicate_type_is_not_constructible)
14143 << VDecl;
14144 VDecl->setInvalidDecl();
14145 return;
14146 }
14147
14148 // WebAssembly tables can't be used to initialise a variable.
14149 if (!Init->getType().isNull() && Init->getType()->isWebAssemblyTableType()) {
14150 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0;
14151 VDecl->setInvalidDecl();
14152 return;
14153 }
14154
14155 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
14156 if (VDecl->getType()->isUndeducedType()) {
14157 if (Init->containsErrors()) {
14158 // Invalidate the decl as we don't know the type for recovery-expr yet.
14159 RealDecl->setInvalidDecl();
14160 VDecl->setInit(Init);
14161 return;
14162 }
14163
14165 assert(VDecl->isInvalidDecl() &&
14166 "decl should be invalidated when deduce fails");
14167 if (auto *RecoveryExpr =
14168 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), {Init})
14169 .get())
14170 VDecl->setInit(RecoveryExpr);
14171 return;
14172 }
14173 }
14174
14175 this->CheckAttributesOnDeducedType(RealDecl);
14176
14177 // we don't initialize groupshared variables so warn and return
14178 if (VDecl->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
14179 Diag(VDecl->getLocation(), diag::warn_hlsl_groupshared_init);
14180 return;
14181 }
14182
14183 // dllimport cannot be used on variable definitions.
14184 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
14185 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
14186 VDecl->setInvalidDecl();
14187 return;
14188 }
14189
14190 // C99 6.7.8p5. If the declaration of an identifier has block scope, and
14191 // the identifier has external or internal linkage, the declaration shall
14192 // have no initializer for the identifier.
14193 // C++14 [dcl.init]p5 is the same restriction for C++.
14194 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
14195 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
14196 VDecl->setInvalidDecl();
14197 return;
14198 }
14199
14200 if (!VDecl->getType()->isDependentType()) {
14201 // A definition must end up with a complete type, which means it must be
14202 // complete with the restriction that an array type might be completed by
14203 // the initializer; note that later code assumes this restriction.
14204 QualType BaseDeclType = VDecl->getType();
14205 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
14206 BaseDeclType = Array->getElementType();
14207 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
14208 diag::err_typecheck_decl_incomplete_type)) {
14209 RealDecl->setInvalidDecl();
14210 return;
14211 }
14212
14213 // The variable can not have an abstract class type.
14214 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
14215 diag::err_abstract_type_in_decl,
14217 VDecl->setInvalidDecl();
14218 }
14219
14220 // C++ [module.import/6]
14221 // ...
14222 // A header unit shall not contain a definition of a non-inline function or
14223 // variable whose name has external linkage.
14224 //
14225 // We choose to allow weak & selectany definitions, as they are common in
14226 // headers, and have semantics similar to inline definitions which are allowed
14227 // in header units.
14228 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
14229 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
14230 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() &&
14231 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl) &&
14233 !(VDecl->hasAttr<SelectAnyAttr>() || VDecl->hasAttr<WeakAttr>())) {
14234 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
14235 VDecl->setInvalidDecl();
14236 }
14237
14238 // If adding the initializer will turn this declaration into a definition,
14239 // and we already have a definition for this variable, diagnose or otherwise
14240 // handle the situation.
14241 if (VarDecl *Def = VDecl->getDefinition())
14242 if (Def != VDecl &&
14243 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
14245 checkVarDeclRedefinition(Def, VDecl))
14246 return;
14247
14248 if (getLangOpts().CPlusPlus) {
14249 // C++ [class.static.data]p4
14250 // If a static data member is of const integral or const
14251 // enumeration type, its declaration in the class definition can
14252 // specify a constant-initializer which shall be an integral
14253 // constant expression (5.19). In that case, the member can appear
14254 // in integral constant expressions. The member shall still be
14255 // defined in a namespace scope if it is used in the program and the
14256 // namespace scope definition shall not contain an initializer.
14257 //
14258 // We already performed a redefinition check above, but for static
14259 // data members we also need to check whether there was an in-class
14260 // declaration with an initializer.
14261 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
14262 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
14263 << VDecl->getDeclName();
14264 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
14265 diag::note_previous_initializer)
14266 << 0;
14267 return;
14268 }
14269
14271 VDecl->setInvalidDecl();
14272 return;
14273 }
14274 }
14275
14276 // If the variable has an initializer and local storage, check whether
14277 // anything jumps over the initialization.
14278 if (VDecl->hasLocalStorage())
14280
14281 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
14282 // a kernel function cannot be initialized."
14283 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
14284 Diag(VDecl->getLocation(), diag::err_local_cant_init);
14285 VDecl->setInvalidDecl();
14286 return;
14287 }
14288
14289 // The LoaderUninitialized attribute acts as a definition (of undef).
14290 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
14291 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
14292 VDecl->setInvalidDecl();
14293 return;
14294 }
14295
14296 if (getLangOpts().HLSL)
14297 if (!HLSL().handleInitialization(VDecl, Init))
14298 return;
14299
14300 // Get the decls type and save a reference for later, since
14301 // CheckInitializerTypes may change it.
14302 QualType DclT = VDecl->getType(), SavT = DclT;
14303
14304 // Expressions default to 'id' when we're in a debugger
14305 // and we are assigning it to a variable of Objective-C pointer type.
14306 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
14307 Init->getType() == Context.UnknownAnyTy) {
14309 if (!Result.isUsable()) {
14310 VDecl->setInvalidDecl();
14311 return;
14312 }
14313 Init = Result.get();
14314 }
14315
14316 // Perform the initialization.
14317 bool InitializedFromParenListExpr = false;
14318 bool IsParenListInit = false;
14319 if (!VDecl->isInvalidDecl()) {
14322 VDecl->getLocation(), DirectInit, Init);
14323
14324 MultiExprArg Args = Init;
14325 if (auto *CXXDirectInit = dyn_cast<ParenListExpr>(Init)) {
14326 Args =
14327 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
14328 InitializedFromParenListExpr = true;
14329 } else if (auto *CXXDirectInit = dyn_cast<CXXParenListInitExpr>(Init)) {
14330 Args = CXXDirectInit->getInitExprs();
14331 InitializedFromParenListExpr = true;
14332 }
14333
14334 InitializationSequence InitSeq(*this, Entity, Kind, Args,
14335 /*TopLevelOfInitList=*/false,
14336 /*TreatUnavailableAsInvalid=*/false);
14337 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
14338 if (!Result.isUsable()) {
14339 // If the provided initializer fails to initialize the var decl,
14340 // we attach a recovery expr for better recovery.
14341 auto RecoveryExpr =
14342 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
14343 if (RecoveryExpr.get())
14344 VDecl->setInit(RecoveryExpr.get());
14345 // In general, for error recovery purposes, the initializer doesn't play
14346 // part in the valid bit of the declaration. There are a few exceptions:
14347 // 1) if the var decl has a deduced auto type, and the type cannot be
14348 // deduced by an invalid initializer;
14349 // 2) if the var decl is a decomposition decl with a non-deduced type,
14350 // and the initialization fails (e.g. `int [a] = {1, 2};`);
14351 // Case 1) was already handled elsewhere.
14352 if (isa<DecompositionDecl>(VDecl)) // Case 2)
14353 VDecl->setInvalidDecl();
14354 return;
14355 }
14356
14357 Init = Result.getAs<Expr>();
14358 IsParenListInit = !InitSeq.steps().empty() &&
14359 InitSeq.step_begin()->Kind ==
14361 QualType VDeclType = VDecl->getType();
14362 if (!Init->getType().isNull() && !Init->getType()->isDependentType() &&
14363 !VDeclType->isDependentType() &&
14364 Context.getAsIncompleteArrayType(VDeclType) &&
14365 Context.getAsIncompleteArrayType(Init->getType())) {
14366 // Bail out if it is not possible to deduce array size from the
14367 // initializer.
14368 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
14369 << VDeclType;
14370 VDecl->setInvalidDecl();
14371 return;
14372 }
14373 }
14374
14375 // Check for self-references within variable initializers.
14376 // Variables declared within a function/method body (except for references)
14377 // are handled by a dataflow analysis.
14378 // This is undefined behavior in C++, but valid in C.
14379 if (getLangOpts().CPlusPlus)
14380 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
14381 VDecl->getType()->isReferenceType())
14382 CheckSelfReference(*this, RealDecl, Init, DirectInit);
14383
14384 // If the type changed, it means we had an incomplete type that was
14385 // completed by the initializer. For example:
14386 // int ary[] = { 1, 3, 5 };
14387 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
14388 if (!VDecl->isInvalidDecl() && (DclT != SavT))
14389 VDecl->setType(DclT);
14390
14391 if (!VDecl->isInvalidDecl()) {
14392 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
14393
14394 if (VDecl->hasAttr<BlocksAttr>())
14395 ObjC().checkRetainCycles(VDecl, Init);
14396
14397 // It is safe to assign a weak reference into a strong variable.
14398 // Although this code can still have problems:
14399 // id x = self.weakProp;
14400 // id y = self.weakProp;
14401 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14402 // paths through the function. This should be revisited if
14403 // -Wrepeated-use-of-weak is made flow-sensitive.
14404 if (FunctionScopeInfo *FSI = getCurFunction())
14405 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
14407 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14408 Init->getBeginLoc()))
14409 FSI->markSafeWeakUse(Init);
14410 }
14411
14412 // The initialization is usually a full-expression.
14413 //
14414 // FIXME: If this is a braced initialization of an aggregate, it is not
14415 // an expression, and each individual field initializer is a separate
14416 // full-expression. For instance, in:
14417 //
14418 // struct Temp { ~Temp(); };
14419 // struct S { S(Temp); };
14420 // struct T { S a, b; } t = { Temp(), Temp() }
14421 //
14422 // we should destroy the first Temp before constructing the second.
14423
14424 // Set context flag for OverflowBehaviorType initialization analysis
14426 true);
14429 /*DiscardedValue*/ false, VDecl->isConstexpr());
14430 if (!Result.isUsable()) {
14431 VDecl->setInvalidDecl();
14432 return;
14433 }
14434 Init = Result.get();
14435
14436 // Attach the initializer to the decl.
14437 VDecl->setInit(Init);
14438
14439 if (VDecl->isLocalVarDecl()) {
14440 // Don't check the initializer if the declaration is malformed.
14441 if (VDecl->isInvalidDecl()) {
14442 // do nothing
14443
14444 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
14445 // This is true even in C++ for OpenCL.
14446 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
14448
14449 // Otherwise, C++ does not restrict the initializer.
14450 } else if (getLangOpts().CPlusPlus) {
14451 // do nothing
14452
14453 // C99 6.7.8p4: All the expressions in an initializer for an object that has
14454 // static storage duration shall be constant expressions or string literals.
14455 } else if (VDecl->getStorageClass() == SC_Static) {
14456 // Avoid evaluating the initializer twice for constexpr variables. It will
14457 // be evaluated later.
14458 if (!VDecl->isConstexpr())
14460
14461 // C89 is stricter than C99 for aggregate initializers.
14462 // C89 6.5.7p3: All the expressions [...] in an initializer list
14463 // for an object that has aggregate or union type shall be
14464 // constant expressions.
14465 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
14467 CheckForConstantInitializer(Init, diag::ext_aggregate_init_not_constant);
14468 }
14469
14470 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
14471 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
14472 if (VDecl->hasLocalStorage())
14473 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14474 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
14475 VDecl->getLexicalDeclContext()->isRecord()) {
14476 // This is an in-class initialization for a static data member, e.g.,
14477 //
14478 // struct S {
14479 // static const int value = 17;
14480 // };
14481
14482 // C++ [class.mem]p4:
14483 // A member-declarator can contain a constant-initializer only
14484 // if it declares a static member (9.4) of const integral or
14485 // const enumeration type, see 9.4.2.
14486 //
14487 // C++11 [class.static.data]p3:
14488 // If a non-volatile non-inline const static data member is of integral
14489 // or enumeration type, its declaration in the class definition can
14490 // specify a brace-or-equal-initializer in which every initializer-clause
14491 // that is an assignment-expression is a constant expression. A static
14492 // data member of literal type can be declared in the class definition
14493 // with the constexpr specifier; if so, its declaration shall specify a
14494 // brace-or-equal-initializer in which every initializer-clause that is
14495 // an assignment-expression is a constant expression.
14496
14497 // Do nothing on dependent types.
14498 if (DclT->isDependentType()) {
14499
14500 // Allow any 'static constexpr' members, whether or not they are of literal
14501 // type. We separately check that every constexpr variable is of literal
14502 // type.
14503 } else if (VDecl->isConstexpr()) {
14504
14505 // Require constness.
14506 } else if (!DclT.isConstQualified()) {
14507 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
14508 << Init->getSourceRange();
14509 VDecl->setInvalidDecl();
14510
14511 // We allow integer constant expressions in all cases.
14512 } else if (DclT->isIntegralOrEnumerationType()) {
14514 // In C++11, a non-constexpr const static data member with an
14515 // in-class initializer cannot be volatile.
14516 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
14517
14518 // We allow foldable floating-point constants as an extension.
14519 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
14520 // In C++98, this is a GNU extension. In C++11, it is not, but we support
14521 // it anyway and provide a fixit to add the 'constexpr'.
14522 if (getLangOpts().CPlusPlus11) {
14523 Diag(VDecl->getLocation(),
14524 diag::ext_in_class_initializer_float_type_cxx11)
14525 << DclT << Init->getSourceRange();
14526 Diag(VDecl->getBeginLoc(),
14527 diag::note_in_class_initializer_float_type_cxx11)
14528 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14529 } else {
14530 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
14531 << DclT << Init->getSourceRange();
14532
14533 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
14534 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
14535 << Init->getSourceRange();
14536 VDecl->setInvalidDecl();
14537 }
14538 }
14539
14540 // Suggest adding 'constexpr' in C++11 for literal types.
14541 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
14542 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
14543 << DclT << Init->getSourceRange()
14544 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
14545 VDecl->setConstexpr(true);
14546
14547 } else {
14548 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
14549 << DclT << Init->getSourceRange();
14550 VDecl->setInvalidDecl();
14551 }
14552 } else if (VDecl->isFileVarDecl()) {
14553 // In C, extern is typically used to avoid tentative definitions when
14554 // declaring variables in headers, but adding an initializer makes it a
14555 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
14556 // In C++, extern is often used to give implicitly static const variables
14557 // external linkage, so don't warn in that case. If selectany is present,
14558 // this might be header code intended for C and C++ inclusion, so apply the
14559 // C++ rules.
14560 if (VDecl->getStorageClass() == SC_Extern &&
14561 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
14562 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
14563 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
14565 Diag(VDecl->getLocation(), diag::warn_extern_init);
14566
14567 // In Microsoft C++ mode, a const variable defined in namespace scope has
14568 // external linkage by default if the variable is declared with
14569 // __declspec(dllexport).
14570 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14572 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
14573 VDecl->setStorageClass(SC_Extern);
14574
14575 // C99 6.7.8p4. All file scoped initializers need to be constant.
14576 // Avoid duplicate diagnostics for constexpr variables.
14577 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
14578 !VDecl->isConstexpr())
14580 }
14581
14582 QualType InitType = Init->getType();
14583 if (!InitType.isNull() &&
14587
14588 // We will represent direct-initialization similarly to copy-initialization:
14589 // int x(1); -as-> int x = 1;
14590 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
14591 //
14592 // Clients that want to distinguish between the two forms, can check for
14593 // direct initializer using VarDecl::getInitStyle().
14594 // A major benefit is that clients that don't particularly care about which
14595 // exactly form was it (like the CodeGen) can handle both cases without
14596 // special case code.
14597
14598 // C++ 8.5p11:
14599 // The form of initialization (using parentheses or '=') matters
14600 // when the entity being initialized has class type.
14601 if (InitializedFromParenListExpr) {
14602 assert(DirectInit && "Call-style initializer must be direct init.");
14603 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
14605 } else if (DirectInit) {
14606 // This must be list-initialization. No other way is direct-initialization.
14608 }
14609
14610 if (LangOpts.OpenMP &&
14611 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) &&
14612 VDecl->isFileVarDecl())
14613 DeclsToCheckForDeferredDiags.insert(VDecl);
14615
14616 if (LangOpts.OpenACC && !InitType.isNull())
14617 OpenACC().ActOnVariableInit(VDecl, InitType);
14618}
14619
14621 // Our main concern here is re-establishing invariants like "a
14622 // variable's type is either dependent or complete".
14623 if (!D || D->isInvalidDecl()) return;
14624
14625 VarDecl *VD = dyn_cast<VarDecl>(D);
14626 if (!VD) return;
14627
14628 // Bindings are not usable if we can't make sense of the initializer.
14629 if (auto *DD = dyn_cast<DecompositionDecl>(D))
14630 for (auto *BD : DD->bindings())
14631 BD->setInvalidDecl();
14632
14633 // Auto types are meaningless if we can't make sense of the initializer.
14634 if (VD->getType()->isUndeducedType()) {
14635 D->setInvalidDecl();
14636 return;
14637 }
14638
14639 QualType Ty = VD->getType();
14640 if (Ty->isDependentType()) return;
14641
14642 // Require a complete type.
14644 Context.getBaseElementType(Ty),
14645 diag::err_typecheck_decl_incomplete_type)) {
14646 VD->setInvalidDecl();
14647 return;
14648 }
14649
14650 // Require a non-abstract type.
14651 if (RequireNonAbstractType(VD->getLocation(), Ty,
14652 diag::err_abstract_type_in_decl,
14654 VD->setInvalidDecl();
14655 return;
14656 }
14657
14658 // Don't bother complaining about constructors or destructors,
14659 // though.
14660}
14661
14663 // If there is no declaration, there was an error parsing it. Just ignore it.
14664 if (!RealDecl)
14665 return;
14666
14667 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
14668 QualType Type = Var->getType();
14669
14670 if (Type.getDesugaredType(Context) == Context.AMDGPUFeaturePredicateTy) {
14671 Diag(Var->getLocation(),
14672 diag::err_amdgcn_predicate_type_is_not_constructible)
14673 << Var;
14674 Var->setInvalidDecl();
14675 return;
14676 }
14677 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
14678 if (isa<DecompositionDecl>(RealDecl)) {
14679 // Point the caret to the token immediately after the closing bracket if
14680 // it can be found; otherwise fall back to the declaration's location.
14681 SourceLocation Loc = Var->getLocation();
14682 SourceLocation RSquareLoc =
14683 dyn_cast<DecompositionDecl>(RealDecl)->getRSquareLoc();
14684 if (std::optional<Token> Next = Lexer::findNextToken(
14685 RSquareLoc, PP.getSourceManager(), PP.getLangOpts()))
14686 Loc = Next->getLocation();
14687 Diag(Loc, diag::err_decomp_decl_requires_init) << Var;
14688 Var->setInvalidDecl();
14689 return;
14690 }
14691
14692 if (Type->isUndeducedType() &&
14693 DeduceVariableDeclarationType(Var, false, nullptr))
14694 return;
14695
14696 this->CheckAttributesOnDeducedType(RealDecl);
14697
14698 // C++11 [class.static.data]p3: A static data member can be declared with
14699 // the constexpr specifier; if so, its declaration shall specify
14700 // a brace-or-equal-initializer.
14701 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
14702 // the definition of a variable [...] or the declaration of a static data
14703 // member.
14704 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
14705 !Var->isThisDeclarationADemotedDefinition()) {
14706 if (Var->isStaticDataMember()) {
14707 // C++1z removes the relevant rule; the in-class declaration is always
14708 // a definition there.
14709 if (!getLangOpts().CPlusPlus17 &&
14710 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14711 Diag(Var->getLocation(),
14712 diag::err_constexpr_static_mem_var_requires_init)
14713 << Var;
14714 Var->setInvalidDecl();
14715 return;
14716 }
14717 } else {
14718 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
14719 Var->setInvalidDecl();
14720 return;
14721 }
14722 }
14723
14724 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
14725 // be initialized.
14726 if (!Var->isInvalidDecl() &&
14727 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
14728 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
14729 bool HasConstExprDefaultConstructor = false;
14730 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14731 for (auto *Ctor : RD->ctors()) {
14732 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
14733 Ctor->getMethodQualifiers().getAddressSpace() ==
14735 HasConstExprDefaultConstructor = true;
14736 }
14737 }
14738 }
14739 if (!HasConstExprDefaultConstructor) {
14740 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
14741 Var->setInvalidDecl();
14742 return;
14743 }
14744 }
14745
14746 // HLSL variable with the `vk::constant_id` attribute must be initialized.
14747 if (!Var->isInvalidDecl() && Var->hasAttr<HLSLVkConstantIdAttr>()) {
14748 Diag(Var->getLocation(), diag::err_specialization_const);
14749 Var->setInvalidDecl();
14750 return;
14751 }
14752
14753 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
14754 if (Var->getStorageClass() == SC_Extern) {
14755 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
14756 << Var;
14757 Var->setInvalidDecl();
14758 return;
14759 }
14760 if (RequireCompleteType(Var->getLocation(), Var->getType(),
14761 diag::err_typecheck_decl_incomplete_type)) {
14762 Var->setInvalidDecl();
14763 return;
14764 }
14765 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
14766 if (!RD->hasTrivialDefaultConstructor()) {
14767 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
14768 Var->setInvalidDecl();
14769 return;
14770 }
14771 }
14772 // The declaration is uninitialized, no need for further checks.
14773 return;
14774 }
14775
14776 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
14777 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
14778 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
14779 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
14781 NTCUK_Init);
14782
14783 switch (DefKind) {
14785 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
14786 break;
14787
14788 // We have an out-of-line definition of a static data member
14789 // that has an in-class initializer, so we type-check this like
14790 // a declaration.
14791 //
14792 [[fallthrough]];
14793
14795 // It's only a declaration.
14796
14797 // Block scope. C99 6.7p7: If an identifier for an object is
14798 // declared with no linkage (C99 6.2.2p6), the type for the
14799 // object shall be complete.
14800 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
14801 !Var->hasLinkage() && !Var->isInvalidDecl() &&
14802 RequireCompleteType(Var->getLocation(), Type,
14803 diag::err_typecheck_decl_incomplete_type))
14804 Var->setInvalidDecl();
14805
14806 // Make sure that the type is not abstract.
14807 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14808 RequireNonAbstractType(Var->getLocation(), Type,
14809 diag::err_abstract_type_in_decl,
14811 Var->setInvalidDecl();
14812 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
14813 Var->getStorageClass() == SC_PrivateExtern) {
14814 Diag(Var->getLocation(), diag::warn_private_extern);
14815 Diag(Var->getLocation(), diag::note_private_extern);
14816 }
14817
14818 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
14819 !Var->isInvalidDecl())
14820 ExternalDeclarations.push_back(Var);
14821
14822 return;
14823
14825 // File scope. C99 6.9.2p2: A declaration of an identifier for an
14826 // object that has file scope without an initializer, and without a
14827 // storage-class specifier or with the storage-class specifier "static",
14828 // constitutes a tentative definition. Note: A tentative definition with
14829 // external linkage is valid (C99 6.2.2p5).
14830 if (!Var->isInvalidDecl()) {
14831 if (const IncompleteArrayType *ArrayT
14832 = Context.getAsIncompleteArrayType(Type)) {
14834 Var->getLocation(), ArrayT->getElementType(),
14835 diag::err_array_incomplete_or_sizeless_type))
14836 Var->setInvalidDecl();
14837 }
14838 if (Var->getStorageClass() == SC_Static) {
14839 // C99 6.9.2p3: If the declaration of an identifier for an object is
14840 // a tentative definition and has internal linkage (C99 6.2.2p3), the
14841 // declared type shall not be an incomplete type.
14842 // NOTE: code such as the following
14843 // static struct s;
14844 // struct s { int a; };
14845 // is accepted by gcc. Hence here we issue a warning instead of
14846 // an error and we do not invalidate the static declaration.
14847 // NOTE: to avoid multiple warnings, only check the first declaration.
14848 if (Var->isFirstDecl())
14849 RequireCompleteType(Var->getLocation(), Type,
14850 diag::ext_typecheck_decl_incomplete_type,
14851 Type->isArrayType());
14852 }
14853 }
14854
14855 // Record the tentative definition; we're done.
14856 if (!Var->isInvalidDecl())
14857 TentativeDefinitions.push_back(Var);
14858 return;
14859 }
14860
14861 // Provide a specific diagnostic for uninitialized variable definitions
14862 // with incomplete array type, unless it is a global unbounded HLSL resource
14863 // array.
14864 if (Type->isIncompleteArrayType() &&
14865 !(getLangOpts().HLSL && Var->hasGlobalStorage() &&
14867 if (Var->isConstexpr())
14868 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
14869 << Var;
14870 else
14871 Diag(Var->getLocation(),
14872 diag::err_typecheck_incomplete_array_needs_initializer);
14873 Var->setInvalidDecl();
14874 return;
14875 }
14876
14877 // Provide a specific diagnostic for uninitialized variable
14878 // definitions with reference type.
14879 if (Type->isReferenceType()) {
14880 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
14881 << Var << SourceRange(Var->getLocation(), Var->getLocation());
14882 return;
14883 }
14884
14885 // Do not attempt to type-check the default initializer for a
14886 // variable with dependent type.
14887 if (Type->isDependentType())
14888 return;
14889
14890 if (Var->isInvalidDecl())
14891 return;
14892
14893 if (!Var->hasAttr<AliasAttr>()) {
14894 if (RequireCompleteType(Var->getLocation(),
14895 Context.getBaseElementType(Type),
14896 diag::err_typecheck_decl_incomplete_type)) {
14897 Var->setInvalidDecl();
14898 return;
14899 }
14900 } else {
14901 return;
14902 }
14903
14904 // The variable can not have an abstract class type.
14905 if (RequireNonAbstractType(Var->getLocation(), Type,
14906 diag::err_abstract_type_in_decl,
14908 Var->setInvalidDecl();
14909 return;
14910 }
14911
14912 // In C, if the definition is const-qualified and has no initializer, it
14913 // is left uninitialized unless it has static or thread storage duration.
14914 if (!getLangOpts().CPlusPlus && Type.isConstQualified()) {
14915 unsigned DiagID = diag::warn_default_init_const_unsafe;
14916 if (Var->getStorageDuration() == SD_Static ||
14917 Var->getStorageDuration() == SD_Thread)
14918 DiagID = diag::warn_default_init_const;
14919
14920 bool EmitCppCompat = !Diags.isIgnored(
14921 diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit,
14922 Var->getLocation());
14923
14924 Diag(Var->getLocation(), DiagID) << Type << EmitCppCompat;
14925 }
14926
14927 // Check for jumps past the implicit initializer. C++0x
14928 // clarifies that this applies to a "variable with automatic
14929 // storage duration", not a "local variable".
14930 // C++11 [stmt.dcl]p3
14931 // A program that jumps from a point where a variable with automatic
14932 // storage duration is not in scope to a point where it is in scope is
14933 // ill-formed unless the variable has scalar type, class type with a
14934 // trivial default constructor and a trivial destructor, a cv-qualified
14935 // version of one of these types, or an array of one of the preceding
14936 // types and is declared without an initializer.
14937 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
14938 if (const auto *CXXRecord =
14939 Context.getBaseElementType(Type)->getAsCXXRecordDecl()) {
14940 // Mark the function (if we're in one) for further checking even if the
14941 // looser rules of C++11 do not require such checks, so that we can
14942 // diagnose incompatibilities with C++98.
14943 if (!CXXRecord->isPOD())
14945 }
14946 }
14947 // In OpenCL, we can't initialize objects in the __local address space,
14948 // even implicitly, so don't synthesize an implicit initializer.
14949 if (getLangOpts().OpenCL &&
14950 Var->getType().getAddressSpace() == LangAS::opencl_local)
14951 return;
14952
14953 // Handle HLSL uninitialized decls
14954 if (getLangOpts().HLSL && HLSL().ActOnUninitializedVarDecl(Var))
14955 return;
14956
14957 // HLSL input & push-constant variables are expected to be externally
14958 // initialized, even when marked `static`.
14959 if (getLangOpts().HLSL &&
14960 hlsl::isInitializedByPipeline(Var->getType().getAddressSpace()))
14961 return;
14962
14963 // C++03 [dcl.init]p9:
14964 // If no initializer is specified for an object, and the
14965 // object is of (possibly cv-qualified) non-POD class type (or
14966 // array thereof), the object shall be default-initialized; if
14967 // the object is of const-qualified type, the underlying class
14968 // type shall have a user-declared default
14969 // constructor. Otherwise, if no initializer is specified for
14970 // a non- static object, the object and its subobjects, if
14971 // any, have an indeterminate initial value); if the object
14972 // or any of its subobjects are of const-qualified type, the
14973 // program is ill-formed.
14974 // C++0x [dcl.init]p11:
14975 // If no initializer is specified for an object, the object is
14976 // default-initialized; [...].
14979 = InitializationKind::CreateDefault(Var->getLocation());
14980
14981 InitializationSequence InitSeq(*this, Entity, Kind, {});
14982 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, {});
14983
14984 if (Init.get()) {
14985 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
14986 // This is important for template substitution.
14987 Var->setInitStyle(VarDecl::CallInit);
14988 } else if (Init.isInvalid()) {
14989 // If default-init fails, attach a recovery-expr initializer to track
14990 // that initialization was attempted and failed.
14991 auto RecoveryExpr =
14992 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
14993 if (RecoveryExpr.get())
14994 Var->setInit(RecoveryExpr.get());
14995 }
14996
14998 }
14999}
15000
15001void Sema::ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt) {
15002 // If there is no declaration, there was an error parsing it. Ignore it.
15003 if (!D)
15004 return;
15005
15006 VarDecl *VD = dyn_cast<VarDecl>(D);
15007 if (!VD) {
15008 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var)
15009 << InExpansionStmt;
15010 D->setInvalidDecl();
15011 return;
15012 }
15013
15014 VD->setCXXForRangeDecl(true);
15015
15016 // for-range-declaration cannot be given a storage class specifier.
15017 int Error = -1;
15018 switch (VD->getStorageClass()) {
15019 case SC_None:
15020 break;
15021 case SC_Extern:
15022 Error = 0;
15023 break;
15024 case SC_Static:
15025 Error = 1;
15026 break;
15027 case SC_PrivateExtern:
15028 Error = 2;
15029 break;
15030 case SC_Auto:
15031 Error = 3;
15032 break;
15033 case SC_Register:
15034 Error = 4;
15035 break;
15036 }
15037
15038 // for-range-declaration cannot be given a storage class specifier con't.
15039 switch (VD->getTSCSpec()) {
15040 case TSCS_thread_local:
15041 Error = 6;
15042 break;
15043 case TSCS___thread:
15044 case TSCS__Thread_local:
15045 case TSCS_unspecified:
15046 break;
15047 }
15048
15049 if (Error != -1) {
15050 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
15051 << InExpansionStmt << VD << Error;
15052 D->setInvalidDecl();
15053 }
15054}
15055
15057 IdentifierInfo *Ident,
15058 ParsedAttributes &Attrs) {
15059 // C++1y [stmt.iter]p1:
15060 // A range-based for statement of the form
15061 // for ( for-range-identifier : for-range-initializer ) statement
15062 // is equivalent to
15063 // for ( auto&& for-range-identifier : for-range-initializer ) statement
15064 DeclSpec DS(Attrs.getPool().getFactory());
15065
15066 const char *PrevSpec;
15067 unsigned DiagID;
15068 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
15070
15072 D.SetIdentifier(Ident, IdentLoc);
15073 D.takeAttributesAppending(Attrs);
15074
15075 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
15076 IdentLoc);
15077 Decl *Var = ActOnDeclarator(S, D);
15078 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
15080 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
15081 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
15082 : IdentLoc);
15083}
15084
15087 return;
15088 auto *Attr = LifetimeBoundAttr::CreateImplicit(Context, MD->getLocation());
15089 QualType MethodType = MD->getType();
15090 QualType AttributedType =
15091 Context.getAttributedType(Attr, MethodType, MethodType);
15092 TypeLocBuilder TLB;
15093 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
15094 TLB.pushFullCopy(TSI->getTypeLoc());
15095 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(AttributedType);
15096 TyLoc.setAttr(Attr);
15097 MD->setType(AttributedType);
15098 MD->setTypeSourceInfo(TLB.getTypeSourceInfo(Context, AttributedType));
15099}
15100
15102 if (var->isInvalidDecl()) return;
15103
15105
15106 if (getLangOpts().OpenCL) {
15107 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
15108 // initialiser
15109 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
15110 !var->hasInit()) {
15111 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
15112 << 1 /*Init*/;
15113 var->setInvalidDecl();
15114 return;
15115 }
15116 }
15117
15118 // In Objective-C, don't allow jumps past the implicit initialization of a
15119 // local retaining variable.
15120 if (getLangOpts().ObjC &&
15121 var->hasLocalStorage()) {
15122 switch (var->getType().getObjCLifetime()) {
15126 break;
15127
15131 break;
15132 }
15133 }
15134
15135 if (var->hasLocalStorage() &&
15136 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
15138
15139 // Warn about externally-visible variables being defined without a
15140 // prior declaration. We only want to do this for global
15141 // declarations, but we also specifically need to avoid doing it for
15142 // class members because the linkage of an anonymous class can
15143 // change if it's later given a typedef name.
15144 if (var->isThisDeclarationADefinition() &&
15145 var->getDeclContext()->getRedeclContext()->isFileContext() &&
15146 var->isExternallyVisible() && var->hasLinkage() &&
15147 !var->isInline() && !var->getDescribedVarTemplate() &&
15148 var->getStorageClass() != SC_Register &&
15150 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
15151 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
15152 var->getLocation())) {
15153 // Find a previous declaration that's not a definition.
15154 VarDecl *prev = var->getPreviousDecl();
15155 while (prev && prev->isThisDeclarationADefinition())
15156 prev = prev->getPreviousDecl();
15157
15158 if (!prev) {
15159 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
15160 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
15161 << /* variable */ 0;
15162 }
15163 }
15164
15165 // Cache the result of checking for constant initialization.
15166 std::optional<bool> CacheHasConstInit;
15167 const Expr *CacheCulprit = nullptr;
15168 auto checkConstInit = [&]() mutable {
15169 const Expr *Init = var->getInit();
15170 if (Init->isInstantiationDependent())
15171 return true;
15172
15173 if (!CacheHasConstInit)
15174 CacheHasConstInit = var->getInit()->isConstantInitializer(
15175 Context, var->getType()->isReferenceType(), &CacheCulprit);
15176 return *CacheHasConstInit;
15177 };
15178
15179 if (var->getTLSKind() == VarDecl::TLS_Static) {
15180 if (var->getType().isDestructedType()) {
15181 // GNU C++98 edits for __thread, [basic.start.term]p3:
15182 // The type of an object with thread storage duration shall not
15183 // have a non-trivial destructor.
15184 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
15186 Diag(var->getLocation(), diag::note_use_thread_local);
15187 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
15188 if (!checkConstInit()) {
15189 // GNU C++98 edits for __thread, [basic.start.init]p4:
15190 // An object of thread storage duration shall not require dynamic
15191 // initialization.
15192 // FIXME: Need strict checking here.
15193 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
15194 << CacheCulprit->getSourceRange();
15196 Diag(var->getLocation(), diag::note_use_thread_local);
15197 }
15198 }
15199 }
15200
15201
15202 if (!var->getType()->isStructureType() && var->hasInit() &&
15203 isa<InitListExpr>(var->getInit())) {
15204 const auto *ILE = cast<InitListExpr>(var->getInit());
15205 unsigned NumInits = ILE->getNumInits();
15206 if (NumInits > 2)
15207 for (unsigned I = 0; I < NumInits; ++I) {
15208 const auto *Init = ILE->getInit(I);
15209 if (!Init)
15210 break;
15211 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15212 if (!SL)
15213 break;
15214
15215 unsigned NumConcat = SL->getNumConcatenated();
15216 // Diagnose missing comma in string array initialization.
15217 // Do not warn when all the elements in the initializer are concatenated
15218 // together. Do not warn for macros too.
15219 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
15220 bool OnlyOneMissingComma = true;
15221 for (unsigned J = I + 1; J < NumInits; ++J) {
15222 const auto *Init = ILE->getInit(J);
15223 if (!Init)
15224 break;
15225 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
15226 if (!SLJ || SLJ->getNumConcatenated() > 1) {
15227 OnlyOneMissingComma = false;
15228 break;
15229 }
15230 }
15231
15232 if (OnlyOneMissingComma) {
15234 for (unsigned i = 0; i < NumConcat - 1; ++i)
15235 Hints.push_back(FixItHint::CreateInsertion(
15236 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
15237
15238 Diag(SL->getStrTokenLoc(1),
15239 diag::warn_concatenated_literal_array_init)
15240 << Hints;
15241 Diag(SL->getBeginLoc(),
15242 diag::note_concatenated_string_literal_silence);
15243 }
15244 // In any case, stop now.
15245 break;
15246 }
15247 }
15248 }
15249
15250
15251 QualType type = var->getType();
15252
15253 if (var->hasAttr<BlocksAttr>())
15255
15256 Expr *Init = var->getInit();
15257 bool GlobalStorage = var->hasGlobalStorage();
15258 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
15259 QualType baseType = Context.getBaseElementType(type);
15260 bool HasConstInit = true;
15261
15262 if (getLangOpts().C23 && var->isConstexpr() && !Init)
15263 Diag(var->getLocation(), diag::err_constexpr_var_requires_const_init)
15264 << var;
15265
15266 // Check whether the initializer is sufficiently constant.
15267 if ((getLangOpts().CPlusPlus || (getLangOpts().C23 && var->isConstexpr())) &&
15268 !type->isDependentType() && Init && !Init->isValueDependent() &&
15269 (GlobalStorage || var->isConstexpr() ||
15270 var->mightBeUsableInConstantExpressions(Context))) {
15271 // If this variable might have a constant initializer or might be usable in
15272 // constant expressions, check whether or not it actually is now. We can't
15273 // do this lazily, because the result might depend on things that change
15274 // later, such as which constexpr functions happen to be defined.
15276 if (!getLangOpts().CPlusPlus11 && !getLangOpts().C23) {
15277 // Prior to C++11, in contexts where a constant initializer is required,
15278 // the set of valid constant initializers is described by syntactic rules
15279 // in [expr.const]p2-6.
15280 // FIXME: Stricter checking for these rules would be useful for constinit /
15281 // -Wglobal-constructors.
15282 HasConstInit = checkConstInit();
15283
15284 // Compute and cache the constant value, and remember that we have a
15285 // constant initializer.
15286 if (HasConstInit) {
15287 if (var->isStaticDataMember() && !var->isInline() &&
15288 var->getLexicalDeclContext()->isRecord() &&
15289 type->isIntegralOrEnumerationType()) {
15290 // In C++98, in-class initialization for a static data member must
15291 // be an integer constant expression.
15292 if (!Init->isIntegerConstantExpr(Context)) {
15293 Diag(Init->getExprLoc(),
15294 diag::ext_in_class_initializer_non_constant)
15295 << Init->getSourceRange();
15296 }
15297 }
15298 (void)var->checkForConstantInitialization(Notes);
15299 Notes.clear();
15300 } else if (CacheCulprit) {
15301 Notes.emplace_back(CacheCulprit->getExprLoc(),
15302 PDiag(diag::note_invalid_subexpr_in_const_expr));
15303 Notes.back().second << CacheCulprit->getSourceRange();
15304 }
15305 } else {
15306 // Evaluate the initializer to see if it's a constant initializer.
15307 HasConstInit = var->checkForConstantInitialization(Notes);
15308 }
15309
15310 if (HasConstInit) {
15311 // FIXME: Consider replacing the initializer with a ConstantExpr.
15312 } else if (var->isConstexpr()) {
15313 SourceLocation DiagLoc = var->getLocation();
15314 // If the note doesn't add any useful information other than a source
15315 // location, fold it into the primary diagnostic.
15316 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15317 diag::note_invalid_subexpr_in_const_expr) {
15318 DiagLoc = Notes[0].first;
15319 Notes.clear();
15320 }
15321 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
15322 << var << Init->getSourceRange();
15323 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15324 Diag(Notes[I].first, Notes[I].second);
15325 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
15326 auto *Attr = var->getAttr<ConstInitAttr>();
15327 Diag(var->getLocation(), diag::err_require_constant_init_failed)
15328 << Init->getSourceRange();
15329 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
15330 << Attr->getRange() << Attr->isConstinit();
15331 for (auto &it : Notes)
15332 Diag(it.first, it.second);
15333 } else if (var->isStaticDataMember() && !var->isInline() &&
15334 var->getLexicalDeclContext()->isRecord()) {
15335 Diag(var->getLocation(), diag::err_in_class_initializer_non_constant)
15336 << Init->getSourceRange();
15337 for (auto &it : Notes)
15338 Diag(it.first, it.second);
15339 var->setInvalidDecl();
15340 } else if (IsGlobal &&
15341 !getDiagnostics().isIgnored(diag::warn_global_constructor,
15342 var->getLocation())) {
15343 // Warn about globals which don't have a constant initializer. Don't
15344 // warn about globals with a non-trivial destructor because we already
15345 // warned about them.
15346 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
15347 if (!(RD && !RD->hasTrivialDestructor())) {
15348 // checkConstInit() here permits trivial default initialization even in
15349 // C++11 onwards, where such an initializer is not a constant initializer
15350 // but nonetheless doesn't require a global constructor.
15351 if (!checkConstInit())
15352 Diag(var->getLocation(), diag::warn_global_constructor)
15353 << Init->getSourceRange();
15354 }
15355 }
15356 }
15357
15358 // Apply section attributes and pragmas to global variables.
15359 if (GlobalStorage && var->isThisDeclarationADefinition() &&
15361 PragmaStack<StringLiteral *> *Stack = nullptr;
15362 int SectionFlags = ASTContext::PSF_Read;
15363 bool MSVCEnv =
15364 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment();
15365 std::optional<QualType::NonConstantStorageReason> Reason;
15366 if (HasConstInit &&
15367 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) {
15368 Stack = &ConstSegStack;
15369 } else {
15370 SectionFlags |= ASTContext::PSF_Write;
15371 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack;
15372 }
15373 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
15374 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
15375 SectionFlags |= ASTContext::PSF_Implicit;
15376 UnifySection(SA->getName(), SectionFlags, var);
15377 } else if (Stack->CurrentValue) {
15378 if (Stack != &ConstSegStack && MSVCEnv &&
15379 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue &&
15380 var->getType().isConstQualified()) {
15381 assert((!Reason || Reason != QualType::NonConstantStorageReason::
15382 NonConstNonReferenceType) &&
15383 "This case should've already been handled elsewhere");
15384 Diag(var->getLocation(), diag::warn_section_msvc_compat)
15385 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit
15387 : *Reason);
15388 }
15389 SectionFlags |= ASTContext::PSF_Implicit;
15390 auto SectionName = Stack->CurrentValue->getString();
15391 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName,
15392 Stack->CurrentPragmaLocation,
15393 SectionAttr::Declspec_allocate));
15394 if (UnifySection(SectionName, SectionFlags, var))
15395 var->dropAttr<SectionAttr>();
15396 }
15397
15398 // Apply the init_seg attribute if this has an initializer. If the
15399 // initializer turns out to not be dynamic, we'll end up ignoring this
15400 // attribute.
15401 if (CurInitSeg && var->getInit())
15402 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
15403 CurInitSegLoc));
15404 }
15405
15406 // All the following checks are C++ only.
15407 if (!getLangOpts().CPlusPlus) {
15408 // If this variable must be emitted, add it as an initializer for the
15409 // current module.
15410 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
15411 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15412 return;
15413 }
15414
15416
15417 // Require the destructor.
15418 if (!type->isDependentType())
15419 if (auto *RD = baseType->getAsCXXRecordDecl())
15421
15422 // If this variable must be emitted, add it as an initializer for the current
15423 // module. For named modules, discardable inline variables may be deferred
15424 // until they are odr-used. Non-inline variables that must be emitted,
15425 // including those with side-effecting initialization, must still be emitted
15426 // even if they have internal linkage.
15427 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) {
15428 GVALinkage Linkage = Context.GetGVALinkageForVariable(var);
15429 if (ModuleScopes.back().Module->isHeaderLikeModule() ||
15431 (Linkage == GVA_Internal && !var->isInline()))
15432 Context.addModuleInitializer(ModuleScopes.back().Module, var);
15433 }
15434
15435 // Build the bindings if this is a structured binding declaration.
15436 if (auto *DD = dyn_cast<DecompositionDecl>(var))
15438}
15439
15441 assert(VD->isStaticLocal());
15442
15443 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15444
15445 // Find outermost function when VD is in lambda function.
15446 while (FD && !getDLLAttr(FD) &&
15447 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
15448 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
15449 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
15450 }
15451
15452 if (!FD)
15453 return;
15454
15455 // Static locals inherit dll attributes from their function.
15456 if (Attr *A = getDLLAttr(FD)) {
15457 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
15458 NewAttr->setInherited(true);
15459 VD->addAttr(NewAttr);
15460 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
15461 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
15462 NewAttr->setInherited(true);
15463 VD->addAttr(NewAttr);
15464
15465 // Export this function to enforce exporting this static variable even
15466 // if it is not used in this compilation unit.
15467 if (!FD->hasAttr<DLLExportAttr>())
15468 FD->addAttr(NewAttr);
15469
15470 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
15471 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
15472 NewAttr->setInherited(true);
15473 VD->addAttr(NewAttr);
15474 }
15475}
15476
15478 assert(VD->getTLSKind());
15479
15480 // Perform TLS alignment check here after attributes attached to the variable
15481 // which may affect the alignment have been processed. Only perform the check
15482 // if the target has a maximum TLS alignment (zero means no constraints).
15483 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
15484 // Protect the check so that it's not performed on dependent types and
15485 // dependent alignments (we can't determine the alignment in that case).
15486 if (!VD->hasDependentAlignment()) {
15487 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
15488 if (Context.getDeclAlign(VD) > MaxAlignChars) {
15489 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
15490 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
15491 << (unsigned)MaxAlignChars.getQuantity();
15492 }
15493 }
15494 }
15495}
15496
15498 // Note that we are no longer parsing the initializer for this declaration.
15499 ParsingInitForAutoVars.erase(ThisDecl);
15500
15501 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
15502 if (!VD)
15503 return;
15504
15505 // Emit any deferred warnings for the variable's initializer, even if the
15506 // variable is invalid
15507 AnalysisWarnings.issueWarningsForRegisteredVarDecl(VD);
15508
15509 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
15511 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
15512 if (PragmaClangBSSSection.Valid)
15513 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
15514 Context, PragmaClangBSSSection.SectionName,
15515 PragmaClangBSSSection.PragmaLocation));
15516 if (PragmaClangDataSection.Valid)
15517 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
15518 Context, PragmaClangDataSection.SectionName,
15519 PragmaClangDataSection.PragmaLocation));
15520 if (PragmaClangRodataSection.Valid)
15521 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
15522 Context, PragmaClangRodataSection.SectionName,
15523 PragmaClangRodataSection.PragmaLocation));
15524 if (PragmaClangRelroSection.Valid)
15525 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
15526 Context, PragmaClangRelroSection.SectionName,
15527 PragmaClangRelroSection.PragmaLocation));
15528 }
15529
15530 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
15531 for (auto *BD : DD->bindings()) {
15533 }
15534 }
15535
15536 CheckInvalidBuiltinCountedByRef(VD->getInit(),
15538
15539 checkAttributesAfterMerging(*this, *VD);
15540
15541 if (VD->isStaticLocal())
15543
15544 if (VD->getTLSKind())
15546
15547 // Perform check for initializers of device-side global variables.
15548 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
15549 // 7.5). We must also apply the same checks to all __shared__
15550 // variables whether they are local or not. CUDA also allows
15551 // constant initializers for __constant__ and __device__ variables.
15552 if (getLangOpts().CUDA)
15554
15555 // Grab the dllimport or dllexport attribute off of the VarDecl.
15556 const InheritableAttr *DLLAttr = getDLLAttr(VD);
15557
15558 // Imported static data members cannot be defined out-of-line.
15559 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
15560 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
15562 // We allow definitions of dllimport class template static data members
15563 // with a warning.
15566 bool IsClassTemplateMember =
15568 Context->getDescribedClassTemplate();
15569
15570 Diag(VD->getLocation(),
15571 IsClassTemplateMember
15572 ? diag::warn_attribute_dllimport_static_field_definition
15573 : diag::err_attribute_dllimport_static_field_definition);
15574 Diag(IA->getLocation(), diag::note_attribute);
15575 if (!IsClassTemplateMember)
15576 VD->setInvalidDecl();
15577 }
15578 }
15579
15580 // dllimport/dllexport variables cannot be thread local, their TLS index
15581 // isn't exported with the variable.
15582 if (DLLAttr && VD->getTLSKind()) {
15583 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
15584 if (F && getDLLAttr(F)) {
15585 assert(VD->isStaticLocal());
15586 // But if this is a static local in a dlimport/dllexport function, the
15587 // function will never be inlined, which means the var would never be
15588 // imported, so having it marked import/export is safe.
15589 } else {
15590 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
15591 << DLLAttr;
15592 VD->setInvalidDecl();
15593 }
15594 }
15595
15596 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
15597 if (!Attr->isInherited() && !Attr->isImplicit() &&
15599 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15600 << Attr;
15601 VD->dropAttr<UsedAttr>();
15602 }
15603 }
15604 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
15605 if (!Attr->isInherited() && !Attr->isImplicit() &&
15607 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
15608 << Attr;
15609 VD->dropAttr<RetainAttr>();
15610 }
15611 }
15612
15613 const DeclContext *DC = VD->getDeclContext();
15614 // If there's a #pragma GCC visibility in scope, and this isn't a class
15615 // member, set the visibility of this variable.
15618
15619 // FIXME: Warn on unused var template partial specializations.
15622
15623 // Now we have parsed the initializer and can update the table of magic
15624 // tag values.
15625 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
15627 return;
15628
15629 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
15630 const Expr *MagicValueExpr = VD->getInit();
15631 if (!MagicValueExpr) {
15632 continue;
15633 }
15634 std::optional<llvm::APSInt> MagicValueInt;
15635 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
15636 Diag(I->getRange().getBegin(),
15637 diag::err_type_tag_for_datatype_not_ice)
15638 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15639 continue;
15640 }
15641 if (MagicValueInt->getActiveBits() > 64) {
15642 Diag(I->getRange().getBegin(),
15643 diag::err_type_tag_for_datatype_too_large)
15644 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
15645 continue;
15646 }
15647 uint64_t MagicValue = MagicValueInt->getZExtValue();
15648 RegisterTypeTagForDatatype(I->getArgumentKind(),
15649 MagicValue,
15650 I->getMatchingCType(),
15651 I->getLayoutCompatible(),
15652 I->getMustBeNull());
15653 }
15654}
15655
15657 auto *VD = dyn_cast<VarDecl>(DD);
15658 return VD && !VD->getType()->hasAutoForTrailingReturnType();
15659}
15660
15662 ArrayRef<Decl *> Group) {
15664
15665 if (DS.isTypeSpecOwned())
15666 Decls.push_back(DS.getRepAsDecl());
15667
15668 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
15669 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
15670 bool DiagnosedMultipleDecomps = false;
15671 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
15672 bool DiagnosedNonDeducedAuto = false;
15673
15674 for (Decl *D : Group) {
15675 if (!D)
15676 continue;
15677 // Check if the Decl has been declared in '#pragma omp declare target'
15678 // directive and has static storage duration.
15679 if (auto *VD = dyn_cast<VarDecl>(D);
15680 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() &&
15681 VD->hasGlobalStorage())
15683 // For declarators, there are some additional syntactic-ish checks we need
15684 // to perform.
15685 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
15686 if (!FirstDeclaratorInGroup)
15687 FirstDeclaratorInGroup = DD;
15688 if (!FirstDecompDeclaratorInGroup)
15689 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
15690 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
15691 !hasDeducedAuto(DD))
15692 FirstNonDeducedAutoInGroup = DD;
15693
15694 if (FirstDeclaratorInGroup != DD) {
15695 // A decomposition declaration cannot be combined with any other
15696 // declaration in the same group.
15697 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
15698 Diag(FirstDecompDeclaratorInGroup->getLocation(),
15699 diag::err_decomp_decl_not_alone)
15700 << FirstDeclaratorInGroup->getSourceRange()
15701 << DD->getSourceRange();
15702 DiagnosedMultipleDecomps = true;
15703 }
15704
15705 // A declarator that uses 'auto' in any way other than to declare a
15706 // variable with a deduced type cannot be combined with any other
15707 // declarator in the same group.
15708 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
15709 Diag(FirstNonDeducedAutoInGroup->getLocation(),
15710 diag::err_auto_non_deduced_not_alone)
15711 << FirstNonDeducedAutoInGroup->getType()
15713 << FirstDeclaratorInGroup->getSourceRange()
15714 << DD->getSourceRange();
15715 DiagnosedNonDeducedAuto = true;
15716 }
15717 }
15718 }
15719
15720 Decls.push_back(D);
15721 }
15722
15724 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
15725 handleTagNumbering(Tag, S);
15726 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
15728 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
15729 }
15730 }
15731
15732 return BuildDeclaratorGroup(Decls);
15733}
15734
15737 // C++14 [dcl.spec.auto]p7: (DR1347)
15738 // If the type that replaces the placeholder type is not the same in each
15739 // deduction, the program is ill-formed.
15740 if (Group.size() > 1) {
15742 VarDecl *DeducedDecl = nullptr;
15743 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
15744 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
15745 if (!D || D->isInvalidDecl())
15746 break;
15747 DeducedType *DT = D->getType()->getContainedDeducedType();
15748 if (!DT || DT->getDeducedType().isNull())
15749 continue;
15750 if (Deduced.isNull()) {
15751 Deduced = DT->getDeducedType();
15752 DeducedDecl = D;
15753 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
15754 auto *AT = dyn_cast<AutoType>(DT);
15755 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
15756 diag::err_auto_different_deductions)
15757 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
15758 << DeducedDecl->getDeclName() << DT->getDeducedType()
15759 << D->getDeclName();
15760 if (DeducedDecl->hasInit())
15761 Dia << DeducedDecl->getInit()->getSourceRange();
15762 if (D->getInit())
15763 Dia << D->getInit()->getSourceRange();
15764 D->setInvalidDecl();
15765 break;
15766 }
15767 }
15768 }
15769
15771
15772 return DeclGroupPtrTy::make(
15773 DeclGroupRef::Create(Context, Group.data(), Group.size()));
15774}
15775
15779
15781 // Don't parse the comment if Doxygen diagnostics are ignored.
15782 if (Group.empty() || !Group[0])
15783 return;
15784
15785 if (Diags.isIgnored(diag::warn_doc_param_not_found,
15786 Group[0]->getLocation()) &&
15787 Diags.isIgnored(diag::warn_unknown_comment_command_name,
15788 Group[0]->getLocation()))
15789 return;
15790
15791 if (Group.size() >= 2) {
15792 // This is a decl group. Normally it will contain only declarations
15793 // produced from declarator list. But in case we have any definitions or
15794 // additional declaration references:
15795 // 'typedef struct S {} S;'
15796 // 'typedef struct S *S;'
15797 // 'struct S *pS;'
15798 // FinalizeDeclaratorGroup adds these as separate declarations.
15799 Decl *MaybeTagDecl = Group[0];
15800 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
15801 Group = Group.slice(1);
15802 }
15803 }
15804
15805 // FIXME: We assume every Decl in the group is in the same file.
15806 // This is false when preprocessor constructs the group from decls in
15807 // different files (e. g. macros or #include).
15808 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
15809}
15810
15812 // Check that there are no default arguments inside the type of this
15813 // parameter.
15814 if (getLangOpts().CPlusPlus)
15816
15817 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
15818 if (D.getCXXScopeSpec().isSet()) {
15819 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
15820 << D.getCXXScopeSpec().getRange();
15821 }
15822
15823 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
15824 // simple identifier except [...irrelevant cases...].
15825 switch (D.getName().getKind()) {
15827 break;
15828
15836 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
15838 break;
15839
15842 // GetNameForDeclarator would not produce a useful name in this case.
15843 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
15844 break;
15845 }
15846}
15847
15849 // This only matters in C.
15850 if (getLangOpts().CPlusPlus)
15851 return;
15852
15853 // This only matters if the declaration has a type.
15854 const auto *VD = dyn_cast<ValueDecl>(D);
15855 if (!VD)
15856 return;
15857
15858 // Get the type, this only matters for tag types.
15859 QualType QT = VD->getType();
15860 const auto *TD = QT->getAsTagDecl();
15861 if (!TD)
15862 return;
15863
15864 // Check if the tag declaration is lexically declared somewhere different
15865 // from the lexical declaration of the given object, then it will be hidden
15866 // in C++ and we should warn on it.
15867 if (!TD->getLexicalParent()->LexicallyEncloses(D->getLexicalDeclContext())) {
15868 unsigned Kind = TD->isEnum() ? 2 : TD->isUnion() ? 1 : 0;
15869 Diag(D->getLocation(), diag::warn_decl_hidden_in_cpp) << Kind;
15870 Diag(TD->getLocation(), diag::note_declared_at);
15871 }
15872}
15873
15875 SourceLocation ExplicitThisLoc) {
15876 if (!ExplicitThisLoc.isValid())
15877 return;
15878 assert(S.getLangOpts().CPlusPlus &&
15879 "explicit parameter in non-cplusplus mode");
15880 if (!S.getLangOpts().CPlusPlus23)
15881 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this)
15882 << P->getSourceRange();
15883
15884 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function
15885 // parameter pack.
15886 if (P->isParameterPack()) {
15887 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack)
15888 << P->getSourceRange();
15889 return;
15890 }
15891 P->setExplicitObjectParameterLoc(ExplicitThisLoc);
15892 if (LambdaScopeInfo *LSI = S.getCurLambda())
15893 LSI->ExplicitObjectParameter = P;
15894}
15895
15897 SourceLocation ExplicitThisLoc) {
15898 const DeclSpec &DS = D.getDeclSpec();
15899
15900 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
15901 // C2y 6.7.7.4p4: A parameter declaration shall not specify a void type,
15902 // except for the special case of a single unnamed parameter of type void
15903 // with no storage class specifier, no type qualifier, and no following
15904 // ellipsis terminator.
15905 // Clang applies the C2y rules for 'register void' in all C language modes,
15906 // same as GCC, because it's questionable what that could possibly mean.
15907
15908 // C++03 [dcl.stc]p2 also permits 'auto'.
15909 StorageClass SC = SC_None;
15911 SC = SC_Register;
15912 // In C++11, the 'register' storage class specifier is deprecated.
15913 // In C++17, it is not allowed, but we tolerate it as an extension.
15914 if (getLangOpts().CPlusPlus11) {
15916 ? diag::ext_register_storage_class
15917 : diag::warn_deprecated_register)
15919 } else if (!getLangOpts().CPlusPlus &&
15921 D.getNumTypeObjects() == 0) {
15923 diag::err_invalid_storage_class_in_func_decl)
15926 }
15927 } else if (getLangOpts().CPlusPlus &&
15929 SC = SC_Auto;
15932 diag::err_invalid_storage_class_in_func_decl);
15934 }
15935
15937 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
15939 if (DS.isInlineSpecified())
15940 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
15941 << getLangOpts().CPlusPlus17;
15942 if (DS.hasConstexprSpecifier())
15943 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
15944 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
15945
15947
15949
15951 QualType parmDeclType = TInfo->getType();
15952
15953 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
15954 const IdentifierInfo *II = D.getIdentifier();
15955 if (II) {
15958 LookupName(R, S);
15959 if (!R.empty()) {
15960 NamedDecl *PrevDecl = *R.begin();
15961 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) {
15962 // Maybe we will complain about the shadowed template parameter.
15964 // Just pretend that we didn't see the previous declaration.
15965 PrevDecl = nullptr;
15966 }
15967 if (PrevDecl && S->isDeclScope(PrevDecl)) {
15968 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
15969 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15970 // Recover by removing the name
15971 II = nullptr;
15972 D.SetIdentifier(nullptr, D.getIdentifierLoc());
15973 D.setInvalidType(true);
15974 }
15975 }
15976 }
15977
15978 // Incomplete resource arrays are not allowed as function parameters in HLSL
15979 if (getLangOpts().HLSL && parmDeclType->isIncompleteArrayType()) {
15980 QualType EltTy = Context.getBaseElementType(parmDeclType);
15981 // `isCompleteType` forces completion of the element type so the resource
15982 // check is valid.
15983 if (!EltTy->isDependentType() &&
15984 isCompleteType(D.getIdentifierLoc(), EltTy) &&
15985 parmDeclType->isHLSLResourceRecordArray()) {
15987 diag::err_hlsl_incomplete_resource_array_in_function_param);
15988 D.setInvalidType(true);
15989 }
15990 }
15991
15992 // Temporarily put parameter variables in the translation unit, not
15993 // the enclosing context. This prevents them from accidentally
15994 // looking like class members in C++.
15995 ParmVarDecl *New =
15996 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
15997 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
15998
15999 if (D.isInvalidType())
16000 New->setInvalidDecl();
16001
16002 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc);
16003
16004 assert(S->isFunctionPrototypeScope());
16005 assert(S->getFunctionPrototypeDepth() >= 1);
16006 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
16008
16010
16011 // Add the parameter declaration into this scope.
16012 S->AddDecl(New);
16013 if (II)
16014 IdResolver.AddDecl(New);
16015
16017
16019 Diag(New->getLocation(), diag::err_module_private_local)
16022
16023 if (New->hasAttr<BlocksAttr>())
16024 Diag(New->getLocation(), diag::err_block_not_allowed_on)
16025 << diag::NotAllowedBlockVarReason::NonlocalVariable;
16026
16027 New->deduceParmAddressSpace(Context);
16028
16029 return New;
16030}
16031
16033 SourceLocation Loc,
16034 QualType T) {
16035 /* FIXME: setting StartLoc == Loc.
16036 Would it be worth to modify callers so as to provide proper source
16037 location for the unnamed parameters, embedding the parameter's type? */
16038 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
16039 T, Context.getTrivialTypeSourceInfo(T, Loc),
16040 SC_None, nullptr);
16041 Param->setImplicit();
16042 return Param;
16043}
16044
16046 // Don't diagnose unused-parameter errors in template instantiations; we
16047 // will already have done so in the template itself.
16049 return;
16050
16051 for (const ParmVarDecl *Parameter : Parameters) {
16052 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
16053 !Parameter->hasAttr<UnusedAttr>() &&
16054 !Parameter->getIdentifier()->isPlaceholder()) {
16055 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
16056 << Parameter->getDeclName();
16057 }
16058 }
16059}
16060
16062 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
16063 if (LangOpts.NumLargeByValueCopy == 0) // No check.
16064 return;
16065
16066 // Warn if the return value is pass-by-value and larger than the specified
16067 // threshold.
16068 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
16069 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
16070 if (Size > LangOpts.NumLargeByValueCopy)
16071 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
16072 }
16073
16074 // Warn if any parameter is pass-by-value and larger than the specified
16075 // threshold.
16076 for (const ParmVarDecl *Parameter : Parameters) {
16077 QualType T = Parameter->getType();
16078 if (T->isDependentType() || !T.isPODType(Context))
16079 continue;
16080 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
16081 if (Size > LangOpts.NumLargeByValueCopy)
16082 Diag(Parameter->getLocation(), diag::warn_parameter_size)
16083 << Parameter << Size;
16084 }
16085}
16086
16088 SourceLocation NameLoc,
16089 const IdentifierInfo *Name, QualType T,
16090 TypeSourceInfo *TSInfo, StorageClass SC) {
16091 // In ARC, infer a lifetime qualifier for appropriate parameter types.
16092 if (getLangOpts().ObjCAutoRefCount &&
16093 T.getObjCLifetime() == Qualifiers::OCL_None &&
16094 T->isObjCLifetimeType()) {
16095
16096 Qualifiers::ObjCLifetime lifetime;
16097
16098 // Special cases for arrays:
16099 // - if it's const, use __unsafe_unretained
16100 // - otherwise, it's an error
16101 if (T->isArrayType()) {
16102 if (!T.isConstQualified()) {
16106 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
16107 else
16108 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
16109 << TSInfo->getTypeLoc().getSourceRange();
16110 }
16112 } else {
16113 lifetime = T->getObjCARCImplicitLifetime();
16114 }
16115 T = Context.getLifetimeQualifiedType(T, lifetime);
16116 }
16117
16118 if (getLangOpts().OpenCL) {
16119 assert(!isa<DecayedType>(T));
16120 if (T->isArrayType() && !T.hasAddressSpace()) {
16121 QualType ET = Context.getAsArrayType(T)->getElementType();
16122 if (!ET.hasAddressSpace()) {
16123 // Add the private address space to the contents of the pointer when a
16124 // pointer parameter is declared as an array and not declared.
16126 T = Context.getAddrSpaceQualType(T, ImplAS);
16127 T = QualType(Context.getAsArrayType(T), 0);
16128 }
16129 }
16130 }
16131
16132 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
16133 Context.getAdjustedParameterType(T),
16134 TSInfo, SC, nullptr);
16135
16136 // Make a note if we created a new pack in the scope of a lambda, so that
16137 // we know that references to that pack must also be expanded within the
16138 // lambda scope.
16139 if (New->isParameterPack())
16140 if (auto *CSI = getEnclosingLambdaOrBlock())
16141 CSI->LocalPacks.push_back(New);
16142
16143 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16144 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
16145 checkNonTrivialCUnion(New->getType(), New->getLocation(),
16148
16149 // Parameter declarators cannot be interface types. All ObjC objects are
16150 // passed by reference.
16151 if (T->isObjCObjectType()) {
16152 SourceLocation TypeEndLoc =
16154 Diag(NameLoc,
16155 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
16156 << FixItHint::CreateInsertion(TypeEndLoc, "*");
16157 T = Context.getObjCObjectPointerType(T);
16158 New->setType(T);
16159 }
16160
16161 // __ptrauth is forbidden on parameters.
16162 if (T.getPointerAuth()) {
16163 Diag(NameLoc, diag::err_ptrauth_qualifier_invalid) << T << 1;
16164 New->setInvalidDecl();
16165 }
16166
16167 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
16168 // duration shall not be qualified by an address-space qualifier."
16169 // Since all parameters have automatic store duration, they can not have
16170 // an address space.
16171 if (T.getAddressSpace() != LangAS::Default &&
16172 // OpenCL allows function arguments declared to be an array of a type
16173 // to be qualified with an address space.
16174 !(getLangOpts().OpenCL &&
16175 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) &&
16176 // WebAssembly allows reference types as parameters. Funcref in particular
16177 // lives in a different address space.
16178 !(T->isFunctionPointerType() &&
16179 T.getAddressSpace() == LangAS::wasm_funcref) &&
16180 // HLSL allows function arguments to be qualified with an address space
16181 // if the groupshared annotation is used.
16182 !(getLangOpts().HLSL &&
16183 T.getAddressSpace() == LangAS::hlsl_groupshared)) {
16184 Diag(NameLoc, diag::err_arg_with_address_space);
16185 New->setInvalidDecl();
16186 }
16187
16188 // PPC MMA non-pointer types are not allowed as function argument types.
16189 if (Context.getTargetInfo().getTriple().isPPC64() &&
16190 PPC().CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
16191 New->setInvalidDecl();
16192 }
16193
16194 return New;
16195}
16196
16198 SourceLocation LocAfterDecls) {
16200
16201 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
16202 // in the declaration list shall have at least one declarator, those
16203 // declarators shall only declare identifiers from the identifier list, and
16204 // every identifier in the identifier list shall be declared.
16205 //
16206 // C89 3.7.1p5 "If a declarator includes an identifier list, only the
16207 // identifiers it names shall be declared in the declaration list."
16208 //
16209 // This is why we only diagnose in C99 and later. Note, the other conditions
16210 // listed are checked elsewhere.
16211 if (!FTI.hasPrototype) {
16212 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
16213 --i;
16214 if (FTI.Params[i].Param == nullptr) {
16215 if (getLangOpts().C99) {
16216 SmallString<256> Code;
16217 llvm::raw_svector_ostream(Code)
16218 << " int " << FTI.Params[i].Ident->getName() << ";\n";
16219 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
16220 << FTI.Params[i].Ident
16221 << FixItHint::CreateInsertion(LocAfterDecls, Code);
16222 }
16223
16224 // Implicitly declare the argument as type 'int' for lack of a better
16225 // type.
16226 AttributeFactory attrs;
16227 DeclSpec DS(attrs);
16228 const char* PrevSpec; // unused
16229 unsigned DiagID; // unused
16230 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
16231 DiagID, Context.getPrintingPolicy());
16232 // Use the identifier location for the type source range.
16233 DS.SetRangeStart(FTI.Params[i].IdentLoc);
16234 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
16237 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
16238 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
16239 }
16240 }
16241 }
16242}
16243
16244Decl *
16246 MultiTemplateParamsArg TemplateParameterLists,
16247 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
16248 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
16249 assert(D.isFunctionDeclarator() && "Not a function declarator!");
16250 Scope *ParentScope = FnBodyScope->getParent();
16251
16252 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
16253 // we define a non-templated function definition, we will create a declaration
16254 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
16255 // The base function declaration will have the equivalent of an `omp declare
16256 // variant` annotation which specifies the mangled definition as a
16257 // specialization function under the OpenMP context defined as part of the
16258 // `omp begin declare variant`.
16260 if (LangOpts.OpenMP && OpenMP().isInOpenMPDeclareVariantScope())
16262 ParentScope, D, TemplateParameterLists, Bases);
16263
16265 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
16266 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
16267
16268 if (!Bases.empty())
16270 Bases);
16271
16272 return Dcl;
16273}
16274
16276 Consumer.HandleInlineFunctionDefinition(D);
16277}
16278
16280 const FunctionDecl *&PossiblePrototype) {
16281 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
16282 Prev = Prev->getPreviousDecl()) {
16283 // Ignore any declarations that occur in function or method
16284 // scope, because they aren't visible from the header.
16285 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
16286 continue;
16287
16288 PossiblePrototype = Prev;
16289 return Prev->getType()->isFunctionProtoType();
16290 }
16291 return false;
16292}
16293
16294static bool
16296 const FunctionDecl *&PossiblePrototype) {
16297 // Don't warn about invalid declarations.
16298 if (FD->isInvalidDecl())
16299 return false;
16300
16301 // Or declarations that aren't global.
16302 if (!FD->isGlobal())
16303 return false;
16304
16305 // Don't warn about C++ member functions.
16306 if (isa<CXXMethodDecl>(FD))
16307 return false;
16308
16309 // Don't warn about 'main'.
16311 if (IdentifierInfo *II = FD->getIdentifier())
16312 if (II->isStr("main") || II->isStr("efi_main"))
16313 return false;
16314
16315 if (FD->isMSVCRTEntryPoint())
16316 return false;
16317
16318 // Don't warn about inline functions.
16319 if (FD->isInlined())
16320 return false;
16321
16322 // Don't warn about function templates.
16324 return false;
16325
16326 // Don't warn about function template specializations.
16328 return false;
16329
16330 // Don't warn for OpenCL kernels.
16331 if (FD->hasAttr<DeviceKernelAttr>())
16332 return false;
16333
16334 // Don't warn on explicitly deleted functions.
16335 if (FD->isDeleted())
16336 return false;
16337
16338 // Don't warn on implicitly local functions (such as having local-typed
16339 // parameters).
16340 if (!FD->isExternallyVisible())
16341 return false;
16342
16343 // If we were able to find a potential prototype, don't warn.
16344 if (FindPossiblePrototype(FD, PossiblePrototype))
16345 return false;
16346
16347 return true;
16348}
16349
16350void
16352 const FunctionDecl *EffectiveDefinition,
16353 SkipBodyInfo *SkipBody) {
16354 const FunctionDecl *Definition = EffectiveDefinition;
16355 if (!Definition &&
16356 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
16357 return;
16358
16359 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
16360 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
16361 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
16362 // A merged copy of the same function, instantiated as a member of
16363 // the same class, is OK.
16364 if (declaresSameEntity(OrigFD, OrigDef) &&
16365 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
16367 return;
16368 }
16369 }
16370 }
16371
16373 return;
16374
16375 // Don't emit an error when this is redefinition of a typo-corrected
16376 // definition.
16378 return;
16379
16380 bool DefinitionVisible = false;
16381 if (SkipBody &&
16383 DefinitionVisible) &&
16384 (Definition->getFormalLinkage() == Linkage::Internal ||
16385 Definition->isInlined() || Definition->getDescribedFunctionTemplate() ||
16386 !Definition->getTemplateParameterLists().empty())) {
16387 SkipBody->ShouldSkip = true;
16388 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
16389 if (!DefinitionVisible) {
16390 if (auto *TD = Definition->getDescribedFunctionTemplate())
16393 }
16394 return;
16395 }
16396
16397 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
16398 Definition->getStorageClass() == SC_Extern)
16399 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
16400 << FD << getLangOpts().CPlusPlus;
16401 else
16402 Diag(FD->getLocation(), diag::err_redefinition) << FD;
16403
16404 Diag(Definition->getLocation(), diag::note_previous_definition);
16405 FD->setInvalidDecl();
16406}
16407
16409 CXXRecordDecl *LambdaClass = CallOperator->getParent();
16410
16412 LSI->CallOperator = CallOperator;
16413 LSI->Lambda = LambdaClass;
16414 LSI->ReturnType = CallOperator->getReturnType();
16415 // When this function is called in situation where the context of the call
16416 // operator is not entered, we set AfterParameterList to false, so that
16417 // `tryCaptureVariable` finds explicit captures in the appropriate context.
16418 // There is also at least a situation as in FinishTemplateArgumentDeduction(),
16419 // where we would set the CurContext to the lambda operator before
16420 // substituting into it. In this case the flag needs to be true such that
16421 // tryCaptureVariable can correctly handle potential captures thereof.
16422 LSI->AfterParameterList = CurContext == CallOperator;
16423 LSI->BeforeCompoundStatement = false;
16424
16425 // GLTemplateParameterList is necessary for getCurGenericLambda() which is
16426 // used at the point of dealing with potential captures.
16427 //
16428 // We don't use LambdaClass->isGenericLambda() because this value doesn't
16429 // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
16430 // associated. (Technically, we could recover that list from their
16431 // instantiation patterns, but for now, the GLTemplateParameterList seems
16432 // unnecessary in these cases.)
16433 if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
16434 LSI->GLTemplateParameterList = FTD->getTemplateParameters();
16435 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
16436
16437 if (LCD == LCD_None)
16439 else if (LCD == LCD_ByCopy)
16441 else if (LCD == LCD_ByRef)
16443 DeclarationNameInfo DNI = CallOperator->getNameInfo();
16444
16446 LSI->Mutable = !CallOperator->isConst();
16447 if (CallOperator->isExplicitObjectMemberFunction())
16448 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0);
16449
16450 // Add the captures to the LSI so they can be noted as already
16451 // captured within tryCaptureVar.
16452 auto I = LambdaClass->field_begin();
16453 for (const auto &C : LambdaClass->captures()) {
16454 if (C.capturesVariable()) {
16455 ValueDecl *VD = C.getCapturedVar();
16456 if (VD->isInitCapture())
16457 CurrentInstantiationScope->InstantiatedLocal(VD, VD);
16458 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
16459 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
16460 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
16461 /*EllipsisLoc*/C.isPackExpansion()
16462 ? C.getEllipsisLoc() : SourceLocation(),
16463 I->getType(), /*Invalid*/false);
16464
16465 } else if (C.capturesThis()) {
16466 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
16467 C.getCaptureKind() == LCK_StarThis);
16468 } else {
16469 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
16470 I->getType());
16471 }
16472 ++I;
16473 }
16474 return LSI;
16475}
16476
16478 SkipBodyInfo *SkipBody,
16479 FnBodyKind BodyKind) {
16480 if (!D) {
16481 // Parsing the function declaration failed in some way. Push on a fake scope
16482 // anyway so we can try to parse the function body.
16485 return D;
16486 }
16487
16488 FunctionDecl *FD = nullptr;
16489
16490 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
16491 FD = FunTmpl->getTemplatedDecl();
16492 else
16493 FD = cast<FunctionDecl>(D);
16494
16495 // Do not push if it is a lambda because one is already pushed when building
16496 // the lambda in ActOnStartOfLambdaDefinition().
16497 if (!isLambdaCallOperator(FD))
16499 FD);
16500
16501 // Check for defining attributes before the check for redefinition.
16502 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
16503 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
16504 FD->dropAttr<AliasAttr>();
16505 FD->setInvalidDecl();
16506 }
16507 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
16508 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
16509 FD->dropAttr<IFuncAttr>();
16510 FD->setInvalidDecl();
16511 }
16512 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
16513 if (Context.getTargetInfo().getTriple().isAArch64() &&
16514 !Context.getTargetInfo().hasFeature("fmv") &&
16515 !Attr->isDefaultVersion()) {
16516 // If function multi versioning disabled skip parsing function body
16517 // defined with non-default target_version attribute
16518 if (SkipBody)
16519 SkipBody->ShouldSkip = true;
16520 return nullptr;
16521 }
16522 }
16523
16524 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
16525 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
16526 Ctor->isDefaultConstructor() &&
16527 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16528 // If this is an MS ABI dllexport default constructor, instantiate any
16529 // default arguments.
16530 if (DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>())
16532 }
16533 }
16534
16535 // See if this is a redefinition. If 'will have body' (or similar) is already
16536 // set, then these checks were already performed when it was set.
16537 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
16539 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
16540
16541 // If we're skipping the body, we're done. Don't enter the scope.
16542 if (SkipBody && SkipBody->ShouldSkip)
16543 return D;
16544 }
16545
16546 // Mark this function as "will have a body eventually". This lets users to
16547 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
16548 // this function.
16549 FD->setWillHaveBody();
16550
16551 // If we are instantiating a generic lambda call operator, push
16552 // a LambdaScopeInfo onto the function stack. But use the information
16553 // that's already been calculated (ActOnLambdaExpr) to prime the current
16554 // LambdaScopeInfo.
16555 // When the template operator is being specialized, the LambdaScopeInfo,
16556 // has to be properly restored so that tryCaptureVariable doesn't try
16557 // and capture any new variables. In addition when calculating potential
16558 // captures during transformation of nested lambdas, it is necessary to
16559 // have the LSI properly restored.
16561 // C++2c 7.5.5.2p17 A member of a closure type shall not be explicitly
16562 // specialized.
16564 Diag(FD->getLocation(), diag::err_lambda_explicit_temp_spec)
16565 << /*specialization*/ 0;
16567 Diag(RD->getLocation(), diag::note_defined_here) << RD;
16568
16569 FD->setInvalidDecl();
16571 } else {
16572 assert(inTemplateInstantiation() &&
16573 "There should be an active template instantiation on the stack "
16574 "when instantiating a generic lambda!");
16576 }
16577 } else {
16578 // Enter a new function scope
16580 }
16581
16582 // Builtin functions cannot be defined.
16583 if (unsigned BuiltinID = FD->getBuiltinID()) {
16584 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
16585 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
16586 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
16587 FD->setInvalidDecl();
16588 }
16589 }
16590
16591 // The return type of a function definition must be complete (C99 6.9.1p3).
16592 // C++23 [dcl.fct.def.general]/p2
16593 // The type of [...] the return for a function definition
16594 // shall not be a (possibly cv-qualified) class type that is incomplete
16595 // or abstract within the function body unless the function is deleted.
16596 QualType ResultType = FD->getReturnType();
16597 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
16598 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
16599 (RequireCompleteType(FD->getLocation(), ResultType,
16600 diag::err_func_def_incomplete_result) ||
16602 diag::err_abstract_type_in_decl,
16604 FD->setInvalidDecl();
16605
16606 if (FnBodyScope)
16607 PushDeclContext(FnBodyScope, FD);
16608
16609 // Check the validity of our function parameters
16610 if (BodyKind != FnBodyKind::Delete)
16612 /*CheckParameterNames=*/true);
16613
16614 // Add non-parameter declarations already in the function to the current
16615 // scope.
16616 if (FnBodyScope) {
16617 for (Decl *NPD : FD->decls()) {
16618 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
16619 if (!NonParmDecl)
16620 continue;
16621 assert(!isa<ParmVarDecl>(NonParmDecl) &&
16622 "parameters should not be in newly created FD yet");
16623
16624 // If the decl has a name, make it accessible in the current scope.
16625 if (NonParmDecl->getDeclName())
16626 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
16627
16628 // Similarly, dive into enums and fish their constants out, making them
16629 // accessible in this scope.
16630 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
16631 for (auto *EI : ED->enumerators())
16632 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
16633 }
16634 }
16635 }
16636
16637 // Introduce our parameters into the function scope
16638 for (auto *Param : FD->parameters()) {
16639 Param->setOwningFunction(FD);
16640
16641 // If this has an identifier, add it to the scope stack.
16642 if (Param->getIdentifier() && FnBodyScope) {
16643 CheckShadow(FnBodyScope, Param);
16644
16645 PushOnScopeChains(Param, FnBodyScope);
16646 }
16647 }
16648
16649 // C++ [module.import/6]
16650 // ...
16651 // A header unit shall not contain a definition of a non-inline function or
16652 // variable whose name has external linkage.
16653 //
16654 // Deleted and Defaulted functions are implicitly inline (but the
16655 // inline state is not set at this point, so check the BodyKind explicitly).
16656 // We choose to allow weak & selectany definitions, as they are common in
16657 // headers, and have semantics similar to inline definitions which are allowed
16658 // in header units.
16659 // FIXME: Consider an alternate location for the test where the inlined()
16660 // state is complete.
16661 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
16662 !FD->isInvalidDecl() && !FD->isInlined() &&
16663 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
16664 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() &&
16665 !FD->isTemplateInstantiation() &&
16666 !(FD->hasAttr<SelectAnyAttr>() || FD->hasAttr<WeakAttr>())) {
16667 assert(FD->isThisDeclarationADefinition());
16668 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
16669 FD->setInvalidDecl();
16670 }
16671
16672 // Ensure that the function's exception specification is instantiated.
16673 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
16675
16676 // dllimport cannot be applied to non-inline function definitions.
16677 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
16678 !FD->isTemplateInstantiation()) {
16679 assert(!FD->hasAttr<DLLExportAttr>());
16680 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
16681 FD->setInvalidDecl();
16682 return D;
16683 }
16684
16685 // Some function attributes (like OptimizeNoneAttr) need actions before
16686 // parsing body started.
16688
16689 // We want to attach documentation to original Decl (which might be
16690 // a function template).
16692 if (getCurLexicalContext()->isObjCContainer() &&
16693 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
16694 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
16695 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
16696
16698
16699 if (!FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>() &&
16700 FnBodyScope) {
16701 // An implicit call expression is synthesized for functions declared with
16702 // the sycl_kernel_entry_point attribute. The call may resolve to a
16703 // function template, a member function template, or a call operator
16704 // of a variable template depending on the results of unqualified lookup
16705 // for 'sycl_kernel_launch' from the beginning of the function body.
16706 // Performing that lookup requires the stack of parsing scopes active
16707 // when the definition is parsed and is thus done here; the result is
16708 // cached in FunctionScopeInfo and used to synthesize the (possibly
16709 // unresolved) call expression after the function body has been parsed.
16710 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
16711 if (!SKEPAttr->isInvalidAttr()) {
16712 ExprResult LaunchIdExpr =
16713 SYCL().BuildSYCLKernelLaunchIdExpr(FD, SKEPAttr->getKernelName());
16714 // Do not mark 'FD' as invalid if construction of `LaunchIDExpr` produces
16715 // an invalid result. Name lookup failure for 'sycl_kernel_launch' is
16716 // treated as an error in the definition of 'FD'; treating it as an error
16717 // of the declaration would affect overload resolution which would
16718 // potentially result in additional errors. If construction of
16719 // 'LaunchIDExpr' failed, then 'SYCLKernelLaunchIdExpr' will be assigned
16720 // a null pointer value below; that is expected.
16721 getCurFunction()->SYCLKernelLaunchIdExpr = LaunchIdExpr.get();
16722 }
16723 }
16724
16725 return D;
16726}
16727
16729 if (!FD || FD->isInvalidDecl())
16730 return;
16731 if (auto *TD = dyn_cast<FunctionTemplateDecl>(FD))
16732 FD = TD->getTemplatedDecl();
16733 if (FD && FD->hasAttr<OptimizeNoneAttr>()) {
16736 CurFPFeatures.applyChanges(FPO);
16737 FpPragmaStack.CurrentValue =
16738 CurFPFeatures.getChangesFrom(FPOptions(LangOpts));
16739 }
16740}
16741
16743 ReturnStmt **Returns = Scope->Returns.data();
16744
16745 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
16746 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
16747 if (!NRVOCandidate->isNRVOVariable()) {
16748 Diag(Returns[I]->getRetValue()->getExprLoc(),
16749 diag::warn_not_eliding_copy_on_return);
16750 Returns[I]->setNRVOCandidate(nullptr);
16751 }
16752 }
16753 }
16754}
16755
16757 // We can't delay parsing the body of a constexpr function template (yet).
16759 return false;
16760
16761 // We can't delay parsing the body of a function template with a deduced
16762 // return type (yet).
16763 if (D.getDeclSpec().hasAutoTypeSpec()) {
16764 // If the placeholder introduces a non-deduced trailing return type,
16765 // we can still delay parsing it.
16766 if (D.getNumTypeObjects()) {
16767 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
16768 if (Outer.Kind == DeclaratorChunk::Function &&
16769 Outer.Fun.hasTrailingReturnType()) {
16770 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
16771 return Ty.isNull() || !Ty->isUndeducedType();
16772 }
16773 }
16774 return false;
16775 }
16776
16777 return true;
16778}
16779
16781 // We cannot skip the body of a function (or function template) which is
16782 // constexpr, since we may need to evaluate its body in order to parse the
16783 // rest of the file.
16784 // We cannot skip the body of a function with an undeduced return type,
16785 // because any callers of that function need to know the type.
16786 if (const FunctionDecl *FD = D->getAsFunction()) {
16787 if (FD->isConstexpr())
16788 return false;
16789 // We can't simply call Type::isUndeducedType here, because inside template
16790 // auto can be deduced to a dependent type, which is not considered
16791 // "undeduced".
16792 if (FD->getReturnType()->getContainedDeducedType())
16793 return false;
16794 }
16795 return Consumer.shouldSkipFunctionBody(D);
16796}
16797
16799 if (!Decl)
16800 return nullptr;
16801 if (FunctionDecl *FD = Decl->getAsFunction())
16802 FD->setHasSkippedBody();
16803 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
16804 MD->setHasSkippedBody();
16805 return Decl;
16806}
16807
16808/// RAII object that pops an ExpressionEvaluationContext when exiting a function
16809/// body.
16811public:
16812 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
16814 if (!IsLambda)
16815 S.PopExpressionEvaluationContext();
16816 }
16817
16818private:
16819 Sema &S;
16820 bool IsLambda = false;
16821};
16822
16824 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
16825
16826 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
16827 auto [It, Inserted] = EscapeInfo.try_emplace(BD);
16828 if (!Inserted)
16829 return It->second;
16830
16831 bool R = false;
16832 const BlockDecl *CurBD = BD;
16833
16834 do {
16835 R = !CurBD->doesNotEscape();
16836 if (R)
16837 break;
16838 CurBD = CurBD->getParent()->getInnermostBlockDecl();
16839 } while (CurBD);
16840
16841 return It->second = R;
16842 };
16843
16844 // If the location where 'self' is implicitly retained is inside a escaping
16845 // block, emit a diagnostic.
16846 for (const std::pair<SourceLocation, const BlockDecl *> &P :
16848 if (IsOrNestedInEscapingBlock(P.second))
16849 S.Diag(P.first, diag::warn_implicitly_retains_self)
16850 << FixItHint::CreateInsertion(P.first, "self->");
16851}
16852
16853static bool methodHasName(const FunctionDecl *FD, StringRef Name) {
16854 return isa<CXXMethodDecl>(FD) && FD->param_empty() &&
16855 FD->getDeclName().isIdentifier() && FD->getName() == Name;
16856}
16857
16859 return methodHasName(FD, "get_return_object");
16860}
16861
16863 return FD->isStatic() &&
16864 methodHasName(FD, "get_return_object_on_allocation_failure");
16865}
16866
16869 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>())
16870 return;
16871 // Allow some_promise_type::get_return_object().
16873 return;
16874 if (!FD->hasAttr<CoroWrapperAttr>())
16875 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD;
16876}
16877
16878Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, bool IsInstantiation,
16879 bool RetainFunctionScopeInfo) {
16881 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
16882
16883 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
16884 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
16885
16886 SourceLocation AnalysisLoc;
16887 if (Body)
16888 AnalysisLoc = Body->getEndLoc();
16889 else if (FD)
16890 AnalysisLoc = FD->getEndLoc();
16892 AnalysisWarnings.getPolicyInEffectAt(AnalysisLoc);
16893 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
16894
16895 // If we skip function body, we can't tell if a function is a coroutine.
16896 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) {
16897 if (FSI->isCoroutine())
16899 else
16901 }
16902
16903 // Diagnose invalid SYCL kernel entry point function declarations
16904 // and build SYCLKernelCallStmts for valid ones.
16905 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLKernelEntryPointAttr>()) {
16906 SYCLKernelEntryPointAttr *SKEPAttr =
16907 FD->getAttr<SYCLKernelEntryPointAttr>();
16908 if (FD->isDefaulted()) {
16909 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16910 << SKEPAttr << diag::InvalidSKEPReason::DefaultedFn;
16911 SKEPAttr->setInvalidAttr();
16912 } else if (FD->isDeleted()) {
16913 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16914 << SKEPAttr << diag::InvalidSKEPReason::DeletedFn;
16915 SKEPAttr->setInvalidAttr();
16916 } else if (FSI->isCoroutine()) {
16917 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16918 << SKEPAttr << diag::InvalidSKEPReason::Coroutine;
16919 SKEPAttr->setInvalidAttr();
16920 } else if (Body && isa<CXXTryStmt>(Body)) {
16921 Diag(SKEPAttr->getLocation(), diag::err_sycl_entry_point_invalid)
16922 << SKEPAttr << diag::InvalidSKEPReason::FunctionTryBlock;
16923 SKEPAttr->setInvalidAttr();
16924 }
16925
16926 // Build an unresolved SYCL kernel call statement for a function template,
16927 // validate that a SYCL kernel call statement was instantiated for an
16928 // (implicit or explicit) instantiation of a function template, or otherwise
16929 // build a (resolved) SYCL kernel call statement for a non-templated
16930 // function or an explicit specialization.
16931 if (Body && !SKEPAttr->isInvalidAttr()) {
16932 StmtResult SR;
16933 if (FD->isTemplateInstantiation()) {
16934 // The function body should already be a SYCLKernelCallStmt in this
16935 // case, but might not be if there were previous errors.
16936 SR = Body;
16937 } else if (!getCurFunction()->SYCLKernelLaunchIdExpr) {
16938 // If name lookup for a template named sycl_kernel_launch failed
16939 // earlier, don't try to build a SYCL kernel call statement as that
16940 // would cause additional errors to be issued; just proceed with the
16941 // original function body.
16942 SR = Body;
16943 } else if (FD->isTemplated()) {
16945 cast<CompoundStmt>(Body), getCurFunction()->SYCLKernelLaunchIdExpr);
16946 } else {
16948 FD, cast<CompoundStmt>(Body),
16949 getCurFunction()->SYCLKernelLaunchIdExpr);
16950 }
16951 // If construction of the replacement body fails, just continue with the
16952 // original function body. An early error return here is not valid; the
16953 // current declaration context and function scopes must be popped before
16954 // returning.
16955 if (SR.isUsable())
16956 Body = SR.get();
16957 }
16958 }
16959
16960 if (FD && !FD->isInvalidDecl() && FD->hasAttr<SYCLExternalAttr>()) {
16961 SYCLExternalAttr *SEAttr = FD->getAttr<SYCLExternalAttr>();
16962 if (FD->isDeletedAsWritten())
16963 Diag(SEAttr->getLocation(),
16964 diag::err_sycl_external_invalid_deleted_function)
16965 << SEAttr;
16966 }
16967
16968 {
16969 // Do not call PopExpressionEvaluationContext() if it is a lambda because
16970 // one is already popped when finishing the lambda in BuildLambdaExpr().
16971 // This is meant to pop the context added in ActOnStartOfFunctionDef().
16972 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
16973 if (FD) {
16974 // The function body and the DefaultedOrDeletedInfo, if present, use
16975 // the same storage; don't overwrite the latter if the former is null
16976 // (the body is initialised to null anyway, so even if the latter isn't
16977 // present, this would still be a no-op).
16978 if (Body)
16979 FD->setBody(Body);
16980 FD->setWillHaveBody(false);
16981
16982 if (getLangOpts().CPlusPlus14) {
16983 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
16984 FD->getReturnType()->isUndeducedType()) {
16985 // For a function with a deduced result type to return void,
16986 // the result type as written must be 'auto' or 'decltype(auto)',
16987 // possibly cv-qualified or constrained, but not ref-qualified.
16988 if (!FD->getReturnType()->getAs<AutoType>()) {
16989 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
16990 << FD->getReturnType();
16991 FD->setInvalidDecl();
16992 } else {
16993 // Falling off the end of the function is the same as 'return;'.
16994 Expr *Dummy = nullptr;
16996 FD, dcl->getLocation(), Dummy,
16997 FD->getReturnType()->getAs<AutoType>()))
16998 FD->setInvalidDecl();
16999 }
17000 }
17001 } else if (getLangOpts().CPlusPlus && isLambdaCallOperator(FD)) {
17002 // In C++11, we don't use 'auto' deduction rules for lambda call
17003 // operators because we don't support return type deduction.
17004 auto *LSI = getCurLambda();
17005 if (LSI->HasImplicitReturnType) {
17007
17008 // C++11 [expr.prim.lambda]p4:
17009 // [...] if there are no return statements in the compound-statement
17010 // [the deduced type is] the type void
17011 QualType RetType =
17012 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
17013
17014 // Update the return type to the deduced type.
17015 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
17016 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
17017 Proto->getExtProtoInfo()));
17018 }
17019 }
17020
17021 // If the function implicitly returns zero (like 'main') or is naked,
17022 // don't complain about missing return statements.
17023 // Clang implicitly returns 0 in C89 mode, but that's considered an
17024 // extension. The check is necessary to ensure the expected extension
17025 // warning is emitted in C89 mode.
17026 if ((FD->hasImplicitReturnZero() &&
17027 (getLangOpts().CPlusPlus || getLangOpts().C99 || !FD->isMain())) ||
17028 FD->hasAttr<NakedAttr>())
17030
17031 // MSVC permits the use of pure specifier (=0) on function definition,
17032 // defined at class scope, warn about this non-standard construct.
17033 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() &&
17034 !FD->isOutOfLine())
17035 Diag(FD->getLocation(), diag::ext_pure_function_definition);
17036
17037 if (!FD->isInvalidDecl()) {
17038 // Don't diagnose unused parameters of defaulted, deleted or naked
17039 // functions.
17040 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
17041 !FD->hasAttr<NakedAttr>())
17044 FD->getReturnType(), FD);
17045
17046 // If this is a structor, we need a vtable.
17047 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
17048 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
17049 else if (CXXDestructorDecl *Destructor =
17050 dyn_cast<CXXDestructorDecl>(FD))
17051 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
17052
17053 // Try to apply the named return value optimization. We have to check
17054 // if we can do this here because lambdas keep return statements around
17055 // to deduce an implicit return type.
17056 if (FD->getReturnType()->isRecordType() &&
17058 computeNRVO(Body, FSI);
17059 }
17060
17061 // GNU warning -Wmissing-prototypes:
17062 // Warn if a global function is defined without a previous
17063 // prototype declaration. This warning is issued even if the
17064 // definition itself provides a prototype. The aim is to detect
17065 // global functions that fail to be declared in header files.
17066 const FunctionDecl *PossiblePrototype = nullptr;
17067 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
17068 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
17069
17070 if (PossiblePrototype) {
17071 // We found a declaration that is not a prototype,
17072 // but that could be a zero-parameter prototype
17073 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
17074 TypeLoc TL = TI->getTypeLoc();
17076 Diag(PossiblePrototype->getLocation(),
17077 diag::note_declaration_not_a_prototype)
17078 << (FD->getNumParams() != 0)
17080 FTL.getRParenLoc(), "void")
17081 : FixItHint{});
17082 }
17083 } else {
17084 // Returns true if the token beginning at this Loc is `const`.
17085 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
17086 const LangOptions &LangOpts) {
17087 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
17088 if (LocInfo.first.isInvalid())
17089 return false;
17090
17091 bool Invalid = false;
17092 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
17093 if (Invalid)
17094 return false;
17095
17096 if (LocInfo.second > Buffer.size())
17097 return false;
17098
17099 const char *LexStart = Buffer.data() + LocInfo.second;
17100 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
17101
17102 return StartTok.consume_front("const") &&
17103 (StartTok.empty() || isWhitespace(StartTok[0]) ||
17104 StartTok.starts_with("/*") || StartTok.starts_with("//"));
17105 };
17106
17107 auto findBeginLoc = [&]() {
17108 // If the return type has `const` qualifier, we want to insert
17109 // `static` before `const` (and not before the typename).
17110 if ((FD->getReturnType()->isAnyPointerType() &&
17113 // But only do this if we can determine where the `const` is.
17114
17115 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
17116 getLangOpts()))
17117
17118 return FD->getBeginLoc();
17119 }
17120 return FD->getTypeSpecStartLoc();
17121 };
17123 diag::note_static_for_internal_linkage)
17124 << /* function */ 1
17125 << (FD->getStorageClass() == SC_None
17126 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
17127 : FixItHint{});
17128 }
17129 }
17130
17131 // We might not have found a prototype because we didn't wish to warn on
17132 // the lack of a missing prototype. Try again without the checks for
17133 // whether we want to warn on the missing prototype.
17134 if (!PossiblePrototype)
17135 (void)FindPossiblePrototype(FD, PossiblePrototype);
17136
17137 // If the function being defined does not have a prototype, then we may
17138 // need to diagnose it as changing behavior in C23 because we now know
17139 // whether the function accepts arguments or not. This only handles the
17140 // case where the definition has no prototype but does have parameters
17141 // and either there is no previous potential prototype, or the previous
17142 // potential prototype also has no actual prototype. This handles cases
17143 // like:
17144 // void f(); void f(a) int a; {}
17145 // void g(a) int a; {}
17146 // See MergeFunctionDecl() for other cases of the behavior change
17147 // diagnostic. See GetFullTypeForDeclarator() for handling of a function
17148 // type without a prototype.
17149 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
17150 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
17151 !PossiblePrototype->isImplicit()))) {
17152 // The function definition has parameters, so this will change behavior
17153 // in C23. If there is a possible prototype, it comes before the
17154 // function definition.
17155 // FIXME: The declaration may have already been diagnosed as being
17156 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
17157 // there's no way to test for the "changes behavior" condition in
17158 // SemaType.cpp when forming the declaration's function type. So, we do
17159 // this awkward dance instead.
17160 //
17161 // If we have a possible prototype and it declares a function with a
17162 // prototype, we don't want to diagnose it; if we have a possible
17163 // prototype and it has no prototype, it may have already been
17164 // diagnosed in SemaType.cpp as deprecated depending on whether
17165 // -Wstrict-prototypes is enabled. If we already warned about it being
17166 // deprecated, add a note that it also changes behavior. If we didn't
17167 // warn about it being deprecated (because the diagnostic is not
17168 // enabled), warn now that it is deprecated and changes behavior.
17169
17170 // This K&R C function definition definitely changes behavior in C23,
17171 // so diagnose it.
17172 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
17173 << /*definition*/ 1 << /* not supported in C23 */ 0;
17174
17175 // If we have a possible prototype for the function which is a user-
17176 // visible declaration, we already tested that it has no prototype.
17177 // This will change behavior in C23. This gets a warning rather than a
17178 // note because it's the same behavior-changing problem as with the
17179 // definition.
17180 if (PossiblePrototype)
17181 Diag(PossiblePrototype->getLocation(),
17182 diag::warn_non_prototype_changes_behavior)
17183 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
17184 << /*definition*/ 1;
17185 }
17186
17187 // Warn on CPUDispatch with an actual body.
17188 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
17189 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
17190 if (!CmpndBody->body_empty())
17191 Diag(CmpndBody->body_front()->getBeginLoc(),
17192 diag::warn_dispatch_body_ignored);
17193
17194 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
17195 const CXXMethodDecl *KeyFunction;
17196 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
17197 MD->isVirtual() &&
17198 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
17199 MD == KeyFunction->getCanonicalDecl()) {
17200 // Update the key-function state if necessary for this ABI.
17201 if (FD->isInlined() &&
17202 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
17203 Context.setNonKeyFunction(MD);
17204
17205 // If the newly-chosen key function is already defined, then we
17206 // need to mark the vtable as used retroactively.
17207 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
17208 const FunctionDecl *Definition;
17209 if (KeyFunction && KeyFunction->isDefined(Definition))
17210 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
17211 } else {
17212 // We just defined they key function; mark the vtable as used.
17213 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
17214 }
17215 }
17216 }
17217
17218 assert((FD == getCurFunctionDecl(/*AllowLambdas=*/true)) &&
17219 "Function parsing confused");
17220 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
17221 assert(MD == getCurMethodDecl() && "Method parsing confused");
17222 MD->setBody(Body);
17223 if (!MD->isInvalidDecl()) {
17225 MD->getReturnType(), MD);
17226
17227 if (Body)
17228 computeNRVO(Body, FSI);
17229 }
17230 if (FSI->ObjCShouldCallSuper) {
17231 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
17232 << MD->getSelector().getAsString();
17233 FSI->ObjCShouldCallSuper = false;
17234 }
17236 const ObjCMethodDecl *InitMethod = nullptr;
17237 bool isDesignated =
17238 MD->isDesignatedInitializerForTheInterface(&InitMethod);
17239 assert(isDesignated && InitMethod);
17240 (void)isDesignated;
17241
17242 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
17243 auto IFace = MD->getClassInterface();
17244 if (!IFace)
17245 return false;
17246 auto SuperD = IFace->getSuperClass();
17247 if (!SuperD)
17248 return false;
17249 return SuperD->getIdentifier() ==
17250 ObjC().NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
17251 };
17252 // Don't issue this warning for unavailable inits or direct subclasses
17253 // of NSObject.
17254 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
17255 Diag(MD->getLocation(),
17256 diag::warn_objc_designated_init_missing_super_call);
17257 Diag(InitMethod->getLocation(),
17258 diag::note_objc_designated_init_marked_here);
17259 }
17261 }
17262 if (FSI->ObjCWarnForNoInitDelegation) {
17263 // Don't issue this warning for unavailable inits.
17264 if (!MD->isUnavailable())
17265 Diag(MD->getLocation(),
17266 diag::warn_objc_secondary_init_missing_init_call);
17267 FSI->ObjCWarnForNoInitDelegation = false;
17268 }
17269
17271 } else {
17272 // Parsing the function declaration failed in some way. Pop the fake scope
17273 // we pushed on.
17274 PopFunctionScopeInfo(ActivePolicy, dcl);
17275 return nullptr;
17276 }
17277
17278 if (Body) {
17281 else if (AMDGPU().HasPotentiallyUnguardedBuiltinUsage(FD))
17283 }
17284
17285 assert(!FSI->ObjCShouldCallSuper &&
17286 "This should only be set for ObjC methods, which should have been "
17287 "handled in the block above.");
17288
17289 // Verify and clean out per-function state.
17290 if (Body && (!FD || !FD->isDefaulted())) {
17291 // C++ constructors that have function-try-blocks can't have return
17292 // statements in the handlers of that block. (C++ [except.handle]p14)
17293 // Verify this.
17294 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
17296
17297 // Verify that gotos and switch cases don't jump into scopes illegally.
17298 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
17300
17301 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
17302 if (!Destructor->getParent()->isDependentType())
17304
17306 Destructor->getParent());
17307 }
17308
17309 // If any errors have occurred, clear out any temporaries that may have
17310 // been leftover. This ensures that these temporaries won't be picked up
17311 // for deletion in some later function.
17314 getDiagnostics().getSuppressAllDiagnostics()) {
17316 }
17318 // Since the body is valid, issue any analysis-based warnings that are
17319 // enabled.
17320 ActivePolicy = &WP;
17321 }
17322
17323 if (!IsInstantiation && FD &&
17324 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) &&
17325 !FD->isInvalidDecl() &&
17327 FD->setInvalidDecl();
17328
17329 if (FD && FD->hasAttr<NakedAttr>()) {
17330 for (const Stmt *S : Body->children()) {
17331 // Allow local register variables without initializer as they don't
17332 // require prologue.
17333 bool RegisterVariables = false;
17334 if (auto *DS = dyn_cast<DeclStmt>(S)) {
17335 for (const auto *Decl : DS->decls()) {
17336 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
17337 RegisterVariables =
17338 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
17339 if (!RegisterVariables)
17340 break;
17341 }
17342 }
17343 }
17344 if (RegisterVariables)
17345 continue;
17346 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
17347 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
17348 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
17349 FD->setInvalidDecl();
17350 break;
17351 }
17352 }
17353 }
17354
17355 assert(ExprCleanupObjects.size() ==
17356 ExprEvalContexts.back().NumCleanupObjects &&
17357 "Leftover temporaries in function");
17358 assert(!Cleanup.exprNeedsCleanups() &&
17359 "Unaccounted cleanups in function");
17360 assert(MaybeODRUseExprs.empty() &&
17361 "Leftover expressions for odr-use checking");
17362 }
17363 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
17364 // the declaration context below. Otherwise, we're unable to transform
17365 // 'this' expressions when transforming immediate context functions.
17366
17367 if (FD)
17369
17370 if (!IsInstantiation)
17372
17373 if (!RetainFunctionScopeInfo)
17374 PopFunctionScopeInfo(ActivePolicy, dcl);
17375 // If any errors have occurred, clear out any temporaries that may have
17376 // been leftover. This ensures that these temporaries won't be picked up for
17377 // deletion in some later function.
17380 }
17381
17382 if (FD && (LangOpts.isTargetDevice() || LangOpts.CUDA ||
17383 (LangOpts.OpenMP && !LangOpts.OMPTargetTriples.empty()))) {
17384 auto ES = getEmissionStatus(FD);
17388 }
17389
17390 if (FD && !FD->isDeleted())
17391 checkTypeSupport(FD->getType(), FD->getLocation(), FD);
17392
17393 return dcl;
17394}
17395
17396/// When we finish delayed parsing of an attribute, we must attach it to the
17397/// relevant Decl.
17399 ParsedAttributes &Attrs) {
17400 // Always attach attributes to the underlying decl.
17401 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
17402 D = TD->getTemplatedDecl();
17403 ProcessDeclAttributeList(S, D, Attrs);
17404 ProcessAPINotes(D);
17405
17406 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
17407 if (Method->isStatic())
17409}
17410
17412 IdentifierInfo &II, Scope *S) {
17413 // It is not valid to implicitly define a function in C23.
17414 assert(LangOpts.implicitFunctionsAllowed() &&
17415 "Implicit function declarations aren't allowed in this language mode");
17416
17417 // Find the scope in which the identifier is injected and the corresponding
17418 // DeclContext.
17419 // FIXME: C89 does not say what happens if there is no enclosing block scope.
17420 // In that case, we inject the declaration into the translation unit scope
17421 // instead.
17422 Scope *BlockScope = S;
17423 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
17424 BlockScope = BlockScope->getParent();
17425
17426 // Loop until we find a DeclContext that is either a function/method or the
17427 // translation unit, which are the only two valid places to implicitly define
17428 // a function. This avoids accidentally defining the function within a tag
17429 // declaration, for example.
17430 Scope *ContextScope = BlockScope;
17431 while (!ContextScope->getEntity() ||
17432 (!ContextScope->getEntity()->isFunctionOrMethod() &&
17433 !ContextScope->getEntity()->isTranslationUnit()))
17434 ContextScope = ContextScope->getParent();
17435 ContextRAII SavedContext(*this, ContextScope->getEntity());
17436
17437 // Before we produce a declaration for an implicitly defined
17438 // function, see whether there was a locally-scoped declaration of
17439 // this name as a function or variable. If so, use that
17440 // (non-visible) declaration, and complain about it.
17441 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
17442 if (ExternCPrev) {
17443 // We still need to inject the function into the enclosing block scope so
17444 // that later (non-call) uses can see it.
17445 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
17446
17447 // C89 footnote 38:
17448 // If in fact it is not defined as having type "function returning int",
17449 // the behavior is undefined.
17450 if (!isa<FunctionDecl>(ExternCPrev) ||
17451 !Context.typesAreCompatible(
17452 cast<FunctionDecl>(ExternCPrev)->getType(),
17453 Context.getFunctionNoProtoType(Context.IntTy))) {
17454 Diag(Loc, diag::ext_use_out_of_scope_declaration)
17455 << ExternCPrev << !getLangOpts().C99;
17456 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
17457 return ExternCPrev;
17458 }
17459 }
17460
17461 // Extension in C99 (defaults to error). Legal in C89, but warn about it.
17462 unsigned diag_id;
17463 if (II.getName().starts_with("__builtin_"))
17464 diag_id = diag::warn_builtin_unknown;
17465 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
17466 else if (getLangOpts().C99)
17467 diag_id = diag::ext_implicit_function_decl_c99;
17468 else
17469 diag_id = diag::warn_implicit_function_decl;
17470
17471 TypoCorrection Corrected;
17472 // Because typo correction is expensive, only do it if the implicit
17473 // function declaration is going to be treated as an error.
17474 //
17475 // Perform the correction before issuing the main diagnostic, as some
17476 // consumers use typo-correction callbacks to enhance the main diagnostic.
17477 if (S && !ExternCPrev &&
17478 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
17480 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
17481 S, nullptr, CCC, CorrectTypoKind::NonError);
17482 }
17483
17484 Diag(Loc, diag_id) << &II;
17485 if (Corrected) {
17486 // If the correction is going to suggest an implicitly defined function,
17487 // skip the correction as not being a particularly good idea.
17488 bool Diagnose = true;
17489 if (const auto *D = Corrected.getCorrectionDecl())
17490 Diagnose = !D->isImplicit();
17491 if (Diagnose)
17492 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
17493 /*ErrorRecovery*/ false);
17494 }
17495
17496 // If we found a prior declaration of this function, don't bother building
17497 // another one. We've already pushed that one into scope, so there's nothing
17498 // more to do.
17499 if (ExternCPrev)
17500 return ExternCPrev;
17501
17502 // Set a Declarator for the implicit definition: int foo();
17503 const char *Dummy;
17504 AttributeFactory attrFactory;
17505 DeclSpec DS(attrFactory);
17506 unsigned DiagID;
17507 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
17508 Context.getPrintingPolicy());
17509 (void)Error; // Silence warning.
17510 assert(!Error && "Error setting up implicit decl!");
17511 SourceLocation NoLoc;
17513 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
17514 /*IsAmbiguous=*/false,
17515 /*LParenLoc=*/NoLoc,
17516 /*Params=*/nullptr,
17517 /*NumParams=*/0,
17518 /*EllipsisLoc=*/NoLoc,
17519 /*RParenLoc=*/NoLoc,
17520 /*RefQualifierIsLvalueRef=*/true,
17521 /*RefQualifierLoc=*/NoLoc,
17522 /*MutableLoc=*/NoLoc, EST_None,
17523 /*ESpecRange=*/SourceRange(),
17524 /*Exceptions=*/nullptr,
17525 /*ExceptionRanges=*/nullptr,
17526 /*NumExceptions=*/0,
17527 /*NoexceptExpr=*/nullptr,
17528 /*ExceptionSpecTokens=*/nullptr,
17529 /*DeclsInPrototype=*/{}, Loc, Loc,
17530 D),
17531 std::move(DS.getAttributes()), SourceLocation());
17532 D.SetIdentifier(&II, Loc);
17533
17534 // Insert this function into the enclosing block scope.
17535 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
17536 FD->setImplicit();
17537
17539
17540 return FD;
17541}
17542
17544 FunctionDecl *FD) {
17545 if (FD->isInvalidDecl())
17546 return;
17547
17548 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
17549 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
17550 return;
17551
17552 UnsignedOrNone AlignmentParam = std::nullopt;
17553 bool IsNothrow = false;
17554 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
17555 return;
17556
17557 // C++2a [basic.stc.dynamic.allocation]p4:
17558 // An allocation function that has a non-throwing exception specification
17559 // indicates failure by returning a null pointer value. Any other allocation
17560 // function never returns a null pointer value and indicates failure only by
17561 // throwing an exception [...]
17562 //
17563 // However, -fcheck-new invalidates this possible assumption, so don't add
17564 // NonNull when that is enabled.
17565 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() &&
17566 !getLangOpts().CheckNew)
17567 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
17568
17569 // C++2a [basic.stc.dynamic.allocation]p2:
17570 // An allocation function attempts to allocate the requested amount of
17571 // storage. [...] If the request succeeds, the value returned by a
17572 // replaceable allocation function is a [...] pointer value p0 different
17573 // from any previously returned value p1 [...]
17574 //
17575 // However, this particular information is being added in codegen,
17576 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
17577
17578 // C++2a [basic.stc.dynamic.allocation]p2:
17579 // An allocation function attempts to allocate the requested amount of
17580 // storage. If it is successful, it returns the address of the start of a
17581 // block of storage whose length in bytes is at least as large as the
17582 // requested size.
17583 if (!FD->hasAttr<AllocSizeAttr>()) {
17584 FD->addAttr(AllocSizeAttr::CreateImplicit(
17585 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
17586 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
17587 }
17588
17589 // C++2a [basic.stc.dynamic.allocation]p3:
17590 // For an allocation function [...], the pointer returned on a successful
17591 // call shall represent the address of storage that is aligned as follows:
17592 // (3.1) If the allocation function takes an argument of type
17593 // std​::​align_­val_­t, the storage will have the alignment
17594 // specified by the value of this argument.
17595 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
17596 FD->addAttr(AllocAlignAttr::CreateImplicit(
17597 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
17598 }
17599
17600 // FIXME:
17601 // C++2a [basic.stc.dynamic.allocation]p3:
17602 // For an allocation function [...], the pointer returned on a successful
17603 // call shall represent the address of storage that is aligned as follows:
17604 // (3.2) Otherwise, if the allocation function is named operator new[],
17605 // the storage is aligned for any object that does not have
17606 // new-extended alignment ([basic.align]) and is no larger than the
17607 // requested size.
17608 // (3.3) Otherwise, the storage is aligned for any object that does not
17609 // have new-extended alignment and is of the requested size.
17610}
17611
17613 if (FD->isInvalidDecl())
17614 return;
17615
17616 // If this is a built-in function, map its builtin attributes to
17617 // actual attributes.
17618 if (unsigned BuiltinID = FD->getBuiltinID()) {
17619 // Handle printf-formatting attributes.
17620 unsigned FormatIdx;
17621 bool HasVAListArg;
17622 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
17623 if (!FD->hasAttr<FormatAttr>()) {
17624 const char *fmt = "printf";
17625 unsigned int NumParams = FD->getNumParams();
17626 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
17627 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
17628 fmt = "NSString";
17629 FD->addAttr(FormatAttr::CreateImplicit(Context,
17630 &Context.Idents.get(fmt),
17631 FormatIdx+1,
17632 HasVAListArg ? 0 : FormatIdx+2,
17633 FD->getLocation()));
17634 }
17635 }
17636 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
17637 HasVAListArg)) {
17638 if (!FD->hasAttr<FormatAttr>())
17639 FD->addAttr(FormatAttr::CreateImplicit(Context,
17640 &Context.Idents.get("scanf"),
17641 FormatIdx+1,
17642 HasVAListArg ? 0 : FormatIdx+2,
17643 FD->getLocation()));
17644 }
17645
17646 // Handle automatically recognized callbacks.
17647 SmallVector<int, 4> Encoding;
17648 if (!FD->hasAttr<CallbackAttr>() &&
17649 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
17650 FD->addAttr(CallbackAttr::CreateImplicit(
17651 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
17652
17653 // Mark const if we don't care about errno and/or floating point exceptions
17654 // that are the only thing preventing the function from being const. This
17655 // allows IRgen to use LLVM intrinsics for such functions.
17656 bool NoExceptions =
17658 bool ConstWithoutErrnoAndExceptions =
17659 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
17660 bool ConstWithoutExceptions =
17661 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
17662 if (!FD->hasAttr<ConstAttr>() &&
17663 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
17664 (!ConstWithoutErrnoAndExceptions ||
17665 (!getLangOpts().MathErrno && NoExceptions)) &&
17666 (!ConstWithoutExceptions || NoExceptions))
17667 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17668
17669 // We make "fma" on GNU or Windows const because we know it does not set
17670 // errno in those environments even though it could set errno based on the
17671 // C standard.
17672 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
17673 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
17674 !FD->hasAttr<ConstAttr>()) {
17675 switch (BuiltinID) {
17676 case Builtin::BI__builtin_fma:
17677 case Builtin::BI__builtin_fmaf:
17678 case Builtin::BI__builtin_fmal:
17679 case Builtin::BIfma:
17680 case Builtin::BIfmaf:
17681 case Builtin::BIfmal:
17682 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17683 break;
17684 default:
17685 break;
17686 }
17687 }
17688
17689 SmallVector<int, 4> Indxs;
17691 if (Context.BuiltinInfo.isNonNull(BuiltinID, Indxs, OptMode) &&
17692 !FD->hasAttr<NonNullAttr>()) {
17694 for (int I : Indxs) {
17695 ParmVarDecl *PVD = FD->getParamDecl(I);
17696 QualType T = PVD->getType();
17697 T = Context.getAttributedType(attr::TypeNonNull, T, T);
17698 PVD->setType(T);
17699 }
17700 } else if (OptMode == Builtin::Info::NonNullMode::Optimizing) {
17702 for (int I : Indxs)
17703 ParamIndxs.push_back(ParamIdx(I + 1, FD));
17704 FD->addAttr(NonNullAttr::CreateImplicit(Context, ParamIndxs.data(),
17705 ParamIndxs.size()));
17706 }
17707 }
17708 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
17709 !FD->hasAttr<ReturnsTwiceAttr>())
17710 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
17711 FD->getLocation()));
17712 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
17713 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17714 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
17715 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
17716 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
17717 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
17718 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
17719 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
17720 // Add the appropriate attribute, depending on the CUDA compilation mode
17721 // and which target the builtin belongs to. For example, during host
17722 // compilation, aux builtins are __device__, while the rest are __host__.
17723 if (getLangOpts().CUDAIsDevice !=
17724 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
17725 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
17726 else
17727 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
17728 }
17729
17730 // Add known guaranteed alignment for allocation functions.
17731 switch (BuiltinID) {
17732 case Builtin::BImemalign:
17733 case Builtin::BIaligned_alloc:
17734 if (!FD->hasAttr<AllocAlignAttr>())
17735 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
17736 FD->getLocation()));
17737 break;
17738 default:
17739 break;
17740 }
17741
17742 // Add allocsize attribute for allocation functions.
17743 switch (BuiltinID) {
17744 case Builtin::BIcalloc:
17745 FD->addAttr(AllocSizeAttr::CreateImplicit(
17746 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
17747 break;
17748 case Builtin::BImemalign:
17749 case Builtin::BIaligned_alloc:
17750 case Builtin::BIrealloc:
17751 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
17752 ParamIdx(), FD->getLocation()));
17753 break;
17754 case Builtin::BImalloc:
17755 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
17756 ParamIdx(), FD->getLocation()));
17757 break;
17758 default:
17759 break;
17760 }
17761 }
17762
17767
17768 // If C++ exceptions are enabled but we are told extern "C" functions cannot
17769 // throw, add an implicit nothrow attribute to any extern "C" function we come
17770 // across.
17771 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
17772 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
17773 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
17774 if (!FPT || FPT->getExceptionSpecType() == EST_None)
17775 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
17776 }
17777
17778 IdentifierInfo *Name = FD->getIdentifier();
17779 if (!Name)
17780 return;
17783 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
17785 // Okay: this could be a libc/libm/Objective-C function we know
17786 // about.
17787 } else
17788 return;
17789
17790 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
17791 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
17792 // target-specific builtins, perhaps?
17793 if (!FD->hasAttr<FormatAttr>())
17794 FD->addAttr(FormatAttr::CreateImplicit(Context,
17795 &Context.Idents.get("printf"), 2,
17796 Name->isStr("vasprintf") ? 0 : 3,
17797 FD->getLocation()));
17798 }
17799
17800 if (Name->isStr("__CFStringMakeConstantString")) {
17801 // We already have a __builtin___CFStringMakeConstantString,
17802 // but builds that use -fno-constant-cfstrings don't go through that.
17803 if (!FD->hasAttr<FormatArgAttr>())
17804 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
17805 FD->getLocation()));
17806 }
17807}
17808
17810 TypeSourceInfo *TInfo) {
17811 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
17812 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
17813
17814 if (!TInfo) {
17815 assert(D.isInvalidType() && "no declarator info for valid type");
17816 TInfo = Context.getTrivialTypeSourceInfo(T);
17817 }
17818
17819 // Scope manipulation handled by caller.
17820 TypedefDecl *NewTD =
17822 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
17823
17824 // Bail out immediately if we have an invalid declaration.
17825 if (D.isInvalidType()) {
17826 NewTD->setInvalidDecl();
17827 return NewTD;
17828 }
17829
17831 if (CurContext->isFunctionOrMethod())
17832 Diag(NewTD->getLocation(), diag::err_module_private_local)
17833 << 2 << NewTD
17837 else
17838 NewTD->setModulePrivate();
17839 }
17840
17841 // C++ [dcl.typedef]p8:
17842 // If the typedef declaration defines an unnamed class (or
17843 // enum), the first typedef-name declared by the declaration
17844 // to be that class type (or enum type) is used to denote the
17845 // class type (or enum type) for linkage purposes only.
17846 // We need to check whether the type was declared in the declaration.
17847 switch (D.getDeclSpec().getTypeSpecType()) {
17848 case TST_enum:
17849 case TST_struct:
17850 case TST_interface:
17851 case TST_union:
17852 case TST_class: {
17853 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
17854 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
17855 break;
17856 }
17857
17858 default:
17859 break;
17860 }
17861
17862 return NewTD;
17863}
17864
17866 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
17867 QualType T = TI->getType();
17868
17869 if (T->isDependentType())
17870 return false;
17871
17872 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
17873 // integral type; any cv-qualification is ignored.
17874 // C23 6.7.3.3p5: The underlying type of the enumeration is the unqualified,
17875 // non-atomic version of the type specified by the type specifiers in the
17876 // specifier qualifier list.
17877 // Because of how odd C's rule is, we'll let the user know that operations
17878 // involving the enumeration type will be non-atomic.
17879 if (T->isAtomicType())
17880 Diag(UnderlyingLoc, diag::warn_atomic_stripped_in_enum);
17881
17882 Qualifiers Q = T.getQualifiers();
17883 std::optional<unsigned> QualSelect;
17884 if (Q.hasConst() && Q.hasVolatile())
17885 QualSelect = diag::CVQualList::Both;
17886 else if (Q.hasConst())
17887 QualSelect = diag::CVQualList::Const;
17888 else if (Q.hasVolatile())
17889 QualSelect = diag::CVQualList::Volatile;
17890
17891 if (QualSelect)
17892 Diag(UnderlyingLoc, diag::warn_cv_stripped_in_enum) << *QualSelect;
17893
17894 T = T.getAtomicUnqualifiedType();
17895
17896 // This doesn't use 'isIntegralType' despite the error message mentioning
17897 // integral type because isIntegralType would also allow enum types in C.
17898 if (const BuiltinType *BT = T->getAs<BuiltinType>())
17899 if (BT->isInteger())
17900 return false;
17901
17902 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
17903 << T << T->isBitIntType();
17904}
17905
17907 QualType EnumUnderlyingTy, bool IsFixed,
17908 const EnumDecl *Prev) {
17909 if (IsScoped != Prev->isScoped()) {
17910 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
17911 << Prev->isScoped();
17912 Diag(Prev->getLocation(), diag::note_previous_declaration);
17913 return true;
17914 }
17915
17916 if (IsFixed && Prev->isFixed()) {
17917 if (!EnumUnderlyingTy->isDependentType() &&
17918 !Prev->getIntegerType()->isDependentType() &&
17919 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
17920 Prev->getIntegerType())) {
17921 // TODO: Highlight the underlying type of the redeclaration.
17922 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
17923 << EnumUnderlyingTy << Prev->getIntegerType();
17924 Diag(Prev->getLocation(), diag::note_previous_declaration)
17925 << Prev->getIntegerTypeRange();
17926 return true;
17927 }
17928 } else if (IsFixed != Prev->isFixed()) {
17929 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
17930 << Prev->isFixed();
17931 Diag(Prev->getLocation(), diag::note_previous_declaration);
17932 return true;
17933 }
17934
17935 return false;
17936}
17937
17938/// Get diagnostic %select index for tag kind for
17939/// redeclaration diagnostic message.
17940/// WARNING: Indexes apply to particular diagnostics only!
17941///
17942/// \returns diagnostic %select index.
17944 switch (Tag) {
17946 return 0;
17948 return 1;
17949 case TagTypeKind::Class:
17950 return 2;
17951 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
17952 }
17953}
17954
17955/// Determine if tag kind is a class-key compatible with
17956/// class for redeclaration (class, struct, or __interface).
17957///
17958/// \returns true iff the tag kind is compatible.
17960{
17961 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class ||
17963}
17964
17966 if (isa<TypedefDecl>(PrevDecl))
17967 return NonTagKind::Typedef;
17968 else if (isa<TypeAliasDecl>(PrevDecl))
17969 return NonTagKind::TypeAlias;
17970 else if (isa<ClassTemplateDecl>(PrevDecl))
17971 return NonTagKind::Template;
17972 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
17974 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
17976 switch (TTK) {
17979 case TagTypeKind::Class:
17980 return getLangOpts().CPlusPlus ? NonTagKind::NonClass
17982 case TagTypeKind::Union:
17983 return NonTagKind::NonUnion;
17984 case TagTypeKind::Enum:
17985 return NonTagKind::NonEnum;
17986 }
17987 llvm_unreachable("invalid TTK");
17988}
17989
17991 TagTypeKind NewTag, bool isDefinition,
17992 SourceLocation NewTagLoc,
17993 const IdentifierInfo *Name) {
17994 // C++ [dcl.type.elab]p3:
17995 // The class-key or enum keyword present in the
17996 // elaborated-type-specifier shall agree in kind with the
17997 // declaration to which the name in the elaborated-type-specifier
17998 // refers. This rule also applies to the form of
17999 // elaborated-type-specifier that declares a class-name or
18000 // friend class since it can be construed as referring to the
18001 // definition of the class. Thus, in any
18002 // elaborated-type-specifier, the enum keyword shall be used to
18003 // refer to an enumeration (7.2), the union class-key shall be
18004 // used to refer to a union (clause 9), and either the class or
18005 // struct class-key shall be used to refer to a class (clause 9)
18006 // declared using the class or struct class-key.
18007 TagTypeKind OldTag = Previous->getTagKind();
18008 if (OldTag != NewTag &&
18010 return false;
18011
18012 // Tags are compatible, but we might still want to warn on mismatched tags.
18013 // Non-class tags can't be mismatched at this point.
18015 return true;
18016
18017 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
18018 // by our warning analysis. We don't want to warn about mismatches with (eg)
18019 // declarations in system headers that are designed to be specialized, but if
18020 // a user asks us to warn, we should warn if their code contains mismatched
18021 // declarations.
18022 auto IsIgnoredLoc = [&](SourceLocation Loc) {
18023 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
18024 Loc);
18025 };
18026 if (IsIgnoredLoc(NewTagLoc))
18027 return true;
18028
18029 auto IsIgnored = [&](const TagDecl *Tag) {
18030 return IsIgnoredLoc(Tag->getLocation());
18031 };
18032 while (IsIgnored(Previous)) {
18033 Previous = Previous->getPreviousDecl();
18034 if (!Previous)
18035 return true;
18036 OldTag = Previous->getTagKind();
18037 }
18038
18039 bool isTemplate = false;
18040 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
18041 isTemplate = Record->getDescribedClassTemplate();
18042
18044 if (OldTag != NewTag) {
18045 // In a template instantiation, do not offer fix-its for tag mismatches
18046 // since they usually mess up the template instead of fixing the problem.
18047 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
18049 << getRedeclDiagFromTagKind(OldTag);
18050 // FIXME: Note previous location?
18051 }
18052 return true;
18053 }
18054
18055 if (isDefinition) {
18056 // On definitions, check all previous tags and issue a fix-it for each
18057 // one that doesn't match the current tag.
18058 if (Previous->getDefinition()) {
18059 // Don't suggest fix-its for redefinitions.
18060 return true;
18061 }
18062
18063 bool previousMismatch = false;
18064 for (const TagDecl *I : Previous->redecls()) {
18065 if (I->getTagKind() != NewTag) {
18066 // Ignore previous declarations for which the warning was disabled.
18067 if (IsIgnored(I))
18068 continue;
18069
18070 if (!previousMismatch) {
18071 previousMismatch = true;
18072 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
18074 << getRedeclDiagFromTagKind(I->getTagKind());
18075 }
18076 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
18078 << FixItHint::CreateReplacement(I->getInnerLocStart(),
18080 }
18081 }
18082 return true;
18083 }
18084
18085 // Identify the prevailing tag kind: this is the kind of the definition (if
18086 // there is a non-ignored definition), or otherwise the kind of the prior
18087 // (non-ignored) declaration.
18088 const TagDecl *PrevDef = Previous->getDefinition();
18089 if (PrevDef && IsIgnored(PrevDef))
18090 PrevDef = nullptr;
18091 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
18092 if (Redecl->getTagKind() != NewTag) {
18093 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
18095 << getRedeclDiagFromTagKind(OldTag);
18096 Diag(Redecl->getLocation(), diag::note_previous_use);
18097
18098 // If there is a previous definition, suggest a fix-it.
18099 if (PrevDef) {
18100 Diag(NewTagLoc, diag::note_struct_class_suggestion)
18104 }
18105 }
18106
18107 return true;
18108}
18109
18110/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
18111/// from an outer enclosing namespace or file scope inside a friend declaration.
18112/// This should provide the commented out code in the following snippet:
18113/// namespace N {
18114/// struct X;
18115/// namespace M {
18116/// struct Y { friend struct /*N::*/ X; };
18117/// }
18118/// }
18120 SourceLocation NameLoc) {
18121 // While the decl is in a namespace, do repeated lookup of that name and see
18122 // if we get the same namespace back. If we do not, continue until
18123 // translation unit scope, at which point we have a fully qualified NNS.
18126 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
18127 // This tag should be declared in a namespace, which can only be enclosed by
18128 // other namespaces. Bail if there's an anonymous namespace in the chain.
18129 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
18130 if (!Namespace || Namespace->isAnonymousNamespace())
18131 return FixItHint();
18132 IdentifierInfo *II = Namespace->getIdentifier();
18133 Namespaces.push_back(II);
18134 NamedDecl *Lookup = SemaRef.LookupSingleName(
18135 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
18136 if (Lookup == Namespace)
18137 break;
18138 }
18139
18140 // Once we have all the namespaces, reverse them to go outermost first, and
18141 // build an NNS.
18142 SmallString<64> Insertion;
18143 llvm::raw_svector_ostream OS(Insertion);
18144 if (DC->isTranslationUnit())
18145 OS << "::";
18146 std::reverse(Namespaces.begin(), Namespaces.end());
18147 for (auto *II : Namespaces)
18148 OS << II->getName() << "::";
18149 return FixItHint::CreateInsertion(NameLoc, Insertion);
18150}
18151
18152/// Determine whether a tag originally declared in context \p OldDC can
18153/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
18154/// found a declaration in \p OldDC as a previous decl, perhaps through a
18155/// using-declaration).
18157 DeclContext *NewDC) {
18158 OldDC = OldDC->getRedeclContext();
18159 NewDC = NewDC->getRedeclContext();
18160
18161 if (OldDC->Equals(NewDC))
18162 return true;
18163
18164 // In MSVC mode, we allow a redeclaration if the contexts are related (either
18165 // encloses the other).
18166 if (S.getLangOpts().MSVCCompat &&
18167 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
18168 return true;
18169
18170 return false;
18171}
18172
18174Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
18175 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18176 const ParsedAttributesView &Attrs, AccessSpecifier AS,
18177 SourceLocation ModulePrivateLoc,
18178 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
18179 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
18180 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
18181 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
18182 OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
18183 // If this is not a definition, it must have a name.
18184 IdentifierInfo *OrigName = Name;
18185 assert((Name != nullptr || TUK == TagUseKind::Definition) &&
18186 "Nameless record must be a definition!");
18187 assert(TemplateParameterLists.size() == 0 || TUK != TagUseKind::Reference);
18188
18189 OwnedDecl = false;
18191 bool ScopedEnum = ScopedEnumKWLoc.isValid();
18192
18193 // FIXME: Check member specializations more carefully.
18194 bool isMemberSpecialization = false;
18195 bool IsInjectedClassName = false;
18196 bool Invalid = false;
18197
18198 // We only need to do this matching if we have template parameters
18199 // or a scope specifier, which also conveniently avoids this work
18200 // for non-C++ cases.
18201 if (TemplateParameterLists.size() > 0 ||
18202 (SS.isNotEmpty() && TUK != TagUseKind::Reference)) {
18203 TemplateParameterList *TemplateParams =
18205 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
18206 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
18207
18208 // C++23 [dcl.type.elab] p2:
18209 // If an elaborated-type-specifier is the sole constituent of a
18210 // declaration, the declaration is ill-formed unless it is an explicit
18211 // specialization, an explicit instantiation or it has one of the
18212 // following forms: [...]
18213 // C++23 [dcl.enum] p1:
18214 // If the enum-head-name of an opaque-enum-declaration contains a
18215 // nested-name-specifier, the declaration shall be an explicit
18216 // specialization.
18217 //
18218 // FIXME: Class template partial specializations can be forward declared
18219 // per CWG2213, but the resolution failed to allow qualified forward
18220 // declarations. This is almost certainly unintentional, so we allow them.
18221 if (TUK == TagUseKind::Declaration && SS.isNotEmpty() &&
18222 !isMemberSpecialization)
18223 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
18225
18226 if (TemplateParams) {
18227 if (Kind == TagTypeKind::Enum) {
18228 Diag(KWLoc, diag::err_enum_template);
18229 return true;
18230 }
18231
18232 if (TemplateParams->size() > 0) {
18233 // This is a declaration or definition of a class template (which may
18234 // be a member of another template).
18235
18236 if (Invalid)
18237 return true;
18238
18239 OwnedDecl = false;
18241 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
18242 AS, ModulePrivateLoc,
18243 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
18244 TemplateParameterLists.data(), isMemberSpecialization, SkipBody);
18245 return Result.get();
18246 } else {
18247 // The "template<>" header is extraneous.
18248 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
18249 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18250 isMemberSpecialization = true;
18251 }
18252 }
18253
18254 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
18255 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
18256 return true;
18257 }
18258
18259 if (TUK == TagUseKind::Friend && Kind == TagTypeKind::Enum) {
18260 // C++23 [dcl.type.elab]p4:
18261 // If an elaborated-type-specifier appears with the friend specifier as
18262 // an entire member-declaration, the member-declaration shall have one
18263 // of the following forms:
18264 // friend class-key nested-name-specifier(opt) identifier ;
18265 // friend class-key simple-template-id ;
18266 // friend class-key nested-name-specifier template(opt)
18267 // simple-template-id ;
18268 //
18269 // Since enum is not a class-key, so declarations like "friend enum E;"
18270 // are ill-formed. Although CWG2363 reaffirms that such declarations are
18271 // invalid, most implementations accept so we issue a pedantic warning.
18272 Diag(KWLoc, diag::ext_enum_friend) << FixItHint::CreateRemoval(
18273 ScopedEnum ? SourceRange(KWLoc, ScopedEnumKWLoc) : KWLoc);
18274 assert(ScopedEnum || !ScopedEnumUsesClassTag);
18275 Diag(KWLoc, diag::note_enum_friend)
18276 << (ScopedEnum + ScopedEnumUsesClassTag);
18277 }
18278
18279 // Figure out the underlying type if this a enum declaration. We need to do
18280 // this early, because it's needed to detect if this is an incompatible
18281 // redeclaration.
18282 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
18283 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
18284
18285 if (Kind == TagTypeKind::Enum) {
18286 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum) ||
18287 Invalid) {
18288 // No underlying type explicitly specified, or we failed to parse the
18289 // type, default to int.
18290 EnumUnderlying = Context.IntTy.getTypePtr();
18291 } else if (UnderlyingType.get()) {
18292 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
18293 // integral type; any cv-qualification is ignored.
18294 // C23 6.7.3.3p5: The underlying type of the enumeration is the
18295 // unqualified, non-atomic version of the type specified by the type
18296 // specifiers in the specifier qualifier list.
18297 TypeSourceInfo *TI = nullptr;
18298 GetTypeFromParser(UnderlyingType.get(), &TI);
18299 EnumUnderlying = TI;
18300
18302 // Recover by falling back to int.
18303 EnumUnderlying = Context.IntTy.getTypePtr();
18304
18307 EnumUnderlying = Context.IntTy.getTypePtr();
18308
18309 // If the underlying type is atomic, we need to adjust the type before
18310 // continuing. This only happens in the case we stored a TypeSourceInfo
18311 // into EnumUnderlying because the other cases are error recovery up to
18312 // this point. But because it's not possible to gin up a TypeSourceInfo
18313 // for a non-atomic type from an atomic one, we'll store into the Type
18314 // field instead. FIXME: it would be nice to have an easy way to get a
18315 // derived TypeSourceInfo which strips qualifiers including the weird
18316 // ones like _Atomic where it forms a different type.
18317 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying);
18318 TI && TI->getType()->isAtomicType())
18319 EnumUnderlying = TI->getType().getAtomicUnqualifiedType().getTypePtr();
18320
18321 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
18322 // For MSVC ABI compatibility, unfixed enums must use an underlying type
18323 // of 'int'. However, if this is an unfixed forward declaration, don't set
18324 // the underlying type unless the user enables -fms-compatibility. This
18325 // makes unfixed forward declared enums incomplete and is more conforming.
18326 if (TUK == TagUseKind::Definition || getLangOpts().MSVCCompat)
18327 EnumUnderlying = Context.IntTy.getTypePtr();
18328 }
18329 }
18330
18331 DeclContext *SearchDC = CurContext;
18332 DeclContext *DC = CurContext;
18333 bool isStdBadAlloc = false;
18334 bool isStdAlignValT = false;
18335
18337 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference)
18339
18340 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
18341 /// implemented asks for structural equivalence checking, the returned decl
18342 /// here is passed back to the parser, allowing the tag body to be parsed.
18343 auto createTagFromNewDecl = [&]() -> TagDecl * {
18344 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
18345 // If there is an identifier, use the location of the identifier as the
18346 // location of the decl, otherwise use the location of the struct/union
18347 // keyword.
18348 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18349 TagDecl *New = nullptr;
18350
18351 if (Kind == TagTypeKind::Enum) {
18352 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
18353 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
18354 // If this is an undefined enum, bail.
18355 if (TUK != TagUseKind::Definition && !Invalid)
18356 return nullptr;
18357 if (EnumUnderlying) {
18359 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
18361 else
18362 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
18363 QualType EnumTy = ED->getIntegerType();
18364 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
18365 ? Context.getPromotedIntegerType(EnumTy)
18366 : EnumTy);
18367 }
18368 } else { // struct/union
18369 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
18370 nullptr);
18371 }
18372
18373 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
18374 // Add alignment attributes if necessary; these attributes are checked
18375 // when the ASTContext lays out the structure.
18376 //
18377 // It is important for implementing the correct semantics that this
18378 // happen here (in ActOnTag). The #pragma pack stack is
18379 // maintained as a result of parser callbacks which can occur at
18380 // many points during the parsing of a struct declaration (because
18381 // the #pragma tokens are effectively skipped over during the
18382 // parsing of the struct).
18383 if (TUK == TagUseKind::Definition &&
18384 (!SkipBody || !SkipBody->ShouldSkip)) {
18385 if (LangOpts.HLSL)
18386 RD->addAttr(PackedAttr::CreateImplicit(Context));
18389 }
18390 }
18391 New->setLexicalDeclContext(CurContext);
18392 return New;
18393 };
18394
18395 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
18396 if (Name && SS.isNotEmpty()) {
18397 // We have a nested-name tag ('struct foo::bar').
18398
18399 // Check for invalid 'foo::'.
18400 if (SS.isInvalid()) {
18401 Name = nullptr;
18402 goto CreateNewDecl;
18403 }
18404
18405 // If this is a friend or a reference to a class in a dependent
18406 // context, don't try to make a decl for it.
18407 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference) {
18408 DC = computeDeclContext(SS, false);
18409 if (!DC) {
18410 IsDependent = true;
18411 return true;
18412 }
18413 } else {
18414 DC = computeDeclContext(SS, true);
18415 if (!DC) {
18416 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
18417 << SS.getRange();
18418 return true;
18419 }
18420 }
18421
18422 if (RequireCompleteDeclContext(SS, DC))
18423 return true;
18424
18425 SearchDC = DC;
18426 // Look-up name inside 'foo::'.
18428
18429 if (Previous.isAmbiguous())
18430 return true;
18431
18432 if (Previous.empty()) {
18433 // Name lookup did not find anything. However, if the
18434 // nested-name-specifier refers to the current instantiation,
18435 // and that current instantiation has any dependent base
18436 // classes, we might find something at instantiation time: treat
18437 // this as a dependent elaborated-type-specifier.
18438 // But this only makes any sense for reference-like lookups.
18439 if (Previous.wasNotFoundInCurrentInstantiation() &&
18440 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)) {
18441 IsDependent = true;
18442 return true;
18443 }
18444
18445 // A tag 'foo::bar' must already exist.
18446 Diag(NameLoc, diag::err_not_tag_in_scope)
18447 << Kind << Name << DC << SS.getRange();
18448 Name = nullptr;
18449 Invalid = true;
18450 goto CreateNewDecl;
18451 }
18452 } else if (Name) {
18453 // C++14 [class.mem]p14:
18454 // If T is the name of a class, then each of the following shall have a
18455 // name different from T:
18456 // -- every member of class T that is itself a type
18457 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
18458 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
18459 return true;
18460
18461 // If this is a named struct, check to see if there was a previous forward
18462 // declaration or definition.
18463 // FIXME: We're looking into outer scopes here, even when we
18464 // shouldn't be. Doing so can result in ambiguities that we
18465 // shouldn't be diagnosing.
18466 LookupName(Previous, S);
18467
18468 // When declaring or defining a tag, ignore ambiguities introduced
18469 // by types using'ed into this scope.
18470 if (Previous.isAmbiguous() &&
18472 LookupResult::Filter F = Previous.makeFilter();
18473 while (F.hasNext()) {
18474 NamedDecl *ND = F.next();
18475 if (!ND->getDeclContext()->getRedeclContext()->Equals(
18476 SearchDC->getRedeclContext()))
18477 F.erase();
18478 }
18479 F.done();
18480 }
18481
18482 // C++11 [namespace.memdef]p3:
18483 // If the name in a friend declaration is neither qualified nor
18484 // a template-id and the declaration is a function or an
18485 // elaborated-type-specifier, the lookup to determine whether
18486 // the entity has been previously declared shall not consider
18487 // any scopes outside the innermost enclosing namespace.
18488 //
18489 // MSVC doesn't implement the above rule for types, so a friend tag
18490 // declaration may be a redeclaration of a type declared in an enclosing
18491 // scope. They do implement this rule for friend functions.
18492 //
18493 // Does it matter that this should be by scope instead of by
18494 // semantic context?
18495 if (!Previous.empty() && TUK == TagUseKind::Friend) {
18496 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
18497 LookupResult::Filter F = Previous.makeFilter();
18498 bool FriendSawTagOutsideEnclosingNamespace = false;
18499 while (F.hasNext()) {
18500 NamedDecl *ND = F.next();
18502 if (DC->isFileContext() &&
18503 !EnclosingNS->Encloses(ND->getDeclContext())) {
18504 if (getLangOpts().MSVCCompat)
18505 FriendSawTagOutsideEnclosingNamespace = true;
18506 else
18507 F.erase();
18508 }
18509 }
18510 F.done();
18511
18512 // Diagnose this MSVC extension in the easy case where lookup would have
18513 // unambiguously found something outside the enclosing namespace.
18514 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
18515 NamedDecl *ND = Previous.getFoundDecl();
18516 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
18517 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
18518 }
18519 }
18520
18521 // Note: there used to be some attempt at recovery here.
18522 if (Previous.isAmbiguous())
18523 return true;
18524
18525 if (!getLangOpts().CPlusPlus && TUK != TagUseKind::Reference) {
18526 // FIXME: This makes sure that we ignore the contexts associated
18527 // with C structs, unions, and enums when looking for a matching
18528 // tag declaration or definition. See the similar lookup tweak
18529 // in Sema::LookupName; is there a better way to deal with this?
18531 SearchDC = SearchDC->getParent();
18532 } else if (getLangOpts().CPlusPlus) {
18533 // Inside ObjCContainer want to keep it as a lexical decl context but go
18534 // past it (most often to TranslationUnit) to find the semantic decl
18535 // context.
18536 while (isa<ObjCContainerDecl>(SearchDC))
18537 SearchDC = SearchDC->getParent();
18538 }
18539 } else if (getLangOpts().CPlusPlus) {
18540 // Don't use ObjCContainerDecl as the semantic decl context for anonymous
18541 // TagDecl the same way as we skip it for named TagDecl.
18542 while (isa<ObjCContainerDecl>(SearchDC))
18543 SearchDC = SearchDC->getParent();
18544 }
18545
18546 if (Previous.isSingleResult() &&
18547 Previous.getFoundDecl()->isTemplateParameter()) {
18548 // Maybe we will complain about the shadowed template parameter.
18549 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
18550 // Just pretend that we didn't see the previous declaration.
18551 Previous.clear();
18552 }
18553
18554 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
18556 if (Name->isStr("bad_alloc")) {
18557 // This is a declaration of or a reference to "std::bad_alloc".
18558 isStdBadAlloc = true;
18559
18560 // If std::bad_alloc has been implicitly declared (but made invisible to
18561 // name lookup), fill in this implicit declaration as the previous
18562 // declaration, so that the declarations get chained appropriately.
18563 if (Previous.empty() && StdBadAlloc)
18564 Previous.addDecl(getStdBadAlloc());
18565 } else if (Name->isStr("align_val_t")) {
18566 isStdAlignValT = true;
18567 if (Previous.empty() && StdAlignValT)
18568 Previous.addDecl(getStdAlignValT());
18569 }
18570 }
18571
18572 // If we didn't find a previous declaration, and this is a reference
18573 // (or friend reference), move to the correct scope. In C++, we
18574 // also need to do a redeclaration lookup there, just in case
18575 // there's a shadow friend decl.
18576 if (Name && Previous.empty() &&
18577 (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18578 IsTemplateParamOrArg)) {
18579 if (Invalid) goto CreateNewDecl;
18580 assert(SS.isEmpty());
18581
18582 if (TUK == TagUseKind::Reference || IsTemplateParamOrArg) {
18583 // C++ [basic.scope.pdecl]p5:
18584 // -- for an elaborated-type-specifier of the form
18585 //
18586 // class-key identifier
18587 //
18588 // if the elaborated-type-specifier is used in the
18589 // decl-specifier-seq or parameter-declaration-clause of a
18590 // function defined in namespace scope, the identifier is
18591 // declared as a class-name in the namespace that contains
18592 // the declaration; otherwise, except as a friend
18593 // declaration, the identifier is declared in the smallest
18594 // non-class, non-function-prototype scope that contains the
18595 // declaration.
18596 //
18597 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
18598 // C structs and unions.
18599 //
18600 // It is an error in C++ to declare (rather than define) an enum
18601 // type, including via an elaborated type specifier. We'll
18602 // diagnose that later; for now, declare the enum in the same
18603 // scope as we would have picked for any other tag type.
18604 //
18605 // GNU C also supports this behavior as part of its incomplete
18606 // enum types extension, while GNU C++ does not.
18607 //
18608 // Find the context where we'll be declaring the tag.
18609 // FIXME: We would like to maintain the current DeclContext as the
18610 // lexical context,
18611 SearchDC = getTagInjectionContext(SearchDC);
18612
18613 // Find the scope where we'll be declaring the tag.
18615 } else {
18616 assert(TUK == TagUseKind::Friend);
18617 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC);
18618
18619 // C++ [namespace.memdef]p3:
18620 // If a friend declaration in a non-local class first declares a
18621 // class or function, the friend class or function is a member of
18622 // the innermost enclosing namespace.
18623 SearchDC = RD->isLocalClass() ? RD->isLocalClass()
18624 : SearchDC->getEnclosingNamespaceContext();
18625 }
18626
18627 // In C++, we need to do a redeclaration lookup to properly
18628 // diagnose some problems.
18629 // FIXME: redeclaration lookup is also used (with and without C++) to find a
18630 // hidden declaration so that we don't get ambiguity errors when using a
18631 // type declared by an elaborated-type-specifier. In C that is not correct
18632 // and we should instead merge compatible types found by lookup.
18633 if (getLangOpts().CPlusPlus) {
18634 // FIXME: This can perform qualified lookups into function contexts,
18635 // which are meaningless.
18636 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18637 LookupQualifiedName(Previous, SearchDC);
18638 } else {
18639 Previous.setRedeclarationKind(forRedeclarationInCurContext());
18640 LookupName(Previous, S);
18641 }
18642 }
18643
18644 // If we have a known previous declaration to use, then use it.
18645 if (Previous.empty() && SkipBody && SkipBody->Previous)
18646 Previous.addDecl(SkipBody->Previous);
18647
18648 if (!Previous.empty()) {
18649 NamedDecl *PrevDecl = Previous.getFoundDecl();
18650 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
18651
18652 // It's okay to have a tag decl in the same scope as a typedef
18653 // which hides a tag decl in the same scope. Finding this
18654 // with a redeclaration lookup can only actually happen in C++.
18655 //
18656 // This is also okay for elaborated-type-specifiers, which is
18657 // technically forbidden by the current standard but which is
18658 // okay according to the likely resolution of an open issue;
18659 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
18660 if (getLangOpts().CPlusPlus) {
18661 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18662 if (TagDecl *Tag = TD->getUnderlyingType()->getAsTagDecl()) {
18663 if (Tag->getDeclName() == Name &&
18664 Tag->getDeclContext()->getRedeclContext()
18665 ->Equals(TD->getDeclContext()->getRedeclContext())) {
18666 PrevDecl = Tag;
18667 Previous.clear();
18668 Previous.addDecl(Tag);
18669 Previous.resolveKind();
18670 }
18671 }
18672 }
18673 }
18674
18675 // If this is a redeclaration of a using shadow declaration, it must
18676 // declare a tag in the same context. In MSVC mode, we allow a
18677 // redefinition if either context is within the other.
18678 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
18679 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
18680 if (SS.isEmpty() && TUK != TagUseKind::Reference &&
18681 TUK != TagUseKind::Friend &&
18682 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
18683 !(OldTag && isAcceptableTagRedeclContext(
18684 *this, OldTag->getDeclContext(), SearchDC))) {
18685 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
18686 Diag(Shadow->getTargetDecl()->getLocation(),
18687 diag::note_using_decl_target);
18688 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
18689 << 0;
18690 // Recover by ignoring the old declaration.
18691 Previous.clear();
18692 goto CreateNewDecl;
18693 }
18694 }
18695
18696 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
18697 // If this is a use of a previous tag, or if the tag is already declared
18698 // in the same scope (so that the definition/declaration completes or
18699 // rementions the tag), reuse the decl.
18700 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend ||
18701 isTagRedeclarationInScope(DirectPrevDecl, SearchDC, S,
18702 SS.isNotEmpty() ||
18703 isMemberSpecialization)) {
18704
18705 if (auto *RD = dyn_cast<CXXRecordDecl>(PrevDecl);
18706 RD && RD->isInjectedClassName()) {
18707 // If lookup found the injected class name, the previous declaration
18708 // is the class being injected into.
18709 Previous.clear();
18710 PrevDecl = PrevTagDecl = cast<CXXRecordDecl>(RD->getDeclContext());
18711 Previous.addDecl(PrevDecl);
18712 Previous.resolveKind();
18713 IsInjectedClassName = true;
18714 }
18715
18716 // Make sure that this wasn't declared as an enum and now used as a
18717 // struct or something similar.
18718 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
18719 TUK == TagUseKind::Definition, KWLoc,
18720 Name)) {
18721 bool SafeToContinue =
18722 (PrevTagDecl->getTagKind() != TagTypeKind::Enum &&
18723 Kind != TagTypeKind::Enum);
18724 if (SafeToContinue)
18725 Diag(KWLoc, diag::err_use_with_wrong_tag)
18726 << Name
18728 PrevTagDecl->getKindName());
18729 else
18730 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
18731 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
18732
18733 if (SafeToContinue)
18734 Kind = PrevTagDecl->getTagKind();
18735 else {
18736 // Recover by making this an anonymous redefinition.
18737 Name = nullptr;
18738 Previous.clear();
18739 Invalid = true;
18740 }
18741 }
18742
18743 if (Kind == TagTypeKind::Enum &&
18744 PrevTagDecl->getTagKind() == TagTypeKind::Enum) {
18745 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
18746 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend)
18747 return PrevTagDecl;
18748
18749 QualType EnumUnderlyingTy;
18750 if (TypeSourceInfo *TI =
18751 dyn_cast_if_present<TypeSourceInfo *>(EnumUnderlying))
18752 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
18753 else if (const Type *T =
18754 dyn_cast_if_present<const Type *>(EnumUnderlying))
18755 EnumUnderlyingTy = QualType(T, 0);
18756
18757 // All conflicts with previous declarations are recovered by
18758 // returning the previous declaration, unless this is a definition,
18759 // in which case we want the caller to bail out.
18760 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
18761 ScopedEnum, EnumUnderlyingTy,
18762 IsFixed, PrevEnum))
18763 return TUK == TagUseKind::Declaration ? PrevTagDecl : nullptr;
18764 }
18765
18766 // C++11 [class.mem]p1:
18767 // A member shall not be declared twice in the member-specification,
18768 // except that a nested class or member class template can be declared
18769 // and then later defined.
18770 if (TUK == TagUseKind::Declaration && PrevDecl->isCXXClassMember() &&
18771 S->isDeclScope(PrevDecl)) {
18772 Diag(NameLoc, diag::ext_member_redeclared);
18773 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
18774 }
18775
18776 // C++ [class.local]p3:
18777 // A class nested within a local class is a local class. A member of
18778 // a local class X shall be declared only in the definition of X or,
18779 // if the member is a nested class, in the nearest enclosing block
18780 // scope of X.
18781 if (TUK == TagUseKind::Definition && SS.isValid()) {
18782 if (const auto *OutermostClass = dyn_cast<CXXRecordDecl>(PrevDecl)) {
18783 while (const auto *ParentClass =
18784 dyn_cast<CXXRecordDecl>(OutermostClass->getParent()))
18785 OutermostClass = ParentClass;
18786
18787 if (OutermostClass->isLocalClass() &&
18788 !S->isDeclScope(OutermostClass)) {
18789 Diag(NameLoc, diag::err_local_nested_class_invalid_scope)
18790 << Name << OutermostClass;
18791 Diag(OutermostClass->getLocation(), diag::note_defined_here)
18792 << OutermostClass;
18793 }
18794 }
18795 }
18796
18797 if (!Invalid) {
18798 // If this is a use, just return the declaration we found, unless
18799 // we have attributes.
18800 if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18801 if (!Attrs.empty()) {
18802 // FIXME: Diagnose these attributes. For now, we create a new
18803 // declaration to hold them.
18804 } else if (TUK == TagUseKind::Reference &&
18805 (PrevTagDecl->getFriendObjectKind() ==
18807 PrevDecl->getOwningModule() != getCurrentModule()) &&
18808 SS.isEmpty()) {
18809 // This declaration is a reference to an existing entity, but
18810 // has different visibility from that entity: it either makes
18811 // a friend visible or it makes a type visible in a new module.
18812 // In either case, create a new declaration. We only do this if
18813 // the declaration would have meant the same thing if no prior
18814 // declaration were found, that is, if it was found in the same
18815 // scope where we would have injected a declaration.
18816 if (!getTagInjectionContext(CurContext)->getRedeclContext()
18817 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
18818 return PrevTagDecl;
18819 // This is in the injected scope, create a new declaration in
18820 // that scope.
18822 } else {
18823 return PrevTagDecl;
18824 }
18825 }
18826
18827 // Diagnose attempts to redefine a tag.
18828 if (TUK == TagUseKind::Definition) {
18829 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
18830 // If the type is currently being defined, complain
18831 // about a nested redefinition.
18832 if (Def->isBeingDefined()) {
18833 Diag(NameLoc, diag::err_nested_redefinition) << Name;
18834 Diag(PrevTagDecl->getLocation(),
18835 diag::note_previous_definition);
18836 Name = nullptr;
18837 Previous.clear();
18838 Invalid = true;
18839 } else {
18840 // If we're defining a specialization and the previous
18841 // definition is from an implicit instantiation, don't emit an
18842 // error here; we'll catch this in the general case below.
18843 bool IsExplicitSpecializationAfterInstantiation = false;
18844 if (isMemberSpecialization) {
18845 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
18846 IsExplicitSpecializationAfterInstantiation =
18847 RD->getTemplateSpecializationKind() !=
18849 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
18850 IsExplicitSpecializationAfterInstantiation =
18851 ED->getTemplateSpecializationKind() !=
18853 }
18854
18855 // Note that clang allows ODR-like semantics for ObjC/C, i.e.,
18856 // do not keep more that one definition around (merge them).
18857 // However, ensure the decl passes the structural compatibility
18858 // check in C11 6.2.7/1 (or 6.1.2.6/1 in C89).
18859 NamedDecl *Hidden = nullptr;
18860 bool HiddenDefVisible = false;
18861 if (SkipBody && (isRedefinitionAllowedFor(Def, NameLoc, &Hidden,
18862 HiddenDefVisible) ||
18863 getLangOpts().C23)) {
18864 // There is a definition of this tag, but it is not visible.
18865 // We explicitly make use of C++'s one definition rule here,
18866 // and assume that this definition is identical to the hidden
18867 // one we already have. Make the existing definition visible
18868 // and use it in place of this one.
18869 if (!getLangOpts().CPlusPlus) {
18870 // Postpone making the old definition visible until after we
18871 // complete parsing the new one and do the structural
18872 // comparison.
18873 SkipBody->CheckSameAsPrevious = true;
18874 SkipBody->New = createTagFromNewDecl();
18875 SkipBody->Previous = Def;
18876
18877 ProcessDeclAttributeList(S, SkipBody->New, Attrs);
18878 return Def;
18879 }
18880
18881 SkipBody->ShouldSkip = true;
18882 SkipBody->Previous = Def;
18883 if (!HiddenDefVisible && Hidden)
18885 // Carry on and handle it like a normal definition. We'll
18886 // skip starting the definition later.
18887
18888 } else if (!IsExplicitSpecializationAfterInstantiation) {
18889 // A redeclaration in function prototype scope in C isn't
18890 // visible elsewhere, so merely issue a warning.
18891 if (!getLangOpts().CPlusPlus &&
18893 Diag(NameLoc, diag::warn_redefinition_in_param_list)
18894 << Name;
18895 else
18896 Diag(NameLoc, diag::err_redefinition) << Name;
18898 NameLoc.isValid() ? NameLoc : KWLoc);
18899 // If this is a redefinition, recover by making this
18900 // struct be anonymous, which will make any later
18901 // references get the previous definition.
18902 Name = nullptr;
18903 Previous.clear();
18904 Invalid = true;
18905 }
18906 }
18907 }
18908
18909 // Okay, this is definition of a previously declared or referenced
18910 // tag. We're going to create a new Decl for it.
18911 }
18912
18913 // Okay, we're going to make a redeclaration. If this is some kind
18914 // of reference, make sure we build the redeclaration in the same DC
18915 // as the original, and ignore the current access specifier.
18916 if (TUK == TagUseKind::Friend || TUK == TagUseKind::Reference ||
18917 IsInjectedClassName) {
18918 SearchDC = PrevTagDecl->getDeclContext();
18919 AS = AS_none;
18920 }
18921 }
18922 // If we get here we have (another) forward declaration or we
18923 // have a definition. Just create a new decl.
18924
18925 } else {
18926 // If we get here, this is a definition of a new tag type in a nested
18927 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
18928 // new decl/type. We set PrevDecl to NULL so that the entities
18929 // have distinct types.
18930 Previous.clear();
18931 }
18932 // If we get here, we're going to create a new Decl. If PrevDecl
18933 // is non-NULL, it's a definition of the tag declared by
18934 // PrevDecl. If it's NULL, we have a new definition.
18935
18936 // Otherwise, PrevDecl is not a tag, but was found with tag
18937 // lookup. This is only actually possible in C++, where a few
18938 // things like templates still live in the tag namespace.
18939 } else {
18940 // Use a better diagnostic if an elaborated-type-specifier
18941 // found the wrong kind of type on the first
18942 // (non-redeclaration) lookup.
18943 if ((TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) &&
18944 !Previous.isForRedeclaration()) {
18945 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18946 Diag(NameLoc, diag::err_tag_reference_non_tag)
18947 << PrevDecl << NTK << Kind;
18948 Diag(PrevDecl->getLocation(), diag::note_declared_at);
18949 Invalid = true;
18950
18951 // Otherwise, only diagnose if the declaration is in scope.
18952 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
18953 SS.isNotEmpty() || isMemberSpecialization)) {
18954 // do nothing
18955
18956 // Diagnose implicit declarations introduced by elaborated types.
18957 } else if (TUK == TagUseKind::Reference || TUK == TagUseKind::Friend) {
18958 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
18959 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
18960 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18961 Invalid = true;
18962
18963 // Otherwise it's a declaration. Call out a particularly common
18964 // case here.
18965 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
18966 unsigned Kind = 0;
18967 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
18968 Diag(NameLoc, diag::err_tag_definition_of_typedef)
18969 << Name << Kind << TND->getUnderlyingType();
18970 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
18971 Invalid = true;
18972
18973 // Otherwise, diagnose.
18974 } else {
18975 // The tag name clashes with something else in the target scope,
18976 // issue an error and recover by making this tag be anonymous.
18977 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
18978 notePreviousDefinition(PrevDecl, NameLoc);
18979 Name = nullptr;
18980 Invalid = true;
18981 }
18982
18983 // The existing declaration isn't relevant to us; we're in a
18984 // new scope, so clear out the previous declaration.
18985 Previous.clear();
18986 }
18987 }
18988
18989CreateNewDecl:
18990
18991 TagDecl *PrevDecl = nullptr;
18992 if (Previous.isSingleResult())
18993 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
18994
18995 // If there is an identifier, use the location of the identifier as the
18996 // location of the decl, otherwise use the location of the struct/union
18997 // keyword.
18998 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
18999
19000 // Otherwise, create a new declaration. If there is a previous
19001 // declaration of the same entity, the two will be linked via
19002 // PrevDecl.
19003 TagDecl *New;
19004
19005 if (Kind == TagTypeKind::Enum) {
19006 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19007 // enum X { A, B, C } D; D should chain to X.
19008 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
19009 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
19010 ScopedEnumUsesClassTag, IsFixed);
19011
19014 KWLoc, ScopedEnumKWLoc.isValid() ? ScopedEnumKWLoc : KWLoc));
19015
19016 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
19018
19019 // If this is an undefined enum, warn.
19020 if (TUK != TagUseKind::Definition && !Invalid) {
19021 TagDecl *Def;
19022 if (IsFixed && ED->isFixed()) {
19023 // C++0x: 7.2p2: opaque-enum-declaration.
19024 // Conflicts are diagnosed above. Do nothing.
19025 } else if (PrevDecl &&
19026 (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
19027 Diag(Loc, diag::ext_forward_ref_enum_def)
19028 << New;
19029 Diag(Def->getLocation(), diag::note_previous_definition);
19030 } else {
19031 unsigned DiagID = diag::ext_forward_ref_enum;
19032 if (getLangOpts().MSVCCompat)
19033 DiagID = diag::ext_ms_forward_ref_enum;
19034 else if (getLangOpts().CPlusPlus)
19035 DiagID = diag::err_forward_ref_enum;
19036 Diag(Loc, DiagID);
19037 }
19038 }
19039
19040 if (EnumUnderlying) {
19042 if (TypeSourceInfo *TI = dyn_cast<TypeSourceInfo *>(EnumUnderlying))
19044 else
19045 ED->setIntegerType(QualType(cast<const Type *>(EnumUnderlying), 0));
19046 QualType EnumTy = ED->getIntegerType();
19047 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
19048 ? Context.getPromotedIntegerType(EnumTy)
19049 : EnumTy);
19050 assert(ED->isComplete() && "enum with type should be complete");
19051 }
19052 } else {
19053 // struct/union/class
19054
19055 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
19056 // struct X { int A; } D; D should chain to X.
19057 if (getLangOpts().CPlusPlus) {
19058 // FIXME: Look for a way to use RecordDecl for simple structs.
19059 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
19060 cast_or_null<CXXRecordDecl>(PrevDecl));
19061
19062 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
19064 } else
19065 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
19066 cast_or_null<RecordDecl>(PrevDecl));
19067 }
19068
19069 // Only C23 and later allow defining new types in 'offsetof()'.
19070 if (OOK != OffsetOfKind::Outside && TUK == TagUseKind::Definition &&
19072 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
19073 << (OOK == OffsetOfKind::Macro) << New->getSourceRange();
19074
19075 // C++11 [dcl.type]p3:
19076 // A type-specifier-seq shall not define a class or enumeration [...].
19077 if (!Invalid && getLangOpts().CPlusPlus &&
19078 (IsTypeSpecifier || IsTemplateParamOrArg) &&
19079 TUK == TagUseKind::Definition) {
19080 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
19081 << Context.getCanonicalTagType(New);
19082 Invalid = true;
19083 }
19084
19086 DC->getDeclKind() == Decl::Enum) {
19087 Diag(New->getLocation(), diag::err_type_defined_in_enum)
19088 << Context.getCanonicalTagType(New);
19089 Invalid = true;
19090 }
19091
19092 // Maybe add qualifier info.
19093 if (SS.isNotEmpty()) {
19094 if (SS.isSet()) {
19095 // If this is either a declaration or a definition, check the
19096 // nested-name-specifier against the current context.
19097 if ((TUK == TagUseKind::Definition || TUK == TagUseKind::Declaration) &&
19098 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
19099 /*TemplateId=*/nullptr,
19100 isMemberSpecialization))
19101 Invalid = true;
19102
19103 New->setQualifierInfo(SS.getWithLocInContext(Context));
19104 if (TemplateParameterLists.size() > 0) {
19105 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
19106 }
19107 }
19108 else
19109 Invalid = true;
19110 }
19111
19112 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
19113 // Add alignment attributes if necessary; these attributes are checked when
19114 // the ASTContext lays out the structure.
19115 //
19116 // It is important for implementing the correct semantics that this
19117 // happen here (in ActOnTag). The #pragma pack stack is
19118 // maintained as a result of parser callbacks which can occur at
19119 // many points during the parsing of a struct declaration (because
19120 // the #pragma tokens are effectively skipped over during the
19121 // parsing of the struct).
19122 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
19123 if (LangOpts.HLSL)
19124 RD->addAttr(PackedAttr::CreateImplicit(Context));
19127 }
19128 }
19129
19130 if (ModulePrivateLoc.isValid()) {
19131 if (isMemberSpecialization)
19132 Diag(New->getLocation(), diag::err_module_private_specialization)
19133 << 2
19134 << FixItHint::CreateRemoval(ModulePrivateLoc);
19135 // __module_private__ does not apply to local classes. However, we only
19136 // diagnose this as an error when the declaration specifiers are
19137 // freestanding. Here, we just ignore the __module_private__.
19138 else if (!SearchDC->isFunctionOrMethod())
19139 New->setModulePrivate();
19140 }
19141
19142 // If this is a specialization of a member class (of a class template),
19143 // check the specialization.
19144 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
19145 Invalid = true;
19146
19147 // If we're declaring or defining a tag in function prototype scope in C,
19148 // note that this type can only be used within the function and add it to
19149 // the list of decls to inject into the function definition scope. However,
19150 // in C23 and later, while the type is only visible within the function, the
19151 // function can be called with a compatible type defined in the same TU, so
19152 // we silence the diagnostic in C23 and up. This matches the behavior of GCC.
19153 if ((Name || Kind == TagTypeKind::Enum) &&
19154 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
19155 if (getLangOpts().CPlusPlus) {
19156 // C++ [dcl.fct]p6:
19157 // Types shall not be defined in return or parameter types.
19158 if (TUK == TagUseKind::Definition && !IsTypeSpecifier) {
19159 Diag(Loc, diag::err_type_defined_in_param_type)
19160 << Name;
19161 Invalid = true;
19162 }
19163 if (TUK == TagUseKind::Declaration)
19164 Invalid = true;
19165 } else if (!PrevDecl) {
19166 // In C23 mode, if the declaration is complete, we do not want to
19167 // diagnose.
19168 if (!getLangOpts().C23 || TUK != TagUseKind::Definition)
19169 Diag(Loc, diag::warn_decl_in_param_list)
19170 << Context.getCanonicalTagType(New);
19171 }
19172 }
19173
19174 if (Invalid)
19175 New->setInvalidDecl();
19176
19177 // Set the lexical context. If the tag has a C++ scope specifier, the
19178 // lexical context will be different from the semantic context.
19179 New->setLexicalDeclContext(CurContext);
19180
19181 // Mark this as a friend decl if applicable.
19182 // In Microsoft mode, a friend declaration also acts as a forward
19183 // declaration so we always pass true to setObjectOfFriendDecl to make
19184 // the tag name visible.
19185 if (TUK == TagUseKind::Friend)
19186 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
19187
19188 // Set the access specifier.
19189 if (!Invalid && SearchDC->isRecord())
19190 SetMemberAccessSpecifier(New, PrevDecl, AS);
19191
19192 // FIXME: An elaborated-type-specifier referring to an existing tag should
19193 // ideally not introduce a redeclaration. ActOnTag currently creates one, so
19194 // avoid diagnosing it as a redeclaration across module boundaries.
19195 //
19196 // See https://github.com/llvm/llvm-project/pull/194546 for full background.
19197 if (PrevDecl && TUK != TagUseKind::Reference)
19199
19200 if (TUK == TagUseKind::Definition) {
19201 if (!SkipBody || !SkipBody->ShouldSkip) {
19202 New->startDefinition();
19203 } else {
19204 New->setCompleteDefinition();
19205 New->demoteThisDefinitionToDeclaration();
19206 }
19207 }
19208
19209 ProcessDeclAttributeList(S, New, Attrs);
19211
19212 // If this has an identifier, add it to the scope stack.
19213 if (TUK == TagUseKind::Friend || IsInjectedClassName) {
19214 // We might be replacing an existing declaration in the lookup tables;
19215 // if so, borrow its access specifier.
19216 if (PrevDecl)
19217 New->setAccess(PrevDecl->getAccess());
19218
19219 DeclContext *DC = New->getDeclContext()->getRedeclContext();
19221 if (Name) // can be null along some error paths
19222 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19223 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
19224 } else if (Name) {
19225 S = getNonFieldDeclScope(S);
19226 PushOnScopeChains(New, S, true);
19227 } else {
19228 CurContext->addDecl(New);
19229 }
19230
19231 // If this is the C FILE type, notify the AST context.
19232 if (IdentifierInfo *II = New->getIdentifier())
19233 if (!New->isInvalidDecl() &&
19234 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
19235 II->isStr("FILE"))
19236 Context.setFILEDecl(New);
19237
19238 if (PrevDecl)
19239 mergeDeclAttributes(New, PrevDecl);
19240
19241 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) {
19244 }
19245
19246 // If there's a #pragma GCC visibility in scope, set the visibility of this
19247 // record.
19249
19250 // If this is not a definition, process API notes for it now.
19251 if (TUK != TagUseKind::Definition)
19253
19254 if (isMemberSpecialization && !New->isInvalidDecl())
19256
19257 OwnedDecl = true;
19258 // In C++, don't return an invalid declaration. We can't recover well from
19259 // the cases where we make the type anonymous.
19260 if (Invalid && getLangOpts().CPlusPlus) {
19261 if (New->isBeingDefined())
19262 if (auto RD = dyn_cast<RecordDecl>(New))
19263 RD->completeDefinition();
19264 return true;
19265 } else if (SkipBody && SkipBody->ShouldSkip) {
19266 return SkipBody->Previous;
19267 } else {
19268 return New;
19269 }
19270}
19271
19274 TagDecl *Tag = cast<TagDecl>(TagD);
19275
19276 // Enter the tag context.
19277 PushDeclContext(S, Tag);
19278
19280
19281 // If there's a #pragma GCC visibility in scope, set the visibility of this
19282 // record.
19284}
19285
19287 SkipBodyInfo &SkipBody) {
19288 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
19289 return false;
19290
19291 // Make the previous decl visible.
19293 CleanupMergedEnum(S, SkipBody.New);
19294 return true;
19295}
19296
19298 SourceLocation FinalLoc,
19299 bool IsFinalSpelledSealed,
19300 bool IsAbstract,
19301 SourceLocation LBraceLoc) {
19304
19305 FieldCollector->StartClass();
19306
19307 if (!Record->getIdentifier())
19308 return;
19309
19310 if (IsAbstract)
19311 Record->markAbstract();
19312
19313 if (FinalLoc.isValid()) {
19314 Record->addAttr(FinalAttr::Create(Context, FinalLoc,
19315 IsFinalSpelledSealed
19316 ? FinalAttr::Keyword_sealed
19317 : FinalAttr::Keyword_final));
19318 }
19319
19320 // C++ [class]p2:
19321 // [...] The class-name is also inserted into the scope of the
19322 // class itself; this is known as the injected-class-name. For
19323 // purposes of access checking, the injected-class-name is treated
19324 // as if it were a public member name.
19325 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
19326 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
19327 Record->getLocation(), Record->getIdentifier());
19328 InjectedClassName->setImplicit();
19329 InjectedClassName->setAccess(AS_public);
19330 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
19331 InjectedClassName->setDescribedClassTemplate(Template);
19332
19333 PushOnScopeChains(InjectedClassName, S);
19334 assert(InjectedClassName->isInjectedClassName() &&
19335 "Broken injected-class-name");
19336}
19337
19339 SourceRange BraceRange) {
19341 TagDecl *Tag = cast<TagDecl>(TagD);
19342 Tag->setBraceRange(BraceRange);
19343
19344 // Make sure we "complete" the definition even it is invalid.
19345 if (Tag->isBeingDefined()) {
19346 assert(Tag->isInvalidDecl() && "We should already have completed it");
19347 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19348 RD->completeDefinition();
19349 }
19350
19351 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
19352 FieldCollector->FinishClass();
19353 if (RD->hasAttr<SYCLSpecialClassAttr>()) {
19354 auto *Def = RD->getDefinition();
19355 assert(Def && "The record is expected to have a completed definition");
19356 unsigned NumInitMethods = 0;
19357 for (auto *Method : Def->methods()) {
19358 if (!Method->getIdentifier())
19359 continue;
19360 if (Method->getName() == "__init")
19361 NumInitMethods++;
19362 }
19363 if (NumInitMethods > 1 || !Def->hasInitMethod())
19364 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
19365 }
19366
19367 // If we're defining a dynamic class in a module interface unit, we always
19368 // need to produce the vtable for it, even if the vtable is not used in the
19369 // current TU.
19370 //
19371 // The case where the current class is not dynamic is handled in
19372 // MarkVTableUsed.
19373 if (getCurrentModule() && getCurrentModule()->isInterfaceOrPartition())
19374 MarkVTableUsed(RD->getLocation(), RD, /*DefinitionRequired=*/true);
19375 }
19376
19377 // Exit this scope of this tag's definition.
19379
19380 if (getCurLexicalContext()->isObjCContainer() &&
19381 Tag->getDeclContext()->isFileContext())
19382 Tag->setTopLevelDeclInObjCContainer();
19383
19384 // Notify the consumer that we've defined a tag.
19385 if (!Tag->isInvalidDecl())
19386 Consumer.HandleTagDeclDefinition(Tag);
19387
19388 // Clangs implementation of #pragma align(packed) differs in bitfield layout
19389 // from XLs and instead matches the XL #pragma pack(1) behavior.
19390 if (Context.getTargetInfo().getTriple().isOSAIX() &&
19391 AlignPackStack.hasValue()) {
19392 AlignPackInfo APInfo = AlignPackStack.CurrentValue;
19393 // Only diagnose #pragma align(packed).
19394 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
19395 return;
19396 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
19397 if (!RD)
19398 return;
19399 // Only warn if there is at least 1 bitfield member.
19400 if (llvm::any_of(RD->fields(),
19401 [](const FieldDecl *FD) { return FD->isBitField(); }))
19402 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
19403 }
19404}
19405
19408 TagDecl *Tag = cast<TagDecl>(TagD);
19409 Tag->setInvalidDecl();
19410
19411 // Make sure we "complete" the definition even it is invalid.
19412 if (Tag->isBeingDefined()) {
19413 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
19414 RD->completeDefinition();
19415 }
19416
19417 // We're undoing ActOnTagStartDefinition here, not
19418 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
19419 // the FieldCollector.
19420
19422}
19423
19424// Note that FieldName may be null for anonymous bitfields.
19426 const IdentifierInfo *FieldName,
19427 QualType FieldTy, bool IsMsStruct,
19428 Expr *BitWidth) {
19429 assert(BitWidth);
19430 if (BitWidth->containsErrors())
19431 return ExprError();
19432
19433 // C99 6.7.2.1p4 - verify the field type.
19434 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
19435 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
19436 // Handle incomplete and sizeless types with a specific error.
19437 if (RequireCompleteSizedType(FieldLoc, FieldTy,
19438 diag::err_field_incomplete_or_sizeless))
19439 return ExprError();
19440 if (FieldName)
19441 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
19442 << FieldName << FieldTy << BitWidth->getSourceRange();
19443 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
19444 << FieldTy << BitWidth->getSourceRange();
19446 return ExprError();
19447
19448 // If the bit-width is type- or value-dependent, don't try to check
19449 // it now.
19450 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
19451 return BitWidth;
19452
19453 llvm::APSInt Value;
19454 ExprResult ICE =
19456 if (ICE.isInvalid())
19457 return ICE;
19458 BitWidth = ICE.get();
19459
19460 // Zero-width bitfield is ok for anonymous field.
19461 if (Value == 0 && FieldName)
19462 return Diag(FieldLoc, diag::err_bitfield_has_zero_width)
19463 << FieldName << BitWidth->getSourceRange();
19464
19465 if (Value.isSigned() && Value.isNegative()) {
19466 if (FieldName)
19467 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
19468 << FieldName << toString(Value, 10);
19469 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
19470 << toString(Value, 10);
19471 }
19472
19473 // The size of the bit-field must not exceed our maximum permitted object
19474 // size.
19475 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
19476 return Diag(FieldLoc, diag::err_bitfield_too_wide)
19477 << !FieldName << FieldName << toString(Value, 10);
19478 }
19479
19480 if (!FieldTy->isDependentType()) {
19481 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
19482 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
19483 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
19484
19485 // Over-wide bitfields are an error in C or when using the MSVC bitfield
19486 // ABI.
19487 bool CStdConstraintViolation =
19488 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
19489 bool MSBitfieldViolation = Value.ugt(TypeStorageSize) && IsMsStruct;
19490 if (CStdConstraintViolation || MSBitfieldViolation) {
19491 unsigned DiagWidth =
19492 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
19493 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
19494 << (bool)FieldName << FieldName << toString(Value, 10)
19495 << !CStdConstraintViolation << DiagWidth;
19496 }
19497
19498 // Warn on types where the user might conceivably expect to get all
19499 // specified bits as value bits: that's all integral types other than
19500 // 'bool'.
19501 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
19502 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
19503 << FieldName << Value << (unsigned)TypeWidth;
19504 }
19505 }
19506
19507 if (isa<ConstantExpr>(BitWidth))
19508 return BitWidth;
19509 return ConstantExpr::Create(getASTContext(), BitWidth, APValue{Value});
19510}
19511
19513 Declarator &D, Expr *BitfieldWidth) {
19514 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart,
19515 D, BitfieldWidth,
19516 /*InitStyle=*/ICIS_NoInit, AS_public);
19517 return Res;
19518}
19519
19521 SourceLocation DeclStart,
19522 Declarator &D, Expr *BitWidth,
19523 InClassInitStyle InitStyle,
19524 AccessSpecifier AS) {
19525 if (D.isDecompositionDeclarator()) {
19527 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
19528 << Decomp.getSourceRange();
19529 return nullptr;
19530 }
19531
19532 const IdentifierInfo *II = D.getIdentifier();
19533 SourceLocation Loc = DeclStart;
19534 if (II) Loc = D.getIdentifierLoc();
19535
19537 QualType T = TInfo->getType();
19538 if (getLangOpts().CPlusPlus) {
19540
19543 D.setInvalidType();
19544 T = Context.IntTy;
19545 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19546 }
19547 }
19548
19550
19552 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19553 << getLangOpts().CPlusPlus17;
19556 diag::err_invalid_thread)
19558
19559 // Check to see if this name was declared as a member previously
19560 NamedDecl *PrevDecl = nullptr;
19561 LookupResult Previous(*this, II, Loc, LookupMemberName,
19563 LookupName(Previous, S);
19564 switch (Previous.getResultKind()) {
19567 PrevDecl = Previous.getAsSingle<NamedDecl>();
19568 break;
19569
19571 PrevDecl = Previous.getRepresentativeDecl();
19572 break;
19573
19577 break;
19578 }
19579 Previous.suppressDiagnostics();
19580
19581 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19582 // Maybe we will complain about the shadowed template parameter.
19584 // Just pretend that we didn't see the previous declaration.
19585 PrevDecl = nullptr;
19586 }
19587
19588 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19589 PrevDecl = nullptr;
19590
19591 bool Mutable
19592 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
19593 SourceLocation TSSL = D.getBeginLoc();
19594 FieldDecl *NewFD
19595 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
19596 TSSL, AS, PrevDecl, &D);
19597
19598 if (NewFD->isInvalidDecl())
19599 Record->setInvalidDecl();
19600
19602 NewFD->setModulePrivate();
19603
19604 if (NewFD->isInvalidDecl() && PrevDecl) {
19605 // Don't introduce NewFD into scope; there's already something
19606 // with the same name in the same scope.
19607 } else if (II) {
19608 PushOnScopeChains(NewFD, S);
19609 } else
19610 Record->addDecl(NewFD);
19611
19612 return NewFD;
19613}
19614
19616 TypeSourceInfo *TInfo,
19618 bool Mutable, Expr *BitWidth,
19619 InClassInitStyle InitStyle,
19620 SourceLocation TSSL,
19621 AccessSpecifier AS, NamedDecl *PrevDecl,
19622 Declarator *D) {
19623 const IdentifierInfo *II = Name.getAsIdentifierInfo();
19624 bool InvalidDecl = false;
19625 if (D) InvalidDecl = D->isInvalidType();
19626
19627 // If we receive a broken type, recover by assuming 'int' and
19628 // marking this declaration as invalid.
19629 if (T.isNull() || T->containsErrors()) {
19630 InvalidDecl = true;
19631 T = Context.IntTy;
19632 }
19633
19634 QualType EltTy = Context.getBaseElementType(T);
19635 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
19636 bool isIncomplete =
19637 LangOpts.HLSL // HLSL allows sizeless builtin types
19638 ? RequireCompleteType(Loc, EltTy, diag::err_incomplete_type)
19639 : RequireCompleteSizedType(Loc, EltTy,
19640 diag::err_field_incomplete_or_sizeless);
19641 if (isIncomplete) {
19642 // Fields of incomplete type force their record to be invalid.
19643 Record->setInvalidDecl();
19644 InvalidDecl = true;
19645 } else {
19646 NamedDecl *Def;
19647 EltTy->isIncompleteType(&Def);
19648 if (Def && Def->isInvalidDecl()) {
19649 Record->setInvalidDecl();
19650 InvalidDecl = true;
19651 }
19652 }
19653 }
19654
19655 // TR 18037 does not allow fields to be declared with address space
19656 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
19657 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
19658 Diag(Loc, diag::err_field_with_address_space);
19659 Record->setInvalidDecl();
19660 InvalidDecl = true;
19661 }
19662
19663 if (LangOpts.OpenCL) {
19664 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
19665 // used as structure or union field: image, sampler, event or block types.
19666 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
19667 T->isBlockPointerType()) {
19668 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
19669 Record->setInvalidDecl();
19670 InvalidDecl = true;
19671 }
19672 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
19673 // is enabled.
19674 if (BitWidth && !getOpenCLOptions().isAvailableOption(
19675 "__cl_clang_bitfields", LangOpts)) {
19676 Diag(Loc, diag::err_opencl_bitfields);
19677 InvalidDecl = true;
19678 }
19679 }
19680
19681 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
19682 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
19683 T.hasQualifiers()) {
19684 InvalidDecl = true;
19685 Diag(Loc, diag::err_anon_bitfield_qualifiers);
19686 }
19687
19688 // C99 6.7.2.1p8: A member of a structure or union may have any type other
19689 // than a variably modified type.
19690 if (!InvalidDecl && T->isVariablyModifiedType()) {
19692 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
19693 InvalidDecl = true;
19694 }
19695
19696 // Fields can not have abstract class types
19697 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
19698 diag::err_abstract_type_in_decl,
19700 InvalidDecl = true;
19701
19702 if (InvalidDecl)
19703 BitWidth = nullptr;
19704 // If this is declared as a bit-field, check the bit-field.
19705 if (BitWidth) {
19706 BitWidth =
19707 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
19708 if (!BitWidth) {
19709 InvalidDecl = true;
19710 BitWidth = nullptr;
19711 }
19712 }
19713
19714 // Check that 'mutable' is consistent with the type of the declaration.
19715 if (!InvalidDecl && Mutable) {
19716 unsigned DiagID = 0;
19717 if (T->isReferenceType())
19718 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
19719 : diag::err_mutable_reference;
19720 else if (T.isConstQualified())
19721 DiagID = diag::err_mutable_const;
19722
19723 if (DiagID) {
19724 SourceLocation ErrLoc = Loc;
19725 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
19726 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
19727 Diag(ErrLoc, DiagID);
19728 if (DiagID != diag::ext_mutable_reference) {
19729 Mutable = false;
19730 InvalidDecl = true;
19731 }
19732 }
19733 }
19734
19735 // C++11 [class.union]p8 (DR1460):
19736 // At most one variant member of a union may have a
19737 // brace-or-equal-initializer.
19738 if (InitStyle != ICIS_NoInit)
19740
19741 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
19742 BitWidth, Mutable, InitStyle);
19743 if (InvalidDecl)
19744 NewFD->setInvalidDecl();
19745
19746 if (!InvalidDecl)
19748
19749 if (PrevDecl && !isa<TagDecl>(PrevDecl) &&
19750 !PrevDecl->isPlaceholderVar(getLangOpts())) {
19751 Diag(Loc, diag::err_duplicate_member) << II;
19752 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
19753 NewFD->setInvalidDecl();
19754 }
19755
19756 if (!InvalidDecl && getLangOpts().CPlusPlus) {
19757 if (Record->isUnion()) {
19758 if (const auto *RD = EltTy->getAsCXXRecordDecl();
19759 RD && (RD->isBeingDefined() || RD->isCompleteDefinition())) {
19760
19761 // C++ [class.union]p1: An object of a class with a non-trivial
19762 // constructor, a non-trivial copy constructor, a non-trivial
19763 // destructor, or a non-trivial copy assignment operator
19764 // cannot be a member of a union, nor can an array of such
19765 // objects.
19766 if (CheckNontrivialField(NewFD))
19767 NewFD->setInvalidDecl();
19768 }
19769
19770 // C++ [class.union]p1: If a union contains a member of reference type,
19771 // the program is ill-formed, except when compiling with MSVC extensions
19772 // enabled.
19773 if (EltTy->isReferenceType()) {
19774 const bool HaveMSExt =
19775 getLangOpts().MicrosoftExt &&
19777
19778 Diag(NewFD->getLocation(),
19779 HaveMSExt ? diag::ext_union_member_of_reference_type
19780 : diag::err_union_member_of_reference_type)
19781 << NewFD->getDeclName() << EltTy;
19782 if (!HaveMSExt)
19783 NewFD->setInvalidDecl();
19784 }
19785 }
19786 }
19787
19788 // FIXME: We need to pass in the attributes given an AST
19789 // representation, not a parser representation.
19790 if (D) {
19791 // FIXME: The current scope is almost... but not entirely... correct here.
19792 ProcessDeclAttributes(getCurScope(), NewFD, *D);
19793
19794 if (NewFD->hasAttrs())
19796 }
19797
19798 // In auto-retain/release, infer strong retension for fields of
19799 // retainable type.
19800 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(NewFD))
19801 NewFD->setInvalidDecl();
19802
19803 if (T.isObjCGCWeak())
19804 Diag(Loc, diag::warn_attribute_weak_on_field);
19805
19806 // PPC MMA non-pointer types are not allowed as field types.
19807 if (Context.getTargetInfo().getTriple().isPPC64() &&
19808 PPC().CheckPPCMMAType(T, NewFD->getLocation()))
19809 NewFD->setInvalidDecl();
19810
19811 if (Context.getTargetInfo().hasAMDGPUTypes()) {
19812 if (!AMDGPU().checkAMDGPUTypeSupport(T, NewFD->getLocation()))
19813 NewFD->setInvalidDecl();
19814 }
19815
19816 NewFD->setAccess(AS);
19817 return NewFD;
19818}
19819
19821 assert(FD);
19822 assert(getLangOpts().CPlusPlus && "valid check only for C++");
19823
19824 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
19825 return false;
19826
19827 QualType EltTy = Context.getBaseElementType(FD->getType());
19828 if (const auto *RDecl = EltTy->getAsCXXRecordDecl();
19829 RDecl && (RDecl->isBeingDefined() || RDecl->isCompleteDefinition())) {
19830 // We check for copy constructors before constructors
19831 // because otherwise we'll never get complaints about
19832 // copy constructors.
19833
19835 // We're required to check for any non-trivial constructors. Since the
19836 // implicit default constructor is suppressed if there are any
19837 // user-declared constructors, we just need to check that there is a
19838 // trivial default constructor and a trivial copy constructor. (We don't
19839 // worry about move constructors here, since this is a C++98 check.)
19840 if (RDecl->hasNonTrivialCopyConstructor())
19842 else if (!RDecl->hasTrivialDefaultConstructor())
19844 else if (RDecl->hasNonTrivialCopyAssignment())
19846 else if (RDecl->hasNonTrivialDestructor())
19848
19849 if (member != CXXSpecialMemberKind::Invalid) {
19850 if (!getLangOpts().CPlusPlus11 && getLangOpts().ObjCAutoRefCount &&
19851 RDecl->hasObjectMember()) {
19852 // Objective-C++ ARC: it is an error to have a non-trivial field of
19853 // a union. However, system headers in Objective-C programs
19854 // occasionally have Objective-C lifetime objects within unions,
19855 // and rather than cause the program to fail, we make those
19856 // members unavailable.
19857 SourceLocation Loc = FD->getLocation();
19858 if (getSourceManager().isInSystemHeader(Loc)) {
19859 if (!FD->hasAttr<UnavailableAttr>())
19860 FD->addAttr(UnavailableAttr::CreateImplicit(
19861 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
19862 return false;
19863 }
19864 }
19865
19866 Diag(FD->getLocation(),
19868 ? diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member
19869 : diag::err_illegal_union_or_anon_struct_member)
19870 << FD->getParent()->isUnion() << FD->getDeclName() << member;
19871 DiagnoseNontrivial(RDecl, member);
19872 return !getLangOpts().CPlusPlus11;
19873 }
19874 }
19875
19876 return false;
19877}
19878
19880 SmallVectorImpl<Decl *> &AllIvarDecls) {
19881 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
19882 return;
19883
19884 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
19885 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
19886
19887 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField())
19888 return;
19889 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
19890 if (!ID) {
19891 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
19892 if (!CD->IsClassExtension())
19893 return;
19894 }
19895 // No need to add this to end of @implementation.
19896 else
19897 return;
19898 }
19899 // All conditions are met. Add a new bitfield to the tail end of ivars.
19900 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
19901 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
19902 Expr *BitWidth =
19903 ConstantExpr::Create(Context, BW, APValue(llvm::APSInt(Zero)));
19904
19905 Ivar = ObjCIvarDecl::Create(
19906 Context, cast<ObjCContainerDecl>(CurContext), DeclLoc, DeclLoc, nullptr,
19907 Context.CharTy, Context.getTrivialTypeSourceInfo(Context.CharTy, DeclLoc),
19908 ObjCIvarDecl::Private, BitWidth, true);
19909 AllIvarDecls.push_back(Ivar);
19910}
19911
19912/// [class.dtor]p4:
19913/// At the end of the definition of a class, overload resolution is
19914/// performed among the prospective destructors declared in that class with
19915/// an empty argument list to select the destructor for the class, also
19916/// known as the selected destructor.
19917///
19918/// We do the overload resolution here, then mark the selected constructor in the AST.
19919/// Later CXXRecordDecl::getDestructor() will return the selected constructor.
19921 if (!Record->hasUserDeclaredDestructor()) {
19922 return;
19923 }
19924
19925 SourceLocation Loc = Record->getLocation();
19927
19928 for (auto *Decl : Record->decls()) {
19929 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
19930 if (DD->isInvalidDecl())
19931 continue;
19932 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
19933 OCS);
19934 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
19935 }
19936 }
19937
19938 if (OCS.empty()) {
19939 return;
19940 }
19942 unsigned Msg = 0;
19943 OverloadCandidateDisplayKind DisplayKind;
19944
19945 switch (OCS.BestViableFunction(S, Loc, Best)) {
19946 case OR_Success:
19947 case OR_Deleted:
19948 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
19949 break;
19950
19951 case OR_Ambiguous:
19952 Msg = diag::err_ambiguous_destructor;
19953 DisplayKind = OCD_AmbiguousCandidates;
19954 break;
19955
19957 Msg = diag::err_no_viable_destructor;
19958 DisplayKind = OCD_AllCandidates;
19959 break;
19960 }
19961
19962 if (Msg) {
19963 // OpenCL have got their own thing going with destructors. It's slightly broken,
19964 // but we allow it.
19965 if (!S.LangOpts.OpenCL) {
19966 PartialDiagnostic Diag = S.PDiag(Msg) << Record;
19967 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
19968 Record->setInvalidDecl();
19969 }
19970 // It's a bit hacky: At this point we've raised an error but we want the
19971 // rest of the compiler to continue somehow working. However almost
19972 // everything we'll try to do with the class will depend on there being a
19973 // destructor. So let's pretend the first one is selected and hope for the
19974 // best.
19975 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
19976 }
19977}
19978
19979/// [class.mem.special]p5
19980/// Two special member functions are of the same kind if:
19981/// - they are both default constructors,
19982/// - they are both copy or move constructors with the same first parameter
19983/// type, or
19984/// - they are both copy or move assignment operators with the same first
19985/// parameter type and the same cv-qualifiers and ref-qualifier, if any.
19987 CXXMethodDecl *M1,
19988 CXXMethodDecl *M2,
19990 // We don't want to compare templates to non-templates: See
19991 // https://github.com/llvm/llvm-project/issues/59206
19993 return bool(M1->getDescribedFunctionTemplate()) ==
19995 // FIXME: better resolve CWG
19996 // https://cplusplus.github.io/CWG/issues/2787.html
19997 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(),
19998 M2->getNonObjectParameter(0)->getType()))
19999 return false;
20000 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(),
20002 return false;
20003
20004 return true;
20005}
20006
20007/// [class.mem.special]p6:
20008/// An eligible special member function is a special member function for which:
20009/// - the function is not deleted,
20010/// - the associated constraints, if any, are satisfied, and
20011/// - no special member function of the same kind whose associated constraints
20012/// [CWG2595], if any, are satisfied is more constrained.
20016 SmallVector<bool, 4> SatisfactionStatus;
20017
20018 for (CXXMethodDecl *Method : Methods) {
20019 if (!Method->getTrailingRequiresClause())
20020 SatisfactionStatus.push_back(true);
20021 else {
20022 ConstraintSatisfaction Satisfaction;
20023 if (S.CheckFunctionConstraints(Method, Satisfaction))
20024 SatisfactionStatus.push_back(false);
20025 else
20026 SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
20027 }
20028 }
20029
20030 for (size_t i = 0; i < Methods.size(); i++) {
20031 if (!SatisfactionStatus[i])
20032 continue;
20033 CXXMethodDecl *Method = Methods[i];
20034 CXXMethodDecl *OrigMethod = Method;
20035 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
20036 OrigMethod = cast<CXXMethodDecl>(MF);
20037
20039 bool AnotherMethodIsMoreConstrained = false;
20040 for (size_t j = 0; j < Methods.size(); j++) {
20041 if (i == j || !SatisfactionStatus[j])
20042 continue;
20043 CXXMethodDecl *OtherMethod = Methods[j];
20044 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
20045 OtherMethod = cast<CXXMethodDecl>(MF);
20046
20047 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
20048 CSM))
20049 continue;
20050
20052 if (!Other)
20053 continue;
20054 if (!Orig) {
20055 AnotherMethodIsMoreConstrained = true;
20056 break;
20057 }
20058 if (S.IsAtLeastAsConstrained(OtherMethod, {Other}, OrigMethod, {Orig},
20059 AnotherMethodIsMoreConstrained)) {
20060 // There was an error with the constraints comparison. Exit the loop
20061 // and don't consider this function eligible.
20062 AnotherMethodIsMoreConstrained = true;
20063 }
20064 if (AnotherMethodIsMoreConstrained)
20065 break;
20066 }
20067 // FIXME: Do not consider deleted methods as eligible after implementing
20068 // DR1734 and DR1496.
20069 if (!AnotherMethodIsMoreConstrained) {
20070 Method->setIneligibleOrNotSelected(false);
20071 Record->addedEligibleSpecialMemberFunction(Method,
20072 1 << llvm::to_underlying(CSM));
20073 }
20074 }
20075}
20076
20079 SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
20080 SmallVector<CXXMethodDecl *, 4> CopyConstructors;
20081 SmallVector<CXXMethodDecl *, 4> MoveConstructors;
20082 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
20083 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
20084
20085 for (auto *Decl : Record->decls()) {
20086 auto *MD = dyn_cast<CXXMethodDecl>(Decl);
20087 if (!MD) {
20088 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
20089 if (FTD)
20090 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
20091 }
20092 if (!MD)
20093 continue;
20094 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
20095 if (CD->isInvalidDecl())
20096 continue;
20097 if (CD->isDefaultConstructor())
20098 DefaultConstructors.push_back(MD);
20099 else if (CD->isCopyConstructor())
20100 CopyConstructors.push_back(MD);
20101 else if (CD->isMoveConstructor())
20102 MoveConstructors.push_back(MD);
20103 } else if (MD->isCopyAssignmentOperator()) {
20104 CopyAssignmentOperators.push_back(MD);
20105 } else if (MD->isMoveAssignmentOperator()) {
20106 MoveAssignmentOperators.push_back(MD);
20107 }
20108 }
20109
20110 SetEligibleMethods(S, Record, DefaultConstructors,
20112 SetEligibleMethods(S, Record, CopyConstructors,
20114 SetEligibleMethods(S, Record, MoveConstructors,
20116 SetEligibleMethods(S, Record, CopyAssignmentOperators,
20118 SetEligibleMethods(S, Record, MoveAssignmentOperators,
20120}
20121
20122bool Sema::EntirelyFunctionPointers(const RecordDecl *Record) {
20123 // Check to see if a FieldDecl is a pointer to a function.
20124 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
20125 const FieldDecl *FD = dyn_cast<FieldDecl>(D);
20126 if (!FD) {
20127 // Check whether this is a forward declaration that was inserted by
20128 // Clang. This happens when a non-forward declared / defined type is
20129 // used, e.g.:
20130 //
20131 // struct foo {
20132 // struct bar *(*f)();
20133 // struct bar *(*g)();
20134 // };
20135 //
20136 // "struct bar" shows up in the decl AST as a "RecordDecl" with an
20137 // incomplete definition.
20138 if (const auto *TD = dyn_cast<TagDecl>(D))
20139 return !TD->isCompleteDefinition();
20140 return false;
20141 }
20142 QualType FieldType = FD->getType().getDesugaredType(Context);
20143 if (isa<PointerType>(FieldType)) {
20144 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
20145 return PointeeType.getDesugaredType(Context)->isFunctionType();
20146 }
20147 // If a member is a struct entirely of function pointers, that counts too.
20148 if (const auto *Record = FieldType->getAsRecordDecl();
20149 Record && Record->isStruct() && EntirelyFunctionPointers(Record))
20150 return true;
20151 return false;
20152 };
20153
20154 return llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl);
20155}
20156
20157void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
20158 ArrayRef<Decl *> Fields, SourceLocation LBrac,
20159 SourceLocation RBrac,
20160 const ParsedAttributesView &Attrs) {
20161 assert(EnclosingDecl && "missing record or interface decl");
20162
20163 // If this is an Objective-C @implementation or category and we have
20164 // new fields here we should reset the layout of the interface since
20165 // it will now change.
20166 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
20167 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
20168 switch (DC->getKind()) {
20169 default: break;
20170 case Decl::ObjCCategory:
20171 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
20172 break;
20173 case Decl::ObjCImplementation:
20174 Context.
20175 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
20176 break;
20177 }
20178 }
20179
20180 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
20181 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
20182
20183 // Start counting up the number of named members; make sure to include
20184 // members of anonymous structs and unions in the total.
20185 unsigned NumNamedMembers = 0;
20186 if (Record) {
20187 for (const auto *I : Record->decls()) {
20188 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
20189 if (IFD->getDeclName())
20190 ++NumNamedMembers;
20191 }
20192 }
20193
20194 // Verify that all the fields are okay.
20196 const FieldDecl *PreviousField = nullptr;
20197 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
20198 i != end; PreviousField = cast<FieldDecl>(*i), ++i) {
20199 FieldDecl *FD = cast<FieldDecl>(*i);
20200
20201 // Get the type for the field.
20202 const Type *FDTy = FD->getType().getTypePtr();
20203
20204 if (!FD->isAnonymousStructOrUnion()) {
20205 // Remember all fields written by the user.
20206 RecFields.push_back(FD);
20207 }
20208
20209 // If the field is already invalid for some reason, don't emit more
20210 // diagnostics about it.
20211 if (FD->isInvalidDecl()) {
20212 EnclosingDecl->setInvalidDecl();
20213 continue;
20214 }
20215
20216 // C99 6.7.2.1p2:
20217 // A structure or union shall not contain a member with
20218 // incomplete or function type (hence, a structure shall not
20219 // contain an instance of itself, but may contain a pointer to
20220 // an instance of itself), except that the last member of a
20221 // structure with more than one named member may have incomplete
20222 // array type; such a structure (and any union containing,
20223 // possibly recursively, a member that is such a structure)
20224 // shall not be a member of a structure or an element of an
20225 // array.
20226 bool IsLastField = (i + 1 == Fields.end());
20227 if (FDTy->isFunctionType()) {
20228 // Field declared as a function.
20229 Diag(FD->getLocation(), diag::err_field_declared_as_function)
20230 << FD->getDeclName();
20231 FD->setInvalidDecl();
20232 EnclosingDecl->setInvalidDecl();
20233 continue;
20234 } else if (FDTy->isIncompleteArrayType() &&
20235 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
20236 if (Record) {
20237 // Flexible array member.
20238 // Microsoft and g++ is more permissive regarding flexible array.
20239 // It will accept flexible array in union and also
20240 // as the sole element of a struct/class.
20241 unsigned DiagID = 0;
20242 if (!Record->isUnion() && !IsLastField) {
20243 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
20244 << FD->getDeclName() << FD->getType() << Record->getTagKind();
20245 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
20246 FD->setInvalidDecl();
20247 EnclosingDecl->setInvalidDecl();
20248 continue;
20249 } else if (Record->isUnion())
20250 DiagID = getLangOpts().MicrosoftExt
20251 ? diag::ext_flexible_array_union_ms
20252 : diag::ext_flexible_array_union_gnu;
20253 else if (NumNamedMembers < 1)
20254 DiagID = getLangOpts().MicrosoftExt
20255 ? diag::ext_flexible_array_empty_aggregate_ms
20256 : diag::ext_flexible_array_empty_aggregate_gnu;
20257
20258 if (DiagID)
20259 Diag(FD->getLocation(), DiagID)
20260 << FD->getDeclName() << Record->getTagKind();
20261 // While the layout of types that contain virtual bases is not specified
20262 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
20263 // virtual bases after the derived members. This would make a flexible
20264 // array member declared at the end of an object not adjacent to the end
20265 // of the type.
20266 if (CXXRecord && CXXRecord->getNumVBases() != 0)
20267 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
20268 << FD->getDeclName() << Record->getTagKind();
20269 if (!getLangOpts().C99)
20270 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
20271 << FD->getDeclName() << Record->getTagKind();
20272
20273 // If the element type has a non-trivial destructor, we would not
20274 // implicitly destroy the elements, so disallow it for now.
20275 //
20276 // FIXME: GCC allows this. We should probably either implicitly delete
20277 // the destructor of the containing class, or just allow this.
20278 QualType BaseElem = Context.getBaseElementType(FD->getType());
20279 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
20280 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
20281 << FD->getDeclName() << FD->getType();
20282 FD->setInvalidDecl();
20283 EnclosingDecl->setInvalidDecl();
20284 continue;
20285 }
20286 // Okay, we have a legal flexible array member at the end of the struct.
20287 Record->setHasFlexibleArrayMember(true);
20288 } else {
20289 // In ObjCContainerDecl ivars with incomplete array type are accepted,
20290 // unless they are followed by another ivar. That check is done
20291 // elsewhere, after synthesized ivars are known.
20292 }
20293 } else if (!FDTy->isDependentType() &&
20294 (LangOpts.HLSL // HLSL allows sizeless builtin types
20296 diag::err_incomplete_type)
20298 FD->getLocation(), FD->getType(),
20299 diag::err_field_incomplete_or_sizeless))) {
20300 // Incomplete type
20301 FD->setInvalidDecl();
20302 EnclosingDecl->setInvalidDecl();
20303 continue;
20304 } else if (const auto *RD = FDTy->getAsRecordDecl()) {
20305 if (Record && RD->hasFlexibleArrayMember()) {
20306 // A type which contains a flexible array member is considered to be a
20307 // flexible array member.
20308 Record->setHasFlexibleArrayMember(true);
20309 if (!Record->isUnion()) {
20310 // If this is a struct/class and this is not the last element, reject
20311 // it. Note that GCC supports variable sized arrays in the middle of
20312 // structures.
20313 if (!IsLastField)
20314 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
20315 << FD->getDeclName() << FD->getType();
20316 else {
20317 // We support flexible arrays at the end of structs in
20318 // other structs as an extension.
20319 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
20320 << FD->getDeclName();
20321 }
20322 }
20323 }
20324 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
20326 diag::err_abstract_type_in_decl,
20328 // Ivars can not have abstract class types
20329 FD->setInvalidDecl();
20330 }
20331 if (Record && RD->hasObjectMember())
20332 Record->setHasObjectMember(true);
20333 if (Record && RD->hasVolatileMember())
20334 Record->setHasVolatileMember(true);
20335 } else if (FDTy->isObjCObjectType()) {
20336 /// A field cannot be an Objective-c object
20337 Diag(FD->getLocation(), diag::err_statically_allocated_object)
20339 QualType T = Context.getObjCObjectPointerType(FD->getType());
20340 FD->setType(T);
20341 } else if (Record && Record->isUnion() &&
20343 getSourceManager().isInSystemHeader(FD->getLocation()) &&
20344 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
20346 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
20347 // For backward compatibility, fields of C unions declared in system
20348 // headers that have non-trivial ObjC ownership qualifications are marked
20349 // as unavailable unless the qualifier is explicit and __strong. This can
20350 // break ABI compatibility between programs compiled with ARC and MRR, but
20351 // is a better option than rejecting programs using those unions under
20352 // ARC.
20353 FD->addAttr(UnavailableAttr::CreateImplicit(
20354 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
20355 FD->getLocation()));
20356 } else if (getLangOpts().ObjC &&
20357 getLangOpts().getGC() != LangOptions::NonGC && Record &&
20358 !Record->hasObjectMember()) {
20359 if (FD->getType()->isObjCObjectPointerType() ||
20360 FD->getType().isObjCGCStrong())
20361 Record->setHasObjectMember(true);
20362 else if (Context.getAsArrayType(FD->getType())) {
20363 QualType BaseType = Context.getBaseElementType(FD->getType());
20364 if (const auto *RD = BaseType->getAsRecordDecl();
20365 RD && RD->hasObjectMember())
20366 Record->setHasObjectMember(true);
20367 else if (BaseType->isObjCObjectPointerType() ||
20368 BaseType.isObjCGCStrong())
20369 Record->setHasObjectMember(true);
20370 }
20371 }
20372
20373 if (Record && !getLangOpts().CPlusPlus &&
20374 !shouldIgnoreForRecordTriviality(FD)) {
20375 QualType FT = FD->getType();
20377 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
20379 Record->isUnion())
20380 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
20381 }
20384 Record->setNonTrivialToPrimitiveCopy(true);
20385 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
20386 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
20387 }
20388 if (FD->hasAttr<ExplicitInitAttr>())
20389 Record->setHasUninitializedExplicitInitFields(true);
20390 if (FT.isDestructedType()) {
20391 Record->setNonTrivialToPrimitiveDestroy(true);
20392 Record->setParamDestroyedInCallee(true);
20393 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
20394 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
20395 }
20396
20397 if (const auto *RD = FT->getAsRecordDecl()) {
20398 if (RD->getArgPassingRestrictions() ==
20400 Record->setArgPassingRestrictions(
20402 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) {
20403 Record->setArgPassingRestrictions(
20405 } else if (PointerAuthQualifier Q = FT.getPointerAuth();
20406 Q && Q.isAddressDiscriminated()) {
20407 Record->setArgPassingRestrictions(
20409 Record->setNonTrivialToPrimitiveCopy(true);
20410 }
20411 }
20412
20413 if (Record && FD->getType().isVolatileQualified())
20414 Record->setHasVolatileMember(true);
20415 bool ReportMSBitfieldStoragePacking =
20416 Record && PreviousField &&
20417 !Diags.isIgnored(diag::warn_ms_bitfield_mismatched_storage_packing,
20418 Record->getLocation());
20419 auto IsNonDependentBitField = [](const FieldDecl *FD) {
20420 return FD->isBitField() && !FD->getType()->isDependentType();
20421 };
20422
20423 if (ReportMSBitfieldStoragePacking && IsNonDependentBitField(FD) &&
20424 IsNonDependentBitField(PreviousField)) {
20425 CharUnits FDStorageSize = Context.getTypeSizeInChars(FD->getType());
20426 CharUnits PreviousFieldStorageSize =
20427 Context.getTypeSizeInChars(PreviousField->getType());
20428 if (FDStorageSize != PreviousFieldStorageSize) {
20429 Diag(FD->getLocation(),
20430 diag::warn_ms_bitfield_mismatched_storage_packing)
20431 << FD << FD->getType() << FDStorageSize.getQuantity()
20432 << PreviousFieldStorageSize.getQuantity();
20433 Diag(PreviousField->getLocation(),
20434 diag::note_ms_bitfield_mismatched_storage_size_previous)
20435 << PreviousField << PreviousField->getType();
20436 }
20437 }
20438 // Keep track of the number of named members.
20439 if (FD->getIdentifier())
20440 ++NumNamedMembers;
20441 }
20442
20443 // Okay, we successfully defined 'Record'.
20444 if (Record) {
20445 bool Completed = false;
20446 if (S) {
20447 Scope *Parent = S->getParent();
20448 if (Parent && Parent->isTypeAliasScope() &&
20449 Parent->isTemplateParamScope())
20450 Record->setInvalidDecl();
20451 }
20452
20453 if (CXXRecord) {
20454 if (!CXXRecord->isInvalidDecl()) {
20455 // Set access bits correctly on the directly-declared conversions.
20457 I = CXXRecord->conversion_begin(),
20458 E = CXXRecord->conversion_end(); I != E; ++I)
20459 I.setAccess((*I)->getAccess());
20460 }
20461
20462 // Add any implicitly-declared members to this class.
20464
20465 if (!CXXRecord->isDependentType()) {
20466 if (!CXXRecord->isInvalidDecl()) {
20467 // If we have virtual base classes, we may end up finding multiple
20468 // final overriders for a given virtual function. Check for this
20469 // problem now.
20470 if (CXXRecord->getNumVBases()) {
20471 CXXFinalOverriderMap FinalOverriders;
20472 CXXRecord->getFinalOverriders(FinalOverriders);
20473
20474 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
20475 MEnd = FinalOverriders.end();
20476 M != MEnd; ++M) {
20477 for (OverridingMethods::iterator SO = M->second.begin(),
20478 SOEnd = M->second.end();
20479 SO != SOEnd; ++SO) {
20480 assert(SO->second.size() > 0 &&
20481 "Virtual function without overriding functions?");
20482 if (SO->second.size() == 1)
20483 continue;
20484
20485 // C++ [class.virtual]p2:
20486 // In a derived class, if a virtual member function of a base
20487 // class subobject has more than one final overrider the
20488 // program is ill-formed.
20489 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
20490 << (const NamedDecl *)M->first << Record;
20491 Diag(M->first->getLocation(),
20492 diag::note_overridden_virtual_function);
20494 OM = SO->second.begin(),
20495 OMEnd = SO->second.end();
20496 OM != OMEnd; ++OM)
20497 Diag(OM->Method->getLocation(), diag::note_final_overrider)
20498 << (const NamedDecl *)M->first << OM->Method->getParent();
20499
20500 Record->setInvalidDecl();
20501 }
20502 }
20503 CXXRecord->completeDefinition(&FinalOverriders);
20504 Completed = true;
20505 }
20506 }
20507 ComputeSelectedDestructor(*this, CXXRecord);
20509 }
20510 }
20511
20512 if (!Completed)
20513 Record->completeDefinition();
20514
20515 // Handle attributes before checking the layout.
20517
20518 // Maybe randomize the record's decls. We automatically randomize a record
20519 // of function pointers, unless it has the "no_randomize_layout" attribute.
20520 if (!getLangOpts().CPlusPlus && !getLangOpts().RandstructSeed.empty() &&
20521 !Record->isRandomized() && !Record->isUnion() &&
20522 (Record->hasAttr<RandomizeLayoutAttr>() ||
20523 (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
20524 EntirelyFunctionPointers(Record)))) {
20525 SmallVector<Decl *, 32> NewDeclOrdering;
20527 NewDeclOrdering))
20528 Record->reorderDecls(NewDeclOrdering);
20529 }
20530
20531 // We may have deferred checking for a deleted destructor. Check now.
20532 if (CXXRecord) {
20533 auto *Dtor = CXXRecord->getDestructor();
20534 if (Dtor && Dtor->isImplicit() &&
20536 CXXRecord->setImplicitDestructorIsDeleted();
20537 SetDeclDeleted(Dtor, CXXRecord->getLocation());
20538 }
20539 }
20540
20541 if (Record->hasAttrs()) {
20543
20544 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
20546 IA->getRange(), IA->getBestCase(),
20547 IA->getInheritanceModel());
20548 }
20549
20550 // Check if the structure/union declaration is a type that can have zero
20551 // size in C. For C this is a language extension, for C++ it may cause
20552 // compatibility problems.
20553 bool CheckForZeroSize;
20554 if (!getLangOpts().CPlusPlus) {
20555 CheckForZeroSize = true;
20556 } else {
20557 // For C++ filter out types that cannot be referenced in C code.
20559 CheckForZeroSize =
20560 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
20561 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
20562 CXXRecord->isCLike();
20563 }
20564 if (CheckForZeroSize) {
20565 bool ZeroSize = true;
20566 bool IsEmpty = true;
20567 unsigned NonBitFields = 0;
20568 for (RecordDecl::field_iterator I = Record->field_begin(),
20569 E = Record->field_end();
20570 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
20571 IsEmpty = false;
20572 if (I->isUnnamedBitField()) {
20573 if (!I->isZeroLengthBitField())
20574 ZeroSize = false;
20575 } else {
20576 ++NonBitFields;
20577 QualType FieldType = I->getType();
20578 if (FieldType->isIncompleteType() ||
20579 !Context.getTypeSizeInChars(FieldType).isZero())
20580 ZeroSize = false;
20581 }
20582 }
20583
20584 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
20585 // allowed in C++, but warn if its declaration is inside
20586 // extern "C" block.
20587 if (ZeroSize) {
20588 Diag(RecLoc, getLangOpts().CPlusPlus ?
20589 diag::warn_zero_size_struct_union_in_extern_c :
20590 diag::warn_zero_size_struct_union_compat)
20591 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
20592 }
20593
20594 // Structs without named members are extension in C (C99 6.7.2.1p7),
20595 // but are accepted by GCC. In C2y, this became implementation-defined
20596 // (C2y 6.7.3.2p10).
20597 if (NonBitFields == 0 && !getLangOpts().CPlusPlus && !getLangOpts().C2y) {
20598 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union
20599 : diag::ext_no_named_members_in_struct_union)
20600 << Record->isUnion();
20601 }
20602 }
20603 } else {
20604 ObjCIvarDecl **ClsFields =
20605 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
20606 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
20607 ID->setEndOfDefinitionLoc(RBrac);
20608 // Add ivar's to class's DeclContext.
20609 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20610 ClsFields[i]->setLexicalDeclContext(ID);
20611 ID->addDecl(ClsFields[i]);
20612 }
20613 // Must enforce the rule that ivars in the base classes may not be
20614 // duplicates.
20615 if (ID->getSuperClass())
20616 ObjC().DiagnoseDuplicateIvars(ID, ID->getSuperClass());
20617 } else if (ObjCImplementationDecl *IMPDecl =
20618 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
20619 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
20620 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
20621 // Ivar declared in @implementation never belongs to the implementation.
20622 // Only it is in implementation's lexical context.
20623 ClsFields[I]->setLexicalDeclContext(IMPDecl);
20624 ObjC().CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(),
20625 RBrac);
20626 IMPDecl->setIvarLBraceLoc(LBrac);
20627 IMPDecl->setIvarRBraceLoc(RBrac);
20628 } else if (ObjCCategoryDecl *CDecl =
20629 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
20630 // case of ivars in class extension; all other cases have been
20631 // reported as errors elsewhere.
20632 // FIXME. Class extension does not have a LocEnd field.
20633 // CDecl->setLocEnd(RBrac);
20634 // Add ivar's to class extension's DeclContext.
20635 // Diagnose redeclaration of private ivars.
20636 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
20637 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
20638 if (IDecl) {
20639 if (const ObjCIvarDecl *ClsIvar =
20640 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
20641 Diag(ClsFields[i]->getLocation(),
20642 diag::err_duplicate_ivar_declaration);
20643 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
20644 continue;
20645 }
20646 for (const auto *Ext : IDecl->known_extensions()) {
20647 if (const ObjCIvarDecl *ClsExtIvar
20648 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
20649 Diag(ClsFields[i]->getLocation(),
20650 diag::err_duplicate_ivar_declaration);
20651 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
20652 continue;
20653 }
20654 }
20655 }
20656 ClsFields[i]->setLexicalDeclContext(CDecl);
20657 CDecl->addDecl(ClsFields[i]);
20658 }
20659 CDecl->setIvarLBraceLoc(LBrac);
20660 CDecl->setIvarRBraceLoc(RBrac);
20661 }
20662 }
20663
20664 if (Record)
20666
20669}
20670
20671// Given an integral type, return the next larger integral type
20672// (or a NULL type of no such type exists).
20674 // FIXME: Int128/UInt128 support, which also needs to be introduced into
20675 // enum checking below.
20676 assert((T->isIntegralType(Context) ||
20677 T->isEnumeralType()) && "Integral type required!");
20678 const unsigned NumTypes = 4;
20679 QualType SignedIntegralTypes[NumTypes] = {
20680 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
20681 };
20682 QualType UnsignedIntegralTypes[NumTypes] = {
20683 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
20684 Context.UnsignedLongLongTy
20685 };
20686
20687 // Compare value widths, not storage sizes: a _BitInt(33) is stored in 64
20688 // bits but a 64-bit standard type can still represent its incremented
20689 // value. C23 6.7.3.3p12 does not allow the widened type to be a
20690 // bit-precise type either.
20691 unsigned BitWidth = Context.getIntWidth(T);
20692 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
20693 : UnsignedIntegralTypes;
20694 for (unsigned I = 0; I != NumTypes; ++I)
20695 if (Context.getTypeSize(Types[I]) > BitWidth)
20696 return Types[I];
20697
20698 return QualType();
20699}
20700
20702 EnumConstantDecl *LastEnumConst,
20703 SourceLocation IdLoc,
20704 IdentifierInfo *Id,
20705 Expr *Val) {
20706 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
20707 llvm::APSInt EnumVal(IntWidth);
20708 QualType EltTy;
20709
20711 Val = nullptr;
20712
20713 if (Val)
20714 Val = DefaultLvalueConversion(Val).get();
20715
20716 if (Val) {
20717 if (Enum->isDependentType() || Val->isTypeDependent() ||
20718 Val->containsErrors())
20719 EltTy = Context.DependentTy;
20720 else {
20721 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
20722 // underlying type, but do allow it in all other contexts.
20723 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
20724 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
20725 // constant-expression in the enumerator-definition shall be a converted
20726 // constant expression of the underlying type.
20727 EltTy = Enum->getIntegerType();
20729 Val, EltTy, EnumVal, CCEKind::Enumerator);
20730 if (Converted.isInvalid())
20731 Val = nullptr;
20732 else
20733 Val = Converted.get();
20734 } else if (!Val->isValueDependent() &&
20735 !(Val = VerifyIntegerConstantExpression(Val, &EnumVal,
20737 .get())) {
20738 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
20739 } else {
20740 if (Enum->isComplete()) {
20741 EltTy = Enum->getIntegerType();
20742
20743 // In Obj-C and Microsoft mode, require the enumeration value to be
20744 // representable in the underlying type of the enumeration. In C++11,
20745 // we perform a non-narrowing conversion as part of converted constant
20746 // expression checking.
20747 if (!Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20748 if (Context.getTargetInfo()
20749 .getTriple()
20750 .isWindowsMSVCEnvironment()) {
20751 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
20752 } else {
20753 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
20754 }
20755 }
20756
20757 // Cast to the underlying type.
20758 Val = ImpCastExprToType(Val, EltTy,
20759 EltTy->isBooleanType() ? CK_IntegralToBoolean
20760 : CK_IntegralCast)
20761 .get();
20762 } else if (getLangOpts().CPlusPlus) {
20763 // C++11 [dcl.enum]p5:
20764 // If the underlying type is not fixed, the type of each enumerator
20765 // is the type of its initializing value:
20766 // - If an initializer is specified for an enumerator, the
20767 // initializing value has the same type as the expression.
20768 EltTy = Val->getType();
20769 } else {
20770 // C99 6.7.2.2p2:
20771 // The expression that defines the value of an enumeration constant
20772 // shall be an integer constant expression that has a value
20773 // representable as an int.
20774
20775 // Complain if the value is not representable in an int.
20776 if (!Context.isRepresentableIntegerValue(EnumVal, Context.IntTy)) {
20777 Diag(IdLoc, getLangOpts().C23
20778 ? diag::warn_c17_compat_enum_value_not_int
20779 : diag::ext_c23_enum_value_not_int)
20780 << 0 << toString(EnumVal, 10) << Val->getSourceRange()
20781 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
20782 } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
20783 // Force the type of the expression to 'int'.
20784 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
20785 }
20786 EltTy = Val->getType();
20787 }
20788 }
20789 }
20790 }
20791
20792 if (!Val) {
20793 if (Enum->isDependentType())
20794 EltTy = Context.DependentTy;
20795 else if (!LastEnumConst) {
20796 // C++0x [dcl.enum]p5:
20797 // If the underlying type is not fixed, the type of each enumerator
20798 // is the type of its initializing value:
20799 // - If no initializer is specified for the first enumerator, the
20800 // initializing value has an unspecified integral type.
20801 //
20802 // GCC uses 'int' for its unspecified integral type, as does
20803 // C99 6.7.2.2p3.
20804 if (Enum->isFixed()) {
20805 EltTy = Enum->getIntegerType();
20806 }
20807 else {
20808 EltTy = Context.IntTy;
20809 }
20810 } else {
20811 // Assign the last value + 1.
20812 EnumVal = LastEnumConst->getInitVal();
20813 ++EnumVal;
20814 EltTy = LastEnumConst->getType();
20815
20816 // Check for overflow on increment.
20817 if (EnumVal < LastEnumConst->getInitVal()) {
20818 // C++0x [dcl.enum]p5:
20819 // If the underlying type is not fixed, the type of each enumerator
20820 // is the type of its initializing value:
20821 //
20822 // - Otherwise the type of the initializing value is the same as
20823 // the type of the initializing value of the preceding enumerator
20824 // unless the incremented value is not representable in that type,
20825 // in which case the type is an unspecified integral type
20826 // sufficient to contain the incremented value. If no such type
20827 // exists, the program is ill-formed.
20829 if (T.isNull() || Enum->isFixed()) {
20830 // There is no integral type larger enough to represent this
20831 // value. Complain, then allow the value to wrap around.
20832 EnumVal = LastEnumConst->getInitVal();
20833 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
20834 ++EnumVal;
20835 if (Enum->isFixed())
20836 // When the underlying type is fixed, this is ill-formed.
20837 Diag(IdLoc, diag::err_enumerator_wrapped)
20838 << toString(EnumVal, 10)
20839 << EltTy;
20840 else
20841 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
20842 << toString(EnumVal, 10);
20843 } else {
20844 EltTy = T;
20845 }
20846
20847 // Retrieve the last enumerator's value, extent that type to the
20848 // type that is supposed to be large enough to represent the incremented
20849 // value, then increment.
20850 EnumVal = LastEnumConst->getInitVal();
20851 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20852 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
20853 ++EnumVal;
20854
20855 // If we're not in C++, diagnose the overflow of enumerator values,
20856 // which in C99 means that the enumerator value is not representable in
20857 // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
20858 // are representable in some larger integral type and we allow it in
20859 // older language modes as an extension.
20860 // Exclude fixed enumerators since they are diagnosed with an error for
20861 // this case.
20862 if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
20863 Diag(IdLoc, getLangOpts().C23
20864 ? diag::warn_c17_compat_enum_value_not_int
20865 : diag::ext_c23_enum_value_not_int)
20866 << 1 << toString(EnumVal, 10) << 1;
20867 } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
20868 !Context.isRepresentableIntegerValue(EnumVal, EltTy)) {
20869 // Enforce C99 6.7.2.2p2 even when we compute the next value.
20870 Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
20871 : diag::ext_c23_enum_value_not_int)
20872 << 1 << toString(EnumVal, 10) << 1;
20873 }
20874 }
20875 }
20876
20877 if (!EltTy->isDependentType()) {
20878 // Make the enumerator value match the signedness and size of the
20879 // enumerator's type.
20880 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
20881 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
20882 }
20883
20884 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
20885 Val, EnumVal);
20886}
20887
20889 SourceLocation IILoc) {
20890 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
20892 return SkipBodyInfo();
20893
20894 // We have an anonymous enum definition. Look up the first enumerator to
20895 // determine if we should merge the definition with an existing one and
20896 // skip the body.
20897 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
20899 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
20900 if (!PrevECD)
20901 return SkipBodyInfo();
20902
20903 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
20904 NamedDecl *Hidden;
20905 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
20907 Skip.Previous = Hidden;
20908 return Skip;
20909 }
20910
20911 return SkipBodyInfo();
20912}
20913
20914Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
20915 SourceLocation IdLoc, IdentifierInfo *Id,
20916 const ParsedAttributesView &Attrs,
20917 SourceLocation EqualLoc, Expr *Val,
20918 SkipBodyInfo *SkipBody) {
20919 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
20920 EnumConstantDecl *LastEnumConst =
20921 cast_or_null<EnumConstantDecl>(lastEnumConst);
20922
20923 // The scope passed in may not be a decl scope. Zip up the scope tree until
20924 // we find one that is.
20925 S = getNonFieldDeclScope(S);
20926
20927 // Verify that there isn't already something declared with this name in this
20928 // scope.
20929 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName,
20931 LookupName(R, S);
20932 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
20933
20934 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20935 // Maybe we will complain about the shadowed template parameter.
20936 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
20937 // Just pretend that we didn't see the previous declaration.
20938 PrevDecl = nullptr;
20939 }
20940
20941 // C++ [class.mem]p15:
20942 // If T is the name of a class, then each of the following shall have a name
20943 // different from T:
20944 // - every enumerator of every member of class T that is an unscoped
20945 // enumerated type
20946 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped() &&
20948 DeclarationNameInfo(Id, IdLoc)))
20949 return nullptr;
20950
20952 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
20953 if (!New)
20954 return nullptr;
20955
20956 if (PrevDecl && (!SkipBody || !SkipBody->CheckSameAsPrevious)) {
20957 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
20958 // Check for other kinds of shadowing not already handled.
20959 CheckShadow(New, PrevDecl, R);
20960 }
20961
20962 // When in C++, we may get a TagDecl with the same name; in this case the
20963 // enum constant will 'hide' the tag.
20964 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
20965 "Received TagDecl when not in C++!");
20966 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
20967 if (isa<EnumConstantDecl>(PrevDecl))
20968 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
20969 else
20970 Diag(IdLoc, diag::err_redefinition) << Id;
20971 notePreviousDefinition(PrevDecl, IdLoc);
20972 return nullptr;
20973 }
20974 }
20975
20976 // Process attributes.
20977 ProcessDeclAttributeList(S, New, Attrs);
20980
20981 // Register this decl in the current scope stack.
20982 New->setAccess(TheEnumDecl->getAccess());
20984
20986
20987 return New;
20988}
20989
20990// Returns true when the enum initial expression does not trigger the
20991// duplicate enum warning. A few common cases are exempted as follows:
20992// Element2 = Element1
20993// Element2 = Element1 + 1
20994// Element2 = Element1 - 1
20995// Where Element2 and Element1 are from the same enum.
20997 Expr *InitExpr = ECD->getInitExpr();
20998 if (!InitExpr)
20999 return true;
21000 InitExpr = InitExpr->IgnoreImpCasts();
21001
21002 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
21003 if (!BO->isAdditiveOp())
21004 return true;
21005 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
21006 if (!IL)
21007 return true;
21008 if (IL->getValue() != 1)
21009 return true;
21010
21011 InitExpr = BO->getLHS();
21012 }
21013
21014 // This checks if the elements are from the same enum.
21015 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
21016 if (!DRE)
21017 return true;
21018
21019 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
21020 if (!EnumConstant)
21021 return true;
21022
21024 Enum)
21025 return true;
21026
21027 return false;
21028}
21029
21030// Emits a warning when an element is implicitly set a value that
21031// a previous element has already been set to.
21033 EnumDecl *Enum, QualType EnumType) {
21034 // Avoid anonymous enums
21035 if (!Enum->getIdentifier())
21036 return;
21037
21038 // Only check for small enums.
21039 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
21040 return;
21041
21042 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
21043 return;
21044
21045 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
21046 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
21047
21048 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
21049
21050 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
21051 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
21052
21053 // Use int64_t as a key to avoid needing special handling for map keys.
21054 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
21055 llvm::APSInt Val = D->getInitVal();
21056 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
21057 };
21058
21059 DuplicatesVector DupVector;
21060 ValueToVectorMap EnumMap;
21061
21062 // Populate the EnumMap with all values represented by enum constants without
21063 // an initializer.
21064 for (auto *Element : Elements) {
21065 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
21066
21067 // Null EnumConstantDecl means a previous diagnostic has been emitted for
21068 // this constant. Skip this enum since it may be ill-formed.
21069 if (!ECD) {
21070 return;
21071 }
21072
21073 // Constants with initializers are handled in the next loop.
21074 if (ECD->getInitExpr())
21075 continue;
21076
21077 // Duplicate values are handled in the next loop.
21078 EnumMap.insert({EnumConstantToKey(ECD), ECD});
21079 }
21080
21081 if (EnumMap.size() == 0)
21082 return;
21083
21084 // Create vectors for any values that has duplicates.
21085 for (auto *Element : Elements) {
21086 // The last loop returned if any constant was null.
21088 if (!ValidDuplicateEnum(ECD, Enum))
21089 continue;
21090
21091 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
21092 if (Iter == EnumMap.end())
21093 continue;
21094
21095 DeclOrVector& Entry = Iter->second;
21096 if (EnumConstantDecl *D = dyn_cast<EnumConstantDecl *>(Entry)) {
21097 // Ensure constants are different.
21098 if (D == ECD)
21099 continue;
21100
21101 // Create new vector and push values onto it.
21102 auto Vec = std::make_unique<ECDVector>();
21103 Vec->push_back(D);
21104 Vec->push_back(ECD);
21105
21106 // Update entry to point to the duplicates vector.
21107 Entry = Vec.get();
21108
21109 // Store the vector somewhere we can consult later for quick emission of
21110 // diagnostics.
21111 DupVector.emplace_back(std::move(Vec));
21112 continue;
21113 }
21114
21115 ECDVector *Vec = cast<ECDVector *>(Entry);
21116 // Make sure constants are not added more than once.
21117 if (*Vec->begin() == ECD)
21118 continue;
21119
21120 Vec->push_back(ECD);
21121 }
21122
21123 // Emit diagnostics.
21124 for (const auto &Vec : DupVector) {
21125 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
21126
21127 // Emit warning for one enum constant.
21128 auto *FirstECD = Vec->front();
21129 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
21130 << FirstECD << toString(FirstECD->getInitVal(), 10)
21131 << FirstECD->getSourceRange();
21132
21133 // Emit one note for each of the remaining enum constants with
21134 // the same value.
21135 for (auto *ECD : llvm::drop_begin(*Vec))
21136 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
21137 << ECD << toString(ECD->getInitVal(), 10)
21138 << ECD->getSourceRange();
21139 }
21140}
21141
21142bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
21143 bool AllowMask) const {
21144 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
21145 assert(ED->isCompleteDefinition() && "expected enum definition");
21146
21147 auto R = FlagBitsCache.try_emplace(ED);
21148 llvm::APInt &FlagBits = R.first->second;
21149
21150 if (R.second) {
21151 for (auto *E : ED->enumerators()) {
21152 const auto &EVal = E->getInitVal();
21153 // Only single-bit enumerators introduce new flag values.
21154 if (EVal.isPowerOf2())
21155 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
21156 }
21157 }
21158
21159 // A value is in a flag enum if either its bits are a subset of the enum's
21160 // flag bits (the first condition) or we are allowing masks and the same is
21161 // true of its complement (the second condition). When masks are allowed, we
21162 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
21163 //
21164 // While it's true that any value could be used as a mask, the assumption is
21165 // that a mask will have all of the insignificant bits set. Anything else is
21166 // likely a logic error.
21167 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
21168 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
21169}
21170
21171// Emits a warning when a suspicious comparison operator is used along side
21172// binary operators in enum initializers.
21174 const EnumDecl *Enum) {
21175 bool HasBitwiseOp = false;
21176 SmallVector<const BinaryOperator *, 4> SuspiciousCompares;
21177
21178 // Iterate over all the enum values, gather suspisious comparison ops and
21179 // whether any enum initialisers contain a binary operator.
21180 for (const auto *ECD : Enum->enumerators()) {
21181 const Expr *InitExpr = ECD->getInitExpr();
21182 if (!InitExpr)
21183 continue;
21184
21185 const Expr *E = InitExpr->IgnoreParenImpCasts();
21186
21187 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
21188 BinaryOperatorKind Op = BinOp->getOpcode();
21189
21190 // Check for bitwise ops (<<, >>, &, |)
21191 if (BinOp->isBitwiseOp() || BinOp->isShiftOp()) {
21192 HasBitwiseOp = true;
21193 } else if (Op == BO_LT || Op == BO_GT) {
21194 // Check for the typo pattern (Comparison < or >)
21195 const Expr *LHS = BinOp->getLHS()->IgnoreParenImpCasts();
21196 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(LHS)) {
21197 // Specifically looking for accidental bitshifts "1 < X" or "1 > X"
21198 if (IntLiteral->getValue() == 1)
21199 SuspiciousCompares.push_back(BinOp);
21200 }
21201 }
21202 }
21203 }
21204
21205 // If we found a bitwise op and some sus compares, iterate over the compares
21206 // and warn.
21207 if (HasBitwiseOp) {
21208 for (const auto *BinOp : SuspiciousCompares) {
21209 StringRef SuggestedOp = (BinOp->getOpcode() == BO_LT)
21212 SourceLocation OperatorLoc = BinOp->getOperatorLoc();
21213
21214 Sema.Diag(OperatorLoc, diag::warn_comparison_in_enum_initializer)
21215 << BinOp->getOpcodeStr() << SuggestedOp;
21216
21217 Sema.Diag(OperatorLoc, diag::note_enum_compare_typo_suggest)
21218 << SuggestedOp
21219 << FixItHint::CreateReplacement(OperatorLoc, SuggestedOp);
21220 }
21221 }
21222}
21223
21225 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
21226 const ParsedAttributesView &Attrs) {
21227 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
21228 CanQualType EnumType = Context.getCanonicalTagType(Enum);
21229
21230 ProcessDeclAttributeList(S, Enum, Attrs);
21232
21233 if (Enum->isDependentType()) {
21234 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
21235 EnumConstantDecl *ECD =
21236 cast_or_null<EnumConstantDecl>(Elements[i]);
21237 if (!ECD) continue;
21238
21239 ECD->setType(EnumType);
21240 }
21241
21242 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
21243 return;
21244 }
21245
21246 // Verify that all the values are okay, compute the size of the values, and
21247 // reverse the list.
21248 unsigned NumNegativeBits = 0;
21249 unsigned NumPositiveBits = 0;
21250 bool MembersRepresentableByInt =
21251 Context.computeEnumBits(Elements, NumNegativeBits, NumPositiveBits);
21252
21253 // Figure out the type that should be used for this enum.
21254 QualType BestType;
21255 unsigned BestWidth;
21256
21257 // C++0x N3000 [conv.prom]p3:
21258 // An rvalue of an unscoped enumeration type whose underlying
21259 // type is not fixed can be converted to an rvalue of the first
21260 // of the following types that can represent all the values of
21261 // the enumeration: int, unsigned int, long int, unsigned long
21262 // int, long long int, or unsigned long long int.
21263 // C99 6.4.4.3p2:
21264 // An identifier declared as an enumeration constant has type int.
21265 // The C99 rule is modified by C23.
21266 QualType BestPromotionType;
21267
21268 bool Packed = Enum->hasAttr<PackedAttr>();
21269 // -fshort-enums is the equivalent to specifying the packed attribute on all
21270 // enum definitions.
21271 if (LangOpts.ShortEnums)
21272 Packed = true;
21273
21274 // If the enum already has a type because it is fixed or dictated by the
21275 // target, promote that type instead of analyzing the enumerators.
21276 if (Enum->isComplete()) {
21277 BestType = Enum->getIntegerType();
21278 if (Context.isPromotableIntegerType(BestType))
21279 BestPromotionType = Context.getPromotedIntegerType(BestType);
21280 else
21281 BestPromotionType = BestType;
21282
21283 BestWidth = Context.getIntWidth(BestType);
21284 } else {
21285 bool EnumTooLarge = Context.computeBestEnumTypes(
21286 Packed, NumNegativeBits, NumPositiveBits, BestType, BestPromotionType);
21287 BestWidth = Context.getIntWidth(BestType);
21288 if (EnumTooLarge)
21289 Diag(Enum->getLocation(), diag::ext_enum_too_large);
21290 }
21291
21292 // Loop over all of the enumerator constants, changing their types to match
21293 // the type of the enum if needed.
21294 for (auto *D : Elements) {
21295 auto *ECD = cast_or_null<EnumConstantDecl>(D);
21296 if (!ECD) continue; // Already issued a diagnostic.
21297
21298 // C99 says the enumerators have int type, but we allow, as an
21299 // extension, the enumerators to be larger than int size. If each
21300 // enumerator value fits in an int, type it as an int, otherwise type it the
21301 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
21302 // that X has type 'int', not 'unsigned'.
21303
21304 // Determine whether the value fits into an int.
21305 llvm::APSInt InitVal = ECD->getInitVal();
21306
21307 // If it fits into an integer type, force it. Otherwise force it to match
21308 // the enum decl type.
21309 QualType NewTy;
21310 unsigned NewWidth;
21311 bool NewSign;
21312 if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
21313 MembersRepresentableByInt) {
21314 // C23 6.7.3.3.3p15:
21315 // The enumeration member type for an enumerated type without fixed
21316 // underlying type upon completion is:
21317 // - int if all the values of the enumeration are representable as an
21318 // int; or,
21319 // - the enumerated type
21320 NewTy = Context.IntTy;
21321 NewWidth = Context.getTargetInfo().getIntWidth();
21322 NewSign = true;
21323 } else if (ECD->getType() == BestType) {
21324 // Already the right type!
21325 if (getLangOpts().CPlusPlus || (getLangOpts().C23 && Enum->isFixed()))
21326 // C++ [dcl.enum]p4: Following the closing brace of an
21327 // enum-specifier, each enumerator has the type of its
21328 // enumeration.
21329 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21330 // with fixed underlying type is the enumerated type.
21331 ECD->setType(EnumType);
21332 continue;
21333 } else {
21334 NewTy = BestType;
21335 NewWidth = BestWidth;
21336 NewSign = BestType->isSignedIntegerOrEnumerationType();
21337 }
21338
21339 // Adjust the APSInt value.
21340 InitVal = InitVal.extOrTrunc(NewWidth);
21341 InitVal.setIsSigned(NewSign);
21342 ECD->setInitVal(Context, InitVal);
21343
21344 // Adjust the Expr initializer and type.
21345 if (ECD->getInitExpr() &&
21346 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
21347 ECD->setInitExpr(ImplicitCastExpr::Create(
21348 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
21349 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
21350 if (getLangOpts().CPlusPlus ||
21351 (getLangOpts().C23 && (Enum->isFixed() || !MembersRepresentableByInt)))
21352 // C++ [dcl.enum]p4: Following the closing brace of an
21353 // enum-specifier, each enumerator has the type of its
21354 // enumeration.
21355 // C23 6.7.3.3p16: The enumeration member type for an enumerated type
21356 // with fixed underlying type is the enumerated type.
21357 ECD->setType(EnumType);
21358 else
21359 ECD->setType(NewTy);
21360 }
21361
21362 Enum->completeDefinition(BestType, BestPromotionType,
21363 NumPositiveBits, NumNegativeBits);
21364
21365 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
21367
21368 if (Enum->isClosedFlag()) {
21369 for (Decl *D : Elements) {
21370 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
21371 if (!ECD) continue; // Already issued a diagnostic.
21372
21373 llvm::APSInt InitVal = ECD->getInitVal();
21374 if (InitVal != 0 && !InitVal.isPowerOf2() &&
21375 !IsValueInFlagEnum(Enum, InitVal, true))
21376 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
21377 << ECD << Enum;
21378 }
21379 }
21380
21381 // Now that the enum type is defined, ensure it's not been underaligned.
21382 if (Enum->hasAttrs())
21384}
21385
21387 SourceLocation EndLoc) {
21388
21390 FileScopeAsmDecl::Create(Context, CurContext, expr, StartLoc, EndLoc);
21391 CurContext->addDecl(New);
21392 return New;
21393}
21394
21396 auto *New = TopLevelStmtDecl::Create(Context, /*Statement=*/nullptr);
21397 CurContext->addDecl(New);
21398 PushDeclContext(S, New);
21400 PushCompoundScope(false);
21401 return New;
21402}
21403
21405 if (Statement)
21406 D->setStmt(Statement);
21410}
21411
21413 IdentifierInfo* AliasName,
21414 SourceLocation PragmaLoc,
21415 SourceLocation NameLoc,
21416 SourceLocation AliasNameLoc) {
21417 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
21419 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
21421 AsmLabelAttr *Attr =
21422 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), Info);
21423
21424 // If a declaration that:
21425 // 1) declares a function or a variable
21426 // 2) has external linkage
21427 // already exists, add a label attribute to it.
21428 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21429 if (isDeclExternC(PrevDecl))
21430 PrevDecl->addAttr(Attr);
21431 else
21432 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
21433 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
21434 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
21435 } else
21436 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
21437}
21438
21440 SourceLocation PragmaLoc,
21441 SourceLocation NameLoc) {
21442 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
21443
21444 if (PrevDecl) {
21445 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
21446 } else {
21447 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
21448 }
21449}
21450
21452 IdentifierInfo* AliasName,
21453 SourceLocation PragmaLoc,
21454 SourceLocation NameLoc,
21455 SourceLocation AliasNameLoc) {
21456 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
21458 WeakInfo W = WeakInfo(Name, NameLoc);
21459
21460 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
21461 if (!PrevDecl->hasAttr<AliasAttr>())
21462 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
21464 } else {
21465 (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
21466 }
21467}
21468
21470 bool Final) {
21471 assert(FD && "Expected non-null FunctionDecl");
21472
21473 // Templates are emitted when they're instantiated.
21474 if (FD->isDependentContext())
21476
21477 if (LangOpts.SYCLIsDevice && (FD->hasAttr<SYCLKernelAttr>() ||
21478 FD->hasAttr<SYCLKernelEntryPointAttr>() ||
21479 FD->hasAttr<SYCLExternalAttr>()))
21481
21482 // Check whether this function is an externally visible definition.
21483 auto IsEmittedForExternalSymbol = [this, FD]() {
21484 // We have to check the GVA linkage of the function's *definition* -- if we
21485 // only have a declaration, we don't know whether or not the function will
21486 // be emitted, because (say) the definition could include "inline".
21487 const FunctionDecl *Def = FD->getDefinition();
21488
21489 // We can't compute linkage when we skip function bodies.
21490 return Def && !Def->hasSkippedBody() &&
21492 getASTContext().GetGVALinkageForFunction(Def));
21493 };
21494
21495 if (LangOpts.OpenMPIsTargetDevice) {
21496 // In OpenMP device mode we will not emit host only functions, or functions
21497 // we don't need due to their linkage.
21498 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21499 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21500 // DevTy may be changed later by
21501 // #pragma omp declare target to(*) device_type(*).
21502 // Therefore DevTy having no value does not imply host. The emission status
21503 // will be checked again at the end of compilation unit with Final = true.
21504 if (DevTy)
21505 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
21507 // If we have an explicit value for the device type, or we are in a target
21508 // declare context, we need to emit all extern and used symbols.
21509 if (OpenMP().isInOpenMPDeclareTargetContext() || DevTy)
21510 if (IsEmittedForExternalSymbol())
21512 // Device mode only emits what it must, if it wasn't tagged yet and needed,
21513 // we'll omit it.
21514 if (Final)
21516 } else if (LangOpts.OpenMP > 45) {
21517 // In OpenMP host compilation prior to 5.0 everything was an emitted host
21518 // function. In 5.0, no_host was introduced which might cause a function to
21519 // be omitted.
21520 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
21521 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
21522 if (DevTy)
21523 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
21525 }
21526
21527 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
21529
21530 if (LangOpts.CUDA) {
21531 // When compiling for device, host functions are never emitted. Similarly,
21532 // when compiling for host, device and global functions are never emitted.
21533 // (Technically, we do emit a host-side stub for global functions, but this
21534 // doesn't count for our purposes here.)
21536 if (LangOpts.CUDAIsDevice && T == CUDAFunctionTarget::Host)
21538 if (!LangOpts.CUDAIsDevice &&
21541
21542 if (IsEmittedForExternalSymbol())
21544 }
21545
21546 // Otherwise, the function is known-emitted if it's in our set of
21547 // known-emitted functions.
21549}
21550
21552 // Host-side references to a __global__ function refer to the stub, so the
21553 // function itself is never emitted and therefore should not be marked.
21554 // If we have host fn calls kernel fn calls host+device, the HD function
21555 // does not get instantiated on the host. We model this by omitting at the
21556 // call to the kernel from the callgraph. This ensures that, when compiling
21557 // for host, only HD functions actually called from the host get marked as
21558 // known-emitted.
21559 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
21561}
21562
21564 SourceLocation NewDefinitionLoc,
21565 NamedDecl **Suggested, bool &Visible) {
21566 Visible = hasVisibleDefinition(D, Suggested);
21567 // Accoding to [basic.def.odr]p16, it is not allowed to have duplicated definition
21568 // for declaratins which is attached to named modules.
21569 // We only did this if the current module is named module as we have better
21570 // diagnostics for declarations in global module and named modules.
21571 if (getCurrentModule() && getCurrentModule()->isNamedModule() &&
21572 D->isInNamedModule())
21573 return false;
21574 // The redefinition of D in the **current** TU is allowed if D is invisible or
21575 // D is defined in the global module of other module units or D is defined in
21576 // the same header in a different module.
21577 return D->isInAnotherModuleUnit() || !Visible ||
21578 isFromSameSingleIncludeHeader(D, NewDefinitionLoc);
21579}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
static bool isDeclExternC(const T &D)
Definition Decl.cpp:2209
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
Defines helper utilities for supporting the HLSL runtime environment.
static const Decl * getCanonicalDecl(const Decl *D)
Result
Implement __builtin_bit_cast and related operations.
#define CC_VLS_CASE(ABI_VLEN)
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Architecture Architecture
Definition MachO.h:27
llvm::MachO::Record Record
Definition MachO.h:31
static bool isExternC(const NamedDecl *ND)
Definition Mangle.cpp:82
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
@ ForExternalRedeclaration
The lookup results will be used for redeclaration of a name with external linkage; non-visible lookup...
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:186
This file declares semantic analysis for CUDA constructs.
static void diagnoseImplicitlyRetainedSelf(Sema &S)
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition SemaDecl.cpp:181
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool isMainVar(DeclarationName Name, VarDecl *VD)
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition SemaDecl.cpp:236
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
static void checkHybridPatchableAttr(Sema &S, NamedDecl &ND)
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition SemaDecl.cpp:848
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
static bool CheckC23ConstexprVarType(Sema &SemaRef, SourceLocation VarLoc, QualType T)
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD)
static bool FindPossiblePrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
static bool MultiVersionTypesCompatible(FunctionDecl *Old, FunctionDecl *New)
static NestedNameSpecifier synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition SemaDecl.cpp:612
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, SourceLocation ExplicitThisLoc)
static void checkLifetimeBoundAttr(Sema &S, NamedDecl &ND)
static void patchDefaultTargetVersion(FunctionDecl *From, FunctionDecl *To)
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99's...
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS)
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
static unsigned propagateAttribute(ParmVarDecl *To, const ParmVarDecl *From, Sema &S)
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
static bool methodHasName(const FunctionDecl *FD, StringRef Name)
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion, StorageClass SC)
We are trying to inject an anonymous member into the given scope; check if there's an existing declar...
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, const NamedDecl *D)
static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, unsigned BuiltinID)
Determine whether a declaration matches a known function in namespace std.
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, StorageClass SC, SmallVectorImpl< NamedDecl * > &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
OpenCLParamType
@ InvalidAddrSpacePtrKernelParam
@ ValidKernelParam
@ InvalidKernelParam
@ RecordKernelParam
@ PtrKernelParam
@ PtrPtrKernelParam
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const ValueDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, CXXMethodDecl *M1, CXXMethodDecl *M2, CXXSpecialMemberKind CSM)
[class.mem.special]p5 Two special member functions are of the same kind if:
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition SemaDecl.cpp:631
static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record)
[class.dtor]p4: At the end of the definition of a class, overload resolution is performed among the p...
static bool shouldConsiderLinkage(const VarDecl *VD)
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
static bool EquivalentArrayTypes(QualType Old, QualType New, const ASTContext &Ctx)
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
static void checkInheritableAttr(Sema &S, NamedDecl &ND)
static void CheckPoppedLabel(LabelDecl *L, Sema &S, Sema::DiagReceiverTy DiagReceiver)
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
RebuildDeclaratorInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in ...
static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, ArrayRef< CXXMethodDecl * > Methods, CXXSpecialMemberKind CSM)
[class.mem.special]p6: An eligible special member function is a special member function for which:
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition SemaDecl.cpp:863
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
@ SDK_StructuredBinding
@ SDK_Field
@ SDK_Global
@ SDK_Local
@ SDK_Typedef
@ SDK_StaticMember
@ SDK_Using
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
static void CheckForComparisonInEnumInitializer(SemaBase &Sema, const EnumDecl *Enum)
static void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD)
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
static void checkWeakAttr(Sema &S, NamedDecl &ND)
static void checkModularFormatAttr(Sema &S, NamedDecl &ND)
static void checkSelectAnyAttr(Sema &S, NamedDecl &ND)
static bool isImplicitInstantiation(NamedDecl *D)
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations not at class scope from the lookup results.
static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, CXXRecordDecl *Record)
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
static bool looksMutable(QualType T, const ASTContext &Ctx)
static bool isUsingDeclNotAtClassScope(NamedDecl *D)
static void propagateAttributes(ParmVarDecl *To, const ParmVarDecl *From, F &&propagator)
static const NamedDecl * getDefinition(const Decl *D)
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
static bool hasDeducedAuto(DeclaratorDecl *DD)
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
static QualType getCoreType(QualType Ty)
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, AvailabilityMergeKind AMK)
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target or target_version attribute of the function for MultiVersion validity.
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD)
Check the validity of a multiversion function declaration that is the first of its kind.
static bool isSYCLAddressSpace(LangAS AS)
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
static void checkAliasAttr(Sema &S, NamedDecl &ND)
static void filterNonConflictingPreviousTypedefDecls(Sema &S, const TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
static void checkWeakRefAttr(Sema &S, NamedDecl &ND)
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
static bool isAttributeTargetADefinition(Decl *D)
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
static bool CheckDeclarationCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
static bool isRecordType(QualType T)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to Wasm.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
@ GE_None
No error.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_type
Missing a type.
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:123
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:239
SourceManager & getSourceManager()
Definition ASTContext.h:911
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:850
const LangOptions & getLangOpts() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const VariableArrayType * getAsVariableArrayType(QualType T) const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:969
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:3598
Wrapper for source info for arrays.
Definition TypeLoc.h:1808
SourceLocation getLBracketLoc() const
Definition TypeLoc.h:1810
Expr * getSizeExpr() const
Definition TypeLoc.h:1830
TypeLoc getElementLoc() const
Definition TypeLoc.h:1838
SourceLocation getRBracketLoc() const
Definition TypeLoc.h:1818
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3813
QualType getElementType() const
Definition TypeBase.h:3825
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
bool isInherited() const
Definition Attr.h:101
bool isImplicit() const
Returns true if the attribute has been implicitly created instead of explicitly written by the user.
Definition Attr.h:105
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition Attr.h:106
SourceLocation getLocation() const
Definition Attr.h:99
bool isStandardAttributeSyntax() const
The attribute is spelled [[]] in either C or C++ mode, including standard attributes spelled with a k...
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition ParsedAttr.h:635
AttributeFactory & getFactory() const
Definition ParsedAttr.h:731
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition Expr.h:4551
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition Expr.h:4539
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4082
Expr * getLHS() const
Definition Expr.h:4132
StringRef getOpcodeStr() const
Definition Expr.h:4148
Expr * getRHS() const
Definition Expr.h:4134
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4223
A binding in a decomposition declaration.
Definition DeclCXX.h:4215
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4810
bool doesNotEscape() const
Definition Decl.h:4961
This class is used for builtin types like 'int'.
Definition TypeBase.h:3241
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:236
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition Builtins.h:383
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclCXX.h:194
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclCXX.h:195
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition DeclCXX.cpp:3058
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3018
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2977
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3283
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal, const AssociatedConstraint &TrailingRequiresClause={}, const CXXDeductionGuideDecl *SourceDG=nullptr, SourceDeductionGuideKind SK=SourceDeductionGuideKind::None)
Definition DeclCXX.cpp:2383
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3158
A mapping from each virtual member function to its set of final overriders.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2719
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition DeclCXX.cpp:2805
bool isVirtual() const
Definition DeclCXX.h:2205
CXXSpecialMemberKind getSpecialMemberKind() const
Definition DeclCXX.h:2229
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2504
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
Qualifiers getMethodQualifiers() const
Definition DeclCXX.h:2328
bool isConst() const
Definition DeclCXX.h:2202
bool isStatic() const
Definition DeclCXX.cpp:2417
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2263
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
base_class_iterator bases_end()
Definition DeclCXX.h:618
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1382
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1578
base_class_range bases()
Definition DeclCXX.h:609
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
base_class_iterator bases_begin()
Definition DeclCXX.h:616
capture_const_range captures() const
Definition DeclCXX.h:1107
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition DeclCXX.h:1158
bool hasDefinition() const
Definition DeclCXX.h:562
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2054
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition DeclCXX.cpp:2154
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition DeclCXX.h:1069
UnresolvedSetIterator conversion_iterator
Definition DeclCXX.h:1129
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2058
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:523
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
bool isCallToStdMove() const
Definition Expr.cpp:3676
Expr * getCallee()
Definition Expr.h:3134
arg_range arguments()
Definition Expr.h:3239
CastKind getCastKind() const
Definition Expr.h:3764
Expr * getSubExpr()
Definition Expr.h:3770
static CharSourceRange getCharRange(SourceRange R)
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:153
Declaration of a class template.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3851
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:334
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:374
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3907
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclListNode::iterator iterator
Definition DeclBase.h:1409
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2279
bool isFileContext() const
Definition DeclBase.h:2217
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
DeclContextLookupResult lookup_result
Definition DeclBase.h:2627
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool isClosure() const
Definition DeclBase.h:2159
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2142
bool isNamespace() const
Definition DeclBase.h:2239
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
bool isTranslationUnit() const
Definition DeclBase.h:2222
bool isRecord() const
Definition DeclBase.h:2226
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void removeDecl(Decl *D)
Removes a declaration from this context.
void addDecl(Decl *D)
Add the declaration D into this context.
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2423
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2181
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2119
DeclContext * getNonTransparentContext()
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition DeclGroup.h:64
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
ValueDecl * getDecl()
Definition Expr.h:1358
SourceLocation getBeginLoc() const
Definition Expr.h:1369
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:655
bool isModulePrivateSpecified() const
Definition DeclSpec.h:836
static const TST TST_typeof_unqualType
Definition DeclSpec.h:282
bool hasAutoTypeSpec() const
Definition DeclSpec.h:580
static const TST TST_typename
Definition DeclSpec.h:279
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition DeclSpec.cpp:631
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:237
void ClearStorageClassSpecs()
Definition DeclSpec.h:500
bool isNoreturnSpecified() const
Definition DeclSpec.h:668
TST getTypeSpecType() const
Definition DeclSpec.h:522
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:495
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:846
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:716
static const TST TST_interface
Definition DeclSpec.h:277
static const TST TST_typeofExpr
Definition DeclSpec.h:281
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:602
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:715
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:669
bool isExternInLinkageSpec() const
Definition DeclSpec.h:490
static const TST TST_union
Definition DeclSpec.h:275
SCS
storage-class-specifier
Definition DeclSpec.h:224
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:661
static const TST TST_int
Definition DeclSpec.h:258
SourceLocation getModulePrivateSpecLoc() const
Definition DeclSpec.h:837
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
ParsedType getRepAsType() const
Definition DeclSpec.h:532
void UpdateTypeRep(ParsedType Rep)
Definition DeclSpec.h:795
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:487
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:631
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:603
SourceRange getExplicitSpecRange() const
Definition DeclSpec.h:662
Expr * getRepAsExpr() const
Definition DeclSpec.h:540
static const TST TST_enum
Definition DeclSpec.h:274
static const TST TST_decltype
Definition DeclSpec.h:284
static bool isDeclRep(TST T)
Definition DeclSpec.h:453
bool isInlineSpecified() const
Definition DeclSpec.h:644
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:604
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:283
static const TST TST_class
Definition DeclSpec.h:278
TypeSpecifierType TST
Definition DeclSpec.h:250
static const TST TST_void
Definition DeclSpec.h:252
void ClearConstexprSpec()
Definition DeclSpec.h:848
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:532
static const TST TST_atomic
Definition DeclSpec.h:294
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:496
Decl * getRepAsDecl() const
Definition DeclSpec.h:536
static const TST TST_unspecified
Definition DeclSpec.h:251
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:606
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:656
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:843
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:567
void UpdateExprRep(Expr *Rep)
Definition DeclSpec.h:799
static const TSCS TSCS_thread_local
Definition DeclSpec.h:240
static const TST TST_error
Definition DeclSpec.h:301
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclSpec.h:651
bool isTypeSpecOwned() const
Definition DeclSpec.h:526
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:647
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:607
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:605
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:828
bool hasExplicitSpecifier() const
Definition DeclSpec.h:658
bool hasConstexprSpecifier() const
Definition DeclSpec.h:844
static const TST TST_typeofType
Definition DeclSpec.h:280
static const TST TST_auto
Definition DeclSpec.h:291
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:839
static const TST TST_struct
Definition DeclSpec.h:276
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1078
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1093
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:344
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1243
bool isFromGlobalModule() const
Whether this declaration comes from global module.
T * getAttr() const
Definition DeclBase.h:581
bool hasAttrs() const
Definition DeclBase.h:526
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setAttrs(const AttrVec &Attrs)
Definition DeclBase.h:528
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition DeclBase.h:783
bool isInNamedModule() const
Whether this declaration comes from a named module.
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition DeclBase.h:1168
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition Decl.cpp:100
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void setTopLevelDeclInObjCContainer(bool V=true)
Definition DeclBase.h:646
bool isInIdentifierNamespace(unsigned NS) const
Definition DeclBase.h:910
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition DeclBase.h:1236
@ FOK_None
Not a friend object.
Definition DeclBase.h:1234
@ FOK_Declared
A friend of a previously-declared entity.
Definition DeclBase.h:1235
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:604
bool isInAnotherModuleUnit() const
Whether this declaration comes from another module unit.
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
void dropAttrs()
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition DeclBase.h:210
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1197
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2843
bool isInvalidDecl() const
Definition DeclBase.h:596
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1186
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
@ IDNS_Ordinary
Ordinary names.
Definition DeclBase.h:144
void setImplicit(bool I=true)
Definition DeclBase.h:602
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:579
DeclContext * getDeclContext()
Definition DeclBase.h:456
attr_range attrs() const
Definition DeclBase.h:543
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void dropAttr()
Definition DeclBase.h:564
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:385
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition Decl.cpp:1638
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition DeclBase.h:1252
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
Kind getKind() const
Definition DeclBase.h:450
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isAnyOperatorNewOrDelete() const
bool isAnyOperatorDelete() const
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
NameKind getNameKind() const
Determine what kind of name this is.
bool isEmpty() const
Evaluates true when this declaration name is empty.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:781
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:823
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition Decl.cpp:2066
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2070
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2004
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:832
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:856
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:815
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2016
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:838
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:2050
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2508
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2450
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
Expr * getAsmLabel() const
Definition DeclSpec.h:2754
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2793
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2735
void setRedeclaration(bool Val)
Definition DeclSpec.h:2816
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
void SetIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition DeclSpec.h:2391
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2136
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2685
void takeAttributesAppending(ParsedAttributes &attrs)
takeAttributesAppending - Takes attributes from the given ParsedAttributes set and add them to this d...
Definition DeclSpec.h:2728
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2765
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition DeclSpec.h:2715
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2446
bool isRedeclaration() const
Definition DeclSpec.h:2817
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2738
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition DeclSpec.h:2120
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition DeclSpec.cpp:410
bool isFunctionDefinition() const
Definition DeclSpec.h:2789
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2118
bool hasInitializer() const
Definition DeclSpec.h:2798
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition DeclSpec.h:2785
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2405
bool isInvalidType() const
Definition DeclSpec.h:2766
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition DeclSpec.h:2378
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2801
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:2106
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2539
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
A decomposition declaration.
Definition DeclCXX.h:4279
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, SourceLocation RSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition DeclCXX.cpp:3742
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition DeclSpec.h:1840
SourceRange getSourceRange() const
Definition DeclSpec.h:1888
SourceLocation getLSquareLoc() const
Definition DeclSpec.h:1886
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2544
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:970
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3558
llvm::APSInt getInitVal() const
Definition Decl.h:3578
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition Decl.cpp:5781
const Expr * getInitExpr() const
Definition Decl.h:3576
Represents an enum.
Definition Decl.h:4146
enumerator_range enumerators() const
Definition Decl.h:4292
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4364
void setIntegerType(QualType T)
Set the underlying integer type.
Definition Decl.h:4328
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition Decl.h:4331
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4378
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5139
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition Decl.cpp:5178
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4373
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition Decl.cpp:5153
void setPromotionType(QualType T)
Set the promotion type.
Definition Decl.h:4314
void setEnumKeyRange(SourceRange Range)
Definition Decl.h:4226
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4319
EvaluatedExprVisitor - This class visits 'Expr *'s.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
This represents one expression.
Definition Expr.h:113
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3123
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
bool isConstantInitializer(ASTContext &Ctx, bool ForRef=false, const Expr **Culprit=nullptr) const
Returns true if this expression can be emitted to IR as a constant, and thus can be used as a constan...
Definition Expr.cpp:3380
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3103
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:145
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3398
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition Decl.cpp:4780
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
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:4765
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Definition Decl.cpp:4826
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition Decl.cpp:5914
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
Represents a function declaration or definition.
Definition Decl.h:2059
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2820
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2303
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2603
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4244
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition Decl.cpp:3775
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4237
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4232
void setIsPureVirtual(bool P=true)
Definition Decl.cpp:3340
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2428
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition Decl.h:2832
void setHasSkippedBody(bool Skipped=true)
Definition Decl.h:2811
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4066
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3804
param_iterator param_end()
Definition Decl.h:2918
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3052
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition Decl.h:2826
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition Decl.cpp:3748
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition Decl.h:2516
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2504
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition Decl.cpp:3656
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4352
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition Decl.h:2575
void setWillHaveBody(bool V=true)
Definition Decl.h:2817
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions:
Definition Decl.h:2723
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2570
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4362
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3789
param_iterator param_begin()
Definition Decl.h:2917
const ParmVarDecl * getNonObjectParameter(unsigned I) const
Definition Decl.h:2954
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition Decl.h:2440
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2667
FunctionEffectsRef getFunctionEffects() const
Definition Decl.h:3269
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition Decl.cpp:3417
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4296
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:3019
bool isStatic() const
Definition Decl.h:3060
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition Decl.cpp:4585
void setTrivial(bool IT)
Definition Decl.h:2505
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4183
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2597
bool isDeletedAsWritten() const
Definition Decl.h:2671
redecl_iterator redecls_end() const
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2480
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3660
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition Decl.h:2484
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition Decl.h:2555
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition Decl.h:2476
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition Decl.h:2810
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2396
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition Decl.cpp:3410
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition Decl.h:3047
bool param_empty() const
Definition Decl.h:2916
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition Decl.cpp:3210
void setRangeEnd(SourceLocation E)
Definition Decl.h:2332
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition Decl.cpp:3744
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2512
void setIneligibleOrNotSelected(bool II)
Definition Decl.h:2548
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4608
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:3064
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition Decl.cpp:4177
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2600
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4456
void setDefaulted(bool D=true)
Definition Decl.h:2513
bool isConsteval() const
Definition Decl.h:2609
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2993
void setBody(Stmt *B)
Definition Decl.cpp:3278
bool isGlobal() const
Determines whether this is a global function.
Definition Decl.cpp:3674
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3156
bool hasInheritedPrototype() const
Whether this function inherited its prototype from a previous declaration.
Definition Decl.h:2586
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4204
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3868
DeclarationNameInfo getNameInfo() const
Definition Decl.h:2325
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3186
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition Decl.h:2562
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3233
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:3030
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition Decl.cpp:3730
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2816
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5345
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5377
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:6077
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5209
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5409
unsigned getNumParams() const
Definition TypeBase.h:5687
QualType getParamType(unsigned i) const
Definition TypeBase.h:5689
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition TypeBase.h:5906
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5722
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5813
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5698
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5694
Declaration of a template function.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
Wrapper for source info for functions.
Definition TypeLoc.h:1675
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4716
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4828
CallingConv getCC() const
Definition TypeBase.h:4775
ExtInfo withProducesResult(bool producesResult) const
Definition TypeBase.h:4794
unsigned getRegParm() const
Definition TypeBase.h:4768
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4764
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4787
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition TypeBase.h:4808
ExtInfo withRegParm(unsigned RegParm) const
Definition TypeBase.h:4822
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4605
ExtInfo getExtInfo() const
Definition TypeBase.h:4961
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3834
unsigned getRegParmType() const
Definition TypeBase.h:4948
CallingConv getCallConv() const
Definition TypeBase.h:4960
QualType getReturnType() const
Definition TypeBase.h:4945
bool getCmseNSCallAttr() const
Definition TypeBase.h:4959
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:2103
Represents a C array with an unspecified size.
Definition TypeBase.h:4000
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3602
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition Decl.cpp:5808
void setInherited(bool I)
Definition Attr.h:163
Description of a constructor that was inherited from a base class.
Definition DeclCXX.h:2613
child_range children()
Definition Expr.h:5548
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
step_iterator step_begin() const
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
@ SK_ParenthesizedListInit
Initialize an aggreagate with parenthesized list of values.
Describes an entity that is being initialized.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:981
Represents the declaration of a label.
Definition Decl.h:525
bool isResolvedMSAsmLabel() const
Definition Decl.h:560
LabelStmt * getStmt() const
Definition Decl.h:549
bool isMSAsmLabel() const
Definition Decl.h:559
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
Definition ExprCXX.h:2087
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
FPExceptionModeKind getDefaultExceptionMode() const
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
bool isCompatibleWithMSVC() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition Lexer.cpp:1437
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
Definition Lexer.cpp:1381
Visibility getVisibility() const
Definition Visibility.h:89
Linkage getLinkage() const
Definition Visibility.h:88
Represents a linkage specification.
Definition DeclCXX.h:3045
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LinkageSpecLanguageIDs Lang, bool HasBraces)
Definition DeclCXX.cpp:3313
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
bool isAmbiguous() const
Definition Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
Expr * getBase() const
Definition Expr.h:3485
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3744
Describes a module or submodule.
Definition Module.h:340
SourceLocation DefinitionLoc
The location of the module definition.
Definition Module.h:346
Module * Parent
The parent of this module.
Definition Module.h:389
bool isPrivateModule() const
Definition Module.h:448
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:866
bool isModuleImplementation() const
Is this a module implementation.
Definition Module.h:882
bool isModulePartition() const
Is this a module partition.
Definition Module.h:871
bool isGlobalModule() const
Does this Module scope describe a fragment of the global module within some C++ module.
Definition Module.h:438
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:240
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:423
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:940
@ ClassId_NSObject
Definition NSAPI.h:30
This represents a decl that may have a name.
Definition Decl.h:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
bool isLinkageValid() const
True if the computed linkage is valid.
Definition Decl.cpp:1086
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1096
Visibility getVisibility() const
Determines the visibility of this entity.
Definition Decl.h:445
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition Decl.h:480
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition Decl.h:430
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition Decl.cpp:1872
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:718
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1944
bool isExternallyVisible() const
Definition Decl.h:434
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition Decl.cpp:1133
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:398
Represent a C++ namespace.
Definition Decl.h:593
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:644
Class that aids in the construction of nested-name-specifiers along with source-location information ...
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static constexpr NestedNameSpecifier getGlobal()
bool containsErrors() const
Whether this nested name specifier contains an error.
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2335
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition DeclObjC.h:2781
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:954
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition DeclObjC.cpp:78
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2603
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
known_extensions_range known_extensions() const
Definition DeclObjC.h:1768
Wrapper for source info for ObjC interfaces.
Definition TypeLoc.h:1303
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
param_const_iterator param_end() const
Definition DeclObjC.h:361
param_const_iterator param_begin() const
Definition DeclObjC.h:357
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:352
bool isOptional() const
Definition DeclObjC.h:508
ParmVarDecl *const * param_iterator
Definition DeclObjC.h:353
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition TypeLoc.h:895
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(DeclGroupRef P)
Definition Ownership.h:61
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1161
@ CSK_Normal
Normal lookup.
Definition Overload.h:1165
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1377
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
MapType::iterator iterator
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1446
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1459
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1442
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3376
Represents a parameter to a function.
Definition Decl.h:1820
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1884
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1853
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1912
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2943
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2966
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
static const ParsedAttributesView & none()
Definition ParsedAttr.h:830
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:910
ParsedAttributes - A collection of parsed attributes.
Definition ParsedAttr.h:950
AttributePool & getPool() const
Definition ParsedAttr.h:957
PipeType - OpenCL20.
Definition TypeBase.h:8268
Pointer-authentication qualifiers.
Definition TypeBase.h:153
bool isAddressDiscriminated() const
Definition TypeBase.h:266
TypeLoc getPointeeLoc() const
Definition TypeLoc.h:1525
Wrapper for source info for pointers.
Definition TypeLoc.h:1544
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3396
QualType getPointeeType() const
Definition TypeBase.h:3406
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8523
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8517
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:85
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:3149
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition Type.cpp:194
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1230
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition Type.cpp:3215
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8439
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8565
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:8479
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8491
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8533
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition Type.cpp:3199
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition TypeBase.h:1449
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8512
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8560
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1839
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
bool isCanonical() const
Definition TypeBase.h:8496
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1325
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1458
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2914
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition TypeBase.h:1509
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition TypeBase.h:1514
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:73
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8379
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8386
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4969
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
bool hasConst() const
Definition TypeBase.h:458
bool hasVolatile() const
Definition TypeBase.h:468
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
bool empty() const
Definition TypeBase.h:648
static std::string getAddrSpaceAsString(LangAS AS)
Represents a struct/union/class.
Definition Decl.h:4460
field_range fields() const
Definition Decl.h:4663
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5297
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4660
field_iterator field_begin() const
Definition Decl.cpp:5340
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7553
void setMemberSpecialization()
Note that this member template is a specialization.
void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD)
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5468
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3671
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3172
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition Stmt.h:3215
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void setEntity(DeclContext *E)
Definition Scope.h:395
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:414
unsigned getDepth() const
Returns the depth of this scope. The translation-unit has scope depth 0.
Definition Scope.h:325
unsigned getNextFunctionPrototypeIndex()
Return the number of parameters declared in this function prototype, increasing it by one for the nex...
Definition Scope.h:335
const Scope * getFnParent() const
getFnParent - Return the closest scope that is a function body.
Definition Scope.h:284
void AddDecl(Decl *D)
Definition Scope.h:348
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
bool isTypeAliasScope() const
Determine whether this scope is a type alias scope.
Definition Scope.h:614
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:384
void RemoveDecl(Decl *D)
Definition Scope.h:356
void setLookupEntity(DeclContext *E)
Definition Scope.h:400
unsigned getMSLastManglingNumber() const
Definition Scope.h:372
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
unsigned getMSCurManglingNumber() const
Definition Scope.h:378
bool decl_empty() const
Definition Scope.h:346
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:467
unsigned getFunctionPrototypeDepth() const
Returns the number of function prototype scopes in this scope chain.
Definition Scope.h:329
Scope * getDeclParent()
Definition Scope.h:321
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition Scope.h:605
decl_range decls() const
Definition Scope.h:342
bool containedInPrototypeScope() const
containedInPrototypeScope - Return true if this or a parent scope is a FunctionPrototypeScope.
Definition Scope.cpp:106
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:473
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred within this scope.
Definition Scope.h:406
void applyNRVO()
Definition Scope.cpp:171
Scope * getTemplateParamParent()
Definition Scope.h:318
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
void DiagnoseUnguardedBuiltinUsage(FunctionDecl *FD)
void checkNamedBarrierWrapper(RecordDecl *R)
Called in ActOnFields - whenever a C/C++ Record is being finalized.
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1593
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void checkAllowedInitializer(VarDecl *VD)
Definition SemaCUDA.cpp:744
std::string getConfigureFuncName() const
Returns the name of the launch configuration function.
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:211
void maybeAddHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous)
May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, depending on FD and the current co...
Definition SemaCUDA.cpp:874
void checkTargetOverload(FunctionDecl *NewFD, const LookupResult &Previous)
Check whether NewFD is a valid overload for CUDA.
void MaybeAddConstantAttr(VarDecl *VD)
May add implicit CUDAConstantAttr attribute to VD, depending on VD and current compilation settings.
Definition SemaCUDA.cpp:939
void CheckEntryPoint(FunctionDecl *FD)
Definition SemaHLSL.cpp:990
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:751
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:717
void deduceAddressSpace(VarDecl *Decl)
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:820
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:787
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:731
void ActOnVariableDeclarator(VarDecl *VD)
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
void AddCFAuditedAttribute(Decl *D)
AddCFAuditedAttribute - Check whether we're currently within '#pragma clang arc_cf_code_audited' and,...
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void ActOnVariableDeclarator(VarDecl *VD)
Function called when a variable declarator is created, which lets us implement the 'routine' 'functio...
OpenACCRoutineDeclAttr * mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old)
void ActOnFunctionDeclarator(FunctionDecl *FD)
Called when a function decl is created, which lets us implement the 'routine' 'doesn't match next thi...
void ActOnVariableInit(VarDecl *VD, QualType InitType)
Called when a variable is initialized, so we can implement the 'routine 'doesn't match the next thing...
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Decl *D, SmallVectorImpl< FunctionDecl * > &Bases)
Register D as specialization of all base functions in Bases in the current omp begin/end declare vari...
void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl< FunctionDecl * > &Bases)
The declarator D defines a function in the scope S which is nested in an omp begin/end declare varian...
void ActOnOpenMPDeclareTargetInitializer(Decl *D)
Adds OMPDeclareTargetDeclAttr to referenced variables in declare target directive.
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D, const llvm::StringMap< bool > &FeatureMap)
StmtResult BuildUnresolvedSYCLKernelCallStmt(CompoundStmt *Body, Expr *LaunchIdExpr)
Builds an UnresolvedSYCLKernelCallStmt to wrap 'Body'.
Definition SemaSYCL.cpp:819
StmtResult BuildSYCLKernelCallStmt(FunctionDecl *FD, CompoundStmt *Body, Expr *LaunchIdExpr)
Builds a SYCLKernelCallStmt to wrap 'Body' and to be used as the body of 'FD'.
Definition SemaSYCL.cpp:774
void CheckSYCLExternalFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:281
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:298
ExprResult BuildSYCLKernelLaunchIdExpr(FunctionDecl *FD, QualType KernelName)
Builds an expression for the lookup of a 'sycl_kernel_launch' template with 'KernelName' as an explic...
Definition SemaSYCL.cpp:428
SwiftNameAttr * mergeNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
Definition SemaSwift.cpp:26
SwiftAttrAttr * mergeAttrAttr(Decl *D, const SwiftAttrAttr &SAA)
Definition SemaSwift.cpp:42
WebAssemblyExportNameAttr * mergeExportNameAttr(Decl *D, const WebAssemblyExportNameAttr &AL)
Definition SemaWasm.cpp:386
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
Definition SemaWasm.cpp:353
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
Definition SemaWasm.cpp:319
bool IsAlignAttr() const
Definition Sema.h:1921
Mode getAlignMode() const
Definition Sema.h:1923
A RAII object to temporarily push a declaration context.
Definition Sema.h:3534
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1384
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1396
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
static NameClassification DependentNonType()
Definition Sema.h:3760
static NameClassification VarTemplate(TemplateName Name)
Definition Sema.h:3770
static NameClassification Unknown()
Definition Sema.h:3740
static NameClassification OverloadSet(ExprResult E)
Definition Sema.h:3744
static NameClassification UndeclaredTemplate(TemplateName Name)
Definition Sema.h:3788
static NameClassification FunctionTemplate(TemplateName Name)
Definition Sema.h:3776
static NameClassification NonType(NamedDecl *D)
Definition Sema.h:3750
static NameClassification Concept(TemplateName Name)
Definition Sema.h:3782
static NameClassification UndeclaredNonType()
Definition Sema.h:3756
static NameClassification TypeTemplate(TemplateName Name)
Definition Sema.h:3764
static NameClassification Error()
Definition Sema.h:3736
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12573
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12607
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S)
MergeCXXFunctionDecl - Merge two declarations of the same C++ function, once we already know that the...
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1446
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:3638
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13182
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2701
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1137
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:8295
bool isFromSameSingleIncludeHeader(const Decl *PrevD, SourceLocation NewLoc)
Determine if a definition at NewLoc coincides with PrevD.
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9390
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9394
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition Sema.h:9413
@ LookupLocalFriendName
Look up a friend of a local class.
Definition Sema.h:9429
@ LookupRedeclarationWithLinkage
Look up an ordinary name that is going to be redeclared as a name with linkage.
Definition Sema.h:9426
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9402
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9397
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:1531
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, QualType R, bool IsLambda, DeclContext *DC=nullptr)
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record)
MarkBaseAndMemberDestructorsReferenced - Given a record decl, mark all the non-trivial destructors of...
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition Sema.h:4821
PragmaClangSection PragmaClangRodataSection
Definition Sema.h:1847
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition Sema.h:6540
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:1471
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, InheritedConstructorInfo *ICI=nullptr, bool Diagnose=false)
Determine if a special member function should have a deleted definition when it is defaulted.
void ActOnExitFunctionContext()
void inferLifetimeCaptureByAttribute(FunctionDecl *FD)
Add [[clang:lifetime_capture_by(this)]] to STL container methods.
Definition SemaAttr.cpp:318
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Preprocessor & getPreprocessor() const
Definition Sema.h:934
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition Sema.h:2078
PragmaStack< StringLiteral * > CodeSegStack
Definition Sema.h:2072
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old)
CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member function overrides a virtual...
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, const CXXMethodDecl *Old)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl)
AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared special functions,...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
Decl * ActOnConversionDeclarator(CXXConversionDecl *Conversion)
ActOnConversionDeclarator - Called by ActOnDeclarator to complete the declaration of the given C++ co...
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
@ Default
= default ;
Definition Sema.h:4217
@ Delete
deleted-function-body
Definition Sema.h:4223
ExprResult VerifyBitField(SourceLocation FieldLoc, const IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS)
Check whether the given variable declaration has a size that fits within the address space it is decl...
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
void CheckThreadLocalForLargeAlignment(VarDecl *VD)
PersonalityAttr * mergePersonalityAttr(Decl *D, FunctionDecl *Routine, const AttributeCommonInfo &CI)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt)
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
SemaSYCL & SYCL()
Definition Sema.h:1556
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:1768
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition SemaDecl.cpp:689
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
[module.interface]p6: A redeclaration of an entity X is implicitly exported if X was introduced by an...
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
AvailabilityAttr * mergeAndInferAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, const IdentifierInfo *IIEnvironment, const IdentifierInfo *InferredPlatformII)
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ASTContext & Context
Definition Sema.h:1304
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD)
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:228
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
llvm::DenseMap< IdentifierInfo *, PendingPragmaInfo > PendingExportedNames
Definition Sema.h:2360
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement)
void * SkippedDefinitionContext
Definition Sema.h:4441
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
SemaObjC & ObjC()
Definition Sema.h:1516
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1371
void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record)
Emit diagnostic warnings for placeholder members.
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition SemaDecl.cpp:81
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
PragmaStack< bool > StrictGuardStackCheckStack
Definition Sema.h:2075
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition Sema.h:3628
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
ASTContext & getASTContext() const
Definition Sema.h:935
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
void CheckCoroutineWrapper(FunctionDecl *FD)
bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS=nullptr)
isCurrentClassName - Determine whether the identifier II is the name of the class type currently bein...
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method)
Check whether 'this' shows up in the type of a static member function after the (naturally empty) cv-...
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
PragmaStack< StringLiteral * > ConstSegStack
Definition Sema.h:2071
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:777
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition SemaDecl.cpp:713
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord)
Add gsl::Pointer attribute to std::container::iterator.
Definition SemaAttr.cpp:112
void mergeVisibilityType(Decl *D, SourceLocation Loc, VisibilityAttr::VisibilityType Type)
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
void ProcessPragmaWeak(Scope *S, Decl *D)
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1208
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:1773
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:12271
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8413
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition SemaAttr.cpp:838
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
void PushFunctionScope()
Enter a new function scope.
Definition Sema.cpp:2492
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:4659
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD)
void addImplicitCallingConvAbiTag(FunctionDecl *FD)
Attach the ABI tag a standard calling convention variant requires, as an implicit abi_tag attribute.
FPOptions & getCurFPFeatures()
Definition Sema.h:930
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition Sema.cpp:2510
void PopCompoundScope()
Definition Sema.cpp:2643
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:14548
@ UPPC_EnumeratorValue
The enumerator value.
Definition Sema.h:14551
@ UPPC_Initializer
An initializer.
Definition Sema.h:14563
@ UPPC_FriendDeclaration
A friend declaration.
Definition Sema.h:14557
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14536
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14575
@ UPPC_DeclarationQualifier
A declaration qualifier.
Definition Sema.h:14560
@ UPPC_DataMemberType
The type of a data member.
Definition Sema.h:14539
@ UPPC_BitFieldWidth
The size of a bit-field.
Definition Sema.h:14542
const LangOptions & getLangOpts() const
Definition Sema.h:928
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:2604
SourceLocation CurInitSegLoc
Definition Sema.h:2114
void inferLifetimeBoundAttribute(FunctionDecl *FD)
Add [[clang:lifetimebound]] attr for std:: functions and methods.
Definition SemaAttr.cpp:238
ModularFormatAttr * mergeModularFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *ModularImplFn, StringRef ImplName, MutableArrayRef< StringRef > Aspects)
bool currentModuleIsHeaderUnit() const
Is the module scope we are in a C++ Header Unit?
Definition Sema.h:3645
SemaOpenACC & OpenACC()
Definition Sema.h:1521
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:1303
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor, bool IsCopy=false)
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2279
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:1302
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:2719
bool isReachable(const NamedDecl *D)
Determine whether a declaration is reachable.
Definition Sema.h:15674
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr, FnBodyKind BodyKind=FnBodyKind::Other)
SemaHLSL & HLSL()
Definition Sema.h:1481
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization, bool DeclIsDefn)
Perform semantic checking of a new function declaration.
CXXRecordDecl * getStdBadAlloc() const
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
PragmaClangSection PragmaClangRelroSection
Definition Sema.h:1848
SemaRISCV & RISCV()
Definition Sema.h:1546
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:15860
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:217
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:1561
void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based n...
PragmaStack< AlignPackInfo > AlignPackStack
Definition Sema.h:2060
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7007
PragmaStack< StringLiteral * > BSSSegStack
Definition Sema.h:2070
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
DeclContext * getCurLexicalContext() const
Definition Sema.h:1141
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl)
CheckOverloadedOperatorDeclaration - Check whether the declaration of this overloaded operator is wel...
bool hasExplicitCallingConv(QualType T)
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition SemaDecl.cpp:912
void ExitDeclaratorContext(Scope *S)
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
void CheckConstructor(CXXConstructorDecl *Constructor)
CheckConstructor - Checks a fully-formed constructor for well-formedness, issuing any diagnostics req...
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMemberKind CSM)
Diagnose why the specified class does not have a trivial special member of the given kind.
llvm::SmallSetVector< Decl *, 4 > DeclsToCheckForDeferredDiags
Function or variable declarations to be checked for whether the deferred diagnostics should be emitte...
Definition Sema.h:4836
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1339
void PushCompoundScope(bool IsStmtExpr)
Definition Sema.cpp:2638
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:7004
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method)
Check whether 'this' shows up in the attributes of the given static member function.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:648
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:15668
llvm::MapVector< IdentifierInfo *, AsmLabelAttr * > ExtnameUndeclaredIdentifiers
ExtnameUndeclaredIdentifiers - Identifiers contained in #pragma redefine_extname before declared.
Definition Sema.h:3611
StringLiteral * CurInitSeg
Last section used with pragma init_seg.
Definition Sema.h:2113
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9922
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:1444
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
SemaOpenCL & OpenCL()
Definition Sema.h:1526
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:1747
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:3642
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:14079
SourceManager & getSourceManager() const
Definition Sema.h:933
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_enum attribute.
Definition Sema.h:3585
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:1849
@ NTCUK_Destruct
Definition Sema.h:4156
@ NTCUK_Init
Definition Sema.h:4155
@ NTCUK_Copy
Definition Sema.h:4157
FormatMatchesAttr * mergeFormatMatchesAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, StringLiteral *FormatStr)
PragmaClangSection PragmaClangDataSection
Definition Sema.h:1846
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:6801
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".
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15623
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
void ProcessPragmaExport(DeclaratorDecl *newDecl)
bool CheckImmediateEscalatingFunctionDefinition(FunctionDecl *FD, const sema::FunctionScopeInfo *FSI)
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:2659
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:6562
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:641
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
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.
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:276
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:1305
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4722
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7011
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1344
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition Sema.cpp:1894
@ FirstDecl
Parsing the first decl in a TU.
Definition Sema.h:9951
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:1536
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition SemaStmt.cpp:76
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:1263
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:3635
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
llvm::SmallPtrSet< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition Sema.h:3615
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8368
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)
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:1306
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:929
FPOptions CurFPFeatures
Definition Sema.h:1300
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)
void LoadExternalExtnameUndeclaredIdentifiers()
Load pragma redefine_extname'd undeclared identifiers from the external source.
Definition Sema.cpp:1112
PragmaStack< StringLiteral * > DataSegStack
Definition Sema.h:2069
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:11704
@ TPC_ClassTemplateMember
Definition Sema.h:11702
@ TPC_FunctionTemplate
Definition Sema.h:11701
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11705
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:1586
bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl)
Certain globally-unique variables might be accidentally duplicated if built into multiple shared libr...
bool isMainFileLoc(SourceLocation Loc) const
Determines whether the given source location is in the main file and we're in a context where we shou...
Definition Sema.cpp:979
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:6578
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)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool AllowTypoCorrection=true)
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 isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
Determine whether a tag-like declaration found by lookup can be redeclared in the given scope.
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...
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:3604
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2262
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
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, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
PragmaClangSection PragmaClangBSSSection
Definition Sema.h:1845
Decl * ActOnDeclarator(Scope *S, Declarator &D)
@ AbstractVariableType
Definition Sema.h:6325
@ AbstractReturnType
Definition Sema.h:6323
@ AbstractFieldType
Definition Sema.h:6326
@ AbstractIvarType
Definition Sema.h:6327
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:8417
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:6459
void CheckVariableDeclarationType(VarDecl *NewVD)
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1296
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:3581
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:1571
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Format, int FormatIdx, int FirstArg)
IdentifierResolver IdResolver
Definition Sema.h:3527
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:2650
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition SemaDecl.cpp:732
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:149
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:8376
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Sema.h:1295
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:3883
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:1451
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:365
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8712
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.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
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:1819
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:1990
StringRef getString() const
Definition Expr.h:1887
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3852
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition Decl.h:4138
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition Decl.cpp:4994
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:3948
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3934
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
bool isStruct() const
Definition Decl.h:4060
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition Decl.cpp:4966
bool isUnion() const
Definition Decl.h:4063
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:4085
TagKind getTagKind() const
Definition Decl.h:4052
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3998
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:4770
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition Decl.cpp:5932
void setStmt(Stmt *S)
Definition Decl.cpp:5954
Represents a declaration of a type.
Definition Decl.h:3648
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:1468
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:890
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:2766
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8410
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:8421
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isStructureType() const
Definition Type.cpp:809
bool isDependentSizedArrayType() const
Definition TypeBase.h:8795
bool isVoidType() const
Definition TypeBase.h:9048
bool isBooleanType() const
Definition TypeBase.h:9185
bool isFunctionReferenceType() const
Definition TypeBase.h:8750
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2413
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9235
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3239
bool isIncompleteArrayType() const
Definition TypeBase.h:8783
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9351
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:8779
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9215
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8775
bool isFunctionPointerType() const
Definition TypeBase.h:8743
bool isPointerType() const
Definition TypeBase.h:8676
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9342
bool isReferenceType() const
Definition TypeBase.h:8700
bool isHLSLIntangibleType() const
Definition Type.cpp:5710
bool isScalarType() const
Definition TypeBase.h:9154
bool isVariableArrayType() const
Definition TypeBase.h:8787
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:883
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9170
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:8940
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2976
bool isOpenCLSpecificType() const
Definition TypeBase.h:8976
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2629
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isHalfType() const
Definition TypeBase.h:9052
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2233
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2777
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2853
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9228
bool isAtomicType() const
Definition TypeBase.h:8868
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isObjCIdType() const
Definition TypeBase.h:8888
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2877
bool isObjCObjectType() const
Definition TypeBase.h:8859
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9191
bool isEventT() const
Definition TypeBase.h:8924
bool isPointerOrReferenceType() const
Definition TypeBase.h:8680
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2653
bool isFunctionType() const
Definition TypeBase.h:8672
bool isObjCObjectPointerType() const
Definition TypeBase.h:8855
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8761
bool isFloatingType() const
Definition Type.cpp:2515
bool isAnyPointerType() const
Definition TypeBase.h:8684
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition Type.cpp:2238
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:784
bool isNullPtrType() const
Definition TypeBase.h:9085
bool isRecordType() const
Definition TypeBase.h:8803
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5701
bool isUnionType() const
Definition Type.cpp:849
bool isReserveIDT() const
Definition TypeBase.h:8936
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5312
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3802
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5831
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3747
QualType getUnderlyingType() const
Definition Decl.h:3752
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition Decl.h:3758
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6253
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:2329
Opcode getOpcode() const
Definition Expr.h:2324
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2384
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1071
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1075
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1127
UnionParsedType ConstructorName
When Kind == IK_ConstructorName, the class-name of the type whose constructor is being referenced.
Definition DeclSpec.h:1079
SourceLocation EndLocation
The location of the last token that describes this unqualified-id.
Definition DeclSpec.h:1100
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1248
UnionParsedType DestructorName
When Kind == IK_DestructorName, the type referred to by the class-name.
Definition DeclSpec.h:1083
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1097
UnionParsedTemplateTy TemplateName
When Kind == IK_DeductionGuideName, the parsed template-name.
Definition DeclSpec.h:1086
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1067
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1091
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:463
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:3429
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3493
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3487
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:713
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5658
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5652
Represents a variable declaration or definition.
Definition Decl.h:933
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2780
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2131
void setCXXForRangeDecl(bool FRD)
Definition Decl.h:1550
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:1594
TLSKind getTLSKind() const
Definition Decl.cpp:2148
bool hasInit() const
Definition Decl.cpp:2378
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1477
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:2240
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2170
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:2441
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2237
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1603
bool isCXXCondDecl() const
Definition Decl.h:1636
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:944
@ ParenListInit
Parenthesized list-initialization (C++20)
Definition Decl.h:947
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:941
void setStorageClass(StorageClass SC)
Definition Decl.cpp:2143
void setPreviousDeclInSameBlockScope(bool Same)
Definition Decl.h:1618
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1248
void assignAddressSpace(const ASTContext &Ctxt, LangAS AS)
Apply a deduced address space, if one isn't already set.
Definition Decl.cpp:2912
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2346
void setInlineSpecified()
Definition Decl.h:1583
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1215
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2742
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition Decl.h:1366
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition Decl.h:1180
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1576
ThreadStorageClassSpecifier getTSCSpec() const
Definition Decl.h:1184
const Expr * getInit() const
Definition Decl.h:1392
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1239
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1191
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition Decl.cpp:2409
void setConstexpr(bool IC)
Definition Decl.h:1597
@ TLS_Static
TLS with a known-constant initializer.
Definition Decl.h:956
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:959
void setInit(Expr *I)
Definition Decl.cpp:2457
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition Decl.cpp:2325
@ TentativeDefinition
This declaration is a tentative definition.
Definition Decl.h:1322
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1319
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1325
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition Decl.cpp:2785
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition Decl.cpp:2225
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1275
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1175
void setImplicitlyInline()
Definition Decl.h:1588
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition Decl.h:1501
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition Decl.h:1613
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:2689
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1286
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:2749
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1382
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
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:4057
Expr * getSizeExpr() const
Definition TypeBase.h:4071
Captures information about a #pragma weak directive.
Definition Weak.h:25
ValueDecl * getVariable() const
Definition ScopeInfo.h:676
bool isVariableCapture() const
Definition ScopeInfo.h:651
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:687
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:746
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:733
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:722
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:709
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:756
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1099
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:738
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:499
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:255
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:887
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition ScopeInfo.h:918
ParmVarDecl * ExplicitObjectParameter
Definition ScopeInfo.h:884
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition ScopeInfo.h:951
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:872
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:880
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:875
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:899
Provides information about an attempted template argument deduction, whose success or failure was des...
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)
Top level wrappers for InstallAPI frontend operations.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_struct
Definition Specifiers.h:82
@ TST_class
Definition Specifiers.h:83
@ TST_union
Definition Specifiers.h:81
@ TST_enum
Definition Specifiers.h:80
@ TST_interface
Definition Specifiers.h:84
ImplicitTypenameContext
Definition DeclSpec.h:1935
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:828
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:820
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:213
@ 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
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_Internal
Definition Linkage.h:73
CUDAFunctionTarget
Definition Cuda.h:65
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:36
@ 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:272
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ 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:598
@ TemplateTemplateArgument
Definition Sema.h:607
NonTrivialCUnionContext
Definition Sema.h:526
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition Sema.h:622
@ None
Don't merge availability attributes at all.
Definition Sema.h:624
@ Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition Sema.h:630
@ OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition Sema.h:636
@ Redeclaration
Merge availability attributes for a redeclaration, which requires an exact match.
Definition Sema.h:627
@ ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition Sema.h:633
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1035
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1033
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1027
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1025
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1023
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1029
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1019
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1021
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_protected
Definition Specifiers.h:126
@ AS_none
Definition Specifiers.h:128
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:249
@ SC_Auto
Definition Specifiers.h:257
@ SC_PrivateExtern
Definition Specifiers.h:254
@ SC_Extern
Definition Specifiers.h:252
@ SC_Register
Definition Specifiers.h:258
@ SC_Static
Definition Specifiers.h:253
@ SC_None
Definition Specifiers.h:251
@ TSCS_thread_local
C++11 thread_local.
Definition Specifiers.h:242
@ TSCS_unspecified
Definition Specifiers.h:237
@ TSCS__Thread_local
C11 _Thread_local.
Definition Specifiers.h:245
@ TSCS___thread
GNU __thread.
Definition Specifiers.h:239
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:341
@ SD_Static
Static storage duration.
Definition Specifiers.h:342
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:909
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OffsetOfKind
Definition Sema.h:610
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
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:445
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6032
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6037
@ Struct
The "struct" keyword.
Definition TypeBase.h:6034
@ Class
The "class" keyword.
Definition TypeBase.h:6043
@ Union
The "union" keyword.
Definition TypeBase.h:6040
@ Enum
The "enum" keyword.
Definition TypeBase.h:6046
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:4453
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Deduced
The normal deduced case.
Definition TypeBase.h:1818
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2019
@ 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:136
MultiVersionKind
Definition Decl.h:2009
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:1305
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:374
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:428
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_X86StdCall
Definition Specifiers.h:281
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ Enumerator
Enumerator value with fixed underlying type.
Definition Sema.h:834
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:6028
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6018
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6021
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6025
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1775
@ 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:89
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:1472
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition DeclSpec.h:1623
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1447
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1406
const IdentifierInfo * Ident
Definition DeclSpec.h:1378
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1287
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1707
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:1688
FunctionTypeInfo Fun
Definition DeclSpec.h:1686
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition DeclSpec.h:1735
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
Extra information about a function prototype.
Definition TypeBase.h:5494
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition TypeBase.h:5521
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition TypeBase.h:6071
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3493
An element in an Objective-C dictionary literal.
Definition ExprObjC.h:294
Expr * Value
The value of the dictionary element.
Definition ExprObjC.h:299
Expr * Key
The key for the dictionary element.
Definition ExprObjC.h:296
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:59
std::vector< std::string > Features
Definition TargetInfo.h:60
Describes how types, statements, expressions, and declarations should be printed.
ValueType CurrentValue
Definition Sema.h:2045
SourceLocation CurrentPragmaLocation
Definition Sema.h:2046
bool CheckSameAsPrevious
Definition Sema.h:360
NamedDecl * Previous
Definition Sema.h:361
NamedDecl * New
Definition Sema.h:362
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:1059
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1050